我正在尝试解决一个已接受的问题,演示如何使用PyAudio创建一个蜂鸣声。奇怪的是,我发现了很多错误。不幸的是,我从未以编程方式将任何音频数据发送到声卡,因此我不知道如何摆脱错误。互联网不是很有帮助,你能给我一些建议吗?谢谢!
这是一个简短的程序,可以在StackOverflow上的答案中提供哔声:
#!/usr/bin/python3
import math
from pyaudio import PyAudio # sudo apt-get install python{,3}-pyaudio
def sine_tone(frequency:float, duration:float, volume:int = 1, sampleRate:int = 22050):
n_samples = int(sampleRate * duration)
restframes = n_samples % sampleRate
p = PyAudio()
stream = p.open(format=p.get_format_from_width(1), # 8bit
channels=1, # mono
rate=sampleRate,
output=True)
s = lambda t: volume * math.sin(2 * math.pi * frequency * t / sampleRate)
samples = (int(s(t) * 0x7f + 0x80) for t in range(n_samples))
if duration < 1:
stream.write(bytes(bytearray(samples)))
else:
for buf in zip(*[samples]*sampleRate): # write several samples at a time
stream.write(bytes(bytearray(buf)))
# fill remainder of frameset with silence
stream.write(b'\x80' * restframes)
stream.stop_stream()
stream.close()
p.terminate()
#
sine_tone(500, 1)
这将导致以下输出行全部发送到STDERR:
ALSA lib pcm_dmix.c:1052:(snd_pcm_dmix_open) unable to open slave
ALSA lib pcm_dmix.c:1052:(snd_pcm_dmix_open) unable to open slave
ALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear
ALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfe
ALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side
ALSA lib pcm_route.c:867:(find_matching_chmap) Found no matching channel map
ALSA lib pcm_dmix.c:1052:(snd_pcm_dmix_open) unable to open slave
Cannot connect to server socket err = No such file or directory
Cannot connect to server request channel
jack server is not running or cannot be started
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for 4294967295, skipping unlock
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for 4294967295, skipping unlock
为什么msgs被发送到STDERR,它们是什么意思,我怎么能摆脱它们(因为声音似乎按预期播放)?