我想知道是否可以直接在python的输入中播放声音。我正在使用linux,我正在使用OSS,ALSA和Pulseaudio
答案 0 :(得分:2)
你绝对可以用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
中找到更多示例答案 1 :(得分:-1)
我想这取决于你把它变成“python”后你想用它做什么。 我肯定会看看scikits.audiolab库。这就是你可能会使用的,如果你想绘制你正在尝试的声音的谱图(我猜这是你想要做的?)。