我想知道是否可以将声音直接播放到 python 的输入中。我正在使用 linux,因此我正在使用 OSS、ALSA 和 Pulseaudio
问问题
3655 次
2 回答
3
你绝对可以用 python 播放(和生成)声音
这是一个生成正弦波的示例代码,打开默认的 Alsa 播放设备并通过该设备播放正弦波
#!/usr/bin/env python3
import math
import struct
import alsaaudio
from itertools import *
def sine_wave(frequency=440.0, framerate=44100, amplitude=0.5):
"""Stolen from here: http://zacharydenton.com/generate-audio-with-python/"""
period = int(framerate / frequency)
if amplitude > 1.0: amplitude = 1.0
if amplitude < 0.0: amplitude = 0.0
lookup_table = [float(amplitude) * math.sin(2.0*math.pi*float(frequency)*(float(i%period)/float(framerate))) for i in range(period)]
return (lookup_table[i%period] for i in count(0))
sound_out = alsaaudio.PCM() # open default sound output
sound_out.setchannels(1) # use only one channel of audio (aka mono)
sound_out.setrate(44100) # how many samples per second
sound_out.setformat(alsaaudio.PCM_FORMAT_FLOAT_LE) # sample format
for sample in sine_wave():
# alsa only eats binnary data
b = struct.pack("<f", sample) # convert python float to binary float
sound_out.write(b)
或者您可以将麦克风环回扬声器
#!/usr/bin/env python3
import struct
import alsaaudio
sound_out = alsaaudio.PCM() # open default sound output
sound_out.setchannels(1) # use only one channel of audio (aka mono)
sound_out.setperiodsize(5) # buffer size, default is 32
sound_in = alsaaudio.PCM(type=alsaaudio.PCM_CAPTURE) # default recording device
sound_in.setchannels(1) # use only one channel of audio (aka mono)
sound_in.setperiodsize(5) # buffer size, default is 32
while True:
sample_lenght, sample = sound_in.read()
sound_out.write(sample)
更多示例可以在 python alsaaudio 库http://pyalsaaudio.sourceforge.net/libalsaaudio.html中找到
于 2014-06-06T08:39:59.503 回答
-1
我想这取决于你在将它“放入”python 后想用它做什么。我肯定会看看 scikits.audiolab 库。如果您想绘制您正在尝试处理的任何声音的频谱图,这就是您可能使用的(我猜这就是您想要做的?)。
于 2014-06-09T11:24:04.810 回答