PyAudio一次播放多个声音

时间:2015-02-26 13:11:42

标签: python-3.x pyaudio

如何将两个声音与PyAudio合二为一。我浏览了整个互联网,但没有人回答这个问题。我也在考虑使用audiolab或swMixer,但他们不支持Python 3.4 ...我正在考虑将它们的字节串转换为numpy数组,将它与另一个数组合并,然后转换回字符串。这可能吗?

wf1 = wave.open("YYY.wav", 'rb')
wf1 = wave.open("XXX.wav", 'rb')

p = pyaudio.PyAudio()

def callback(in_data, frame_count, time_info, status):
    data1 = wf1.readframes(frame_count)
    data2 = wf2.readframes(frame_count)

    #Here i need to mix these two byte strings together

    return (data, pyaudio.paContinue)

你是我最后的希望, 谢谢你的任何进展!

2 个答案:

答案 0 :(得分:4)

我自己找到了解决方案,这非常简单。所以我会在这里发布我的代码以帮助其他人:

wf1 = wave.open("YYY.wav", 'rb')
wf1 = wave.open("XXX.wav", 'rb')

def callback(in_data, frame_count, time_info, status):
    data1 = wf.readframes(frame_count)
    data2 = wf1.readframes(frame_count)
    decodeddata1 = numpy.fromstring(data1, numpy.int16)
    decodeddata2 = numpy.fromstring(data2, numpy.int16)
    newdata = (decodeddata1 * 0.5 + decodeddata2* 0.5).astype(numpy.int16)
    return (result.tostring(), pyaudio.paContinue)

答案 1 :(得分:1)

我用基本的约瑟夫(Josef)答案发布了一个更新版本,该版本检查声音时间是否不相同。

def callback(in_data, frame_count, time_info, status):
    data1 = wf.readframes(frame_count)
    data2 = wf_2.readframes(frame_count)
    decodeddata1 = numpy.fromstring(data1, numpy.int16)
    decodeddata2 = numpy.fromstring(data2, numpy.int16)

    if(int(decodeddata1.size)==0):
        newdata = (decodeddata2).astype(numpy.int16)
        return (newdata.tostring(), pyaudio.paContinue)     

    if(int(decodeddata2.size)==0):
        newdata = (decodeddata1).astype(numpy.int16)
        return (newdata.tostring(), pyaudio.paContinue)     

    if(int(decodeddata1.size)>int(decodeddata2.size)):
        rest = int(decodeddata1.size)-int(decodeddata2.size)
        for i in range(1,rest+1):
            decodeddata2 = numpy.append(decodeddata2,0)

    if(int(decodeddata1.size)<int(decodeddata2.size)):
        rest = int(decodeddata2.size)-int(decodeddata1.size)
        for i in range(1,rest+1):
            decodeddata1 = numpy.append(decodeddata1,0)


    newdata = (decodeddata1 + decodeddata2).astype(numpy.int16)
    return (newdata.tostring(), pyaudio.paContinue)