我正在使用 Pyaudio 从我的麦克风中捕获音频,并尝试使用 opus 编解码器对其进行编码/解码。我正在使用 SvartalF ( https://github.com/svartalf/python-opus ) 对 libopus 的绑定。
这是我的代码:
import pyaudio
from opus import encoder, decoder
def streaming(p):
chunk = 960
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 48000
streamin = p.open(format = FORMAT,
channels = CHANNELS,
rate = RATE,
input = True,
input_device_index = 7,
frames_per_buffer = chunk)
streamout = p.open(format = FORMAT,
channels = CHANNELS,
rate = 48000,
output = True,
output_device_index = p.get_default_input_device_info()["index"],
frames_per_buffer = chunk)
enc = encoder.Encoder(RATE,CHANNELS,'voip')
dec = decoder.Decoder(RATE,CHANNELS)
data = []
for i in xrange(100):
data.append(streamin.read(chunk*2))
streamout.write(''.join(data))
encdata = []
for x in data:
encdata.append(enc.encode(x,chunk))
print "DATA LENGTH :", len(''.join(data))
print "ENCDATA LENGTH :", len(''.join(encdata))
decdata = ''
for x in encdata:
decdata += dec.decode(x,chunk)
print "DECDATA LENGTH :", len(decdata)
streamout.write(decdata)
streamin.close()
streamout.close()
p = pyaudio.PyAudio()
streaming(p)
p.terminate()
我必须输入chunk*2
而不是chunk
输入data.append(streamin.read(chunk*2))
或DECDATA LENGTH == DATA LENGTH*2
,我不知道为什么。
输出:
DATA LENGTH : 384000
ENCDATA LENGTH : 12865
DECDATA LENGTH : 384000
没有编码/解码,第一个streamout.write(''.join(data))
工作完美。使用编码/解码,streamout.write(decdata)
有点工作,但混合了很多噼啪声。
我在这里做错了什么?