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
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.
The pop means you've got some control over the speakers. Good. Maybe, your program is telling the speakers to work too quietly. Look for things that would cause that: Have you tried volume=1.0 or maybe volume=0.99? Maybe Python isn't coercing the integer 1 into the float 1.0. Double check that your samples array is populated with values of the expected range.
Answered by StevePoling on January 2, 2022
4 Asked on November 20, 2021 by mooshroom14
1 Asked on November 20, 2021 by abdulkarim-kanaan
0 Asked on November 19, 2021 by braeden-hamson
1 Asked on November 17, 2021
1 Asked on November 15, 2021 by balaji-g
2 Asked on November 15, 2021 by rdel
1 Asked on November 15, 2021 by skematic
1 Asked on November 15, 2021 by amon-green
3 Asked on November 13, 2021 by aryndin
1 Asked on November 13, 2021 by anta
1 Asked on November 11, 2021
1 Asked on November 11, 2021 by hossein-nakhaeipoor
4 Asked on November 11, 2021 by matt-lyons
2 Asked on November 11, 2021 by bassline-soup
0 Asked on November 11, 2021 by romd
4 Asked on November 8, 2021 by gilson
Get help from others!