2013-07-18 83 views
2

我用Pyaudio从我的麦克风中捕获音频并尝试使用opus编解码器对它进行编码/解码。我使用SvartalF制作的libopus绑定(https://github.com/svartalf/python-opus)。Python:PortAudio + Opus编码/解码

这里是我的代码:

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而不是chunkdata.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)有点不错,但有很多混杂的脆皮。

我在做什么错在这里?

+0

你好!我现在没有时间去支持python-opus,但是你可以为它分配和贡献,所以我可以用一个固定版本来更新PyPI回购。 – SvartalF

回答

1

这似乎是由解码方法中的python-opus中的错误引起的。

根据Opus API,opus_decode返回解码的样本数。 python绑定假设它将完全填充它传入的结果缓冲区,所以每个解码样本集都会有一个沉默。这种沉默导致低帧尺寸下的开裂和更高帧尺寸下的缺口。尽管文档没有提及任何内容,但看起来返回的数字是每个频道。

更改线路150 of opus/api/decoder.py以下修复它为我:

return array.array('h', pcm[:result*channels]).tostring() 

decode_float方法可能需要同样的变化,如果你需要使用。

-1

只需将输出减半并取第一部分即可。 通过试验和错误我发现这个解决方案令人满意。

from opus import decoder as opus_decoder 
from opus import encoder as opus_encoder 

class OpusCodec(): 
    def __init__(self, *args, **kwargs): 
     self.chunk = 960 
     self.channels = 1 
     self.rate = 48000 
     self.encoder = opus_encoder.Encoder(
      self.rate, 
      self.channels, 
      opus_encoder.APPLICATION_TYPES_MAP['voip'] 
     ) 
     self.decoder = opus_decoder.Decoder(
      self.rate, 
      self.channels, 
     ) 

    def encode(self, data, **kwargs): 
     if not 'frame_size' in kwargs: 
      kwargs['frame_size'] = self.chunk 
     out = self.encoder.encode(data, frame_size=self.chunk) 
     return out 

    def decode(self, data, **kwargs): 
     if not 'frame_size' in kwargs: 
      kwargs['frame_size'] = self.chunk 
     out = self.decoder.decode(data, **kwargs) 
     return out[0:int(len(out)/2)] # hackety hack :D