I just got a new Raspberry Pi 4 and am trying to write a Python program that generates a sound that's just one frequency. However, I am having a problem that I cannot hear any sound coming out of the program at all. Here is the code I am using.
import pyaudio
import numpy as np
p = pyaudio.PyAudio()
print(p.get_default_output_device_info())
volume = 1 # range [0.0, 1.0]
fs = 48000 # sampling rate, Hz, must be integer
duration = 100 # in seconds, may be float
f = 440.0 # sine frequency, Hz, may be float
# generate samples, note conversion to float32 array
samples = (np.sin(2*np.pi*np.arange(fs*duration)*f/fs)).astype(np.float32)
# for paFloat32 sample values must be in range [-1.0, 1.0]
stream = p.open(format=pyaudio.paFloat32,
channels=2,
rate=fs,
output=True)
# play. May repeat with different volume values (if done interactively)
stream.write(volume*samples)
stream.stop_stream()
stream.close()
p.terminate()
I took this code from another question on this site regarding generating the sound I mentioned. The only changes I made were to observe my device's info and to change the sampling rate to my device's default. If I did not change my sampling rate, the program would produce an error. As it is, the program simply runs indefinitely, all the while producing no sound. If I stop the program, a pop can be heard from the speakers.
Now, the Pi itself produces audio output just fine. I have tested both playing audio to HDMI and Analog, with YouTube from the browser, and playing a wav file in Python using the playsound
library.
So, I am quite confused as to why the program above produces no sound. Any insight would be appreciated. Thank you very much in advance.
EDIT: I have also noticed that the program runs indefinitely, even when I set the duration to 1 second.