如何保存同时播放两首曲目的wav文件?在不同的数量

时间:2017-04-01 18:27:46

标签: python python-2.7 audio wave

我在python中编码并使用“wave”库。 我已经设法用这个库保存新的波形文件,但没有两个声音文件重叠 - 它们将在保存时一个接一个地播放。 如果有人可以帮助如何保存文件,其中两个曲目在同时播放 在不同的音量将是伟大的。 感谢。

1 个答案:

答案 0 :(得分:0)

您可以使用pydub库(我在std lib中围绕python wave模块编写的光包装器)来完成它:

from pydub import AudioSegment

sound1 = AudioSegment.from_file("/path/to/my_sound.wav")
sound2 = AudioSegment.from_file("/path/to/another_sound.wav")

combined = sound1.overlay(sound2)

combined.export("/path/to/combined.wav", format='wav')

但如果您真的想使用wave:

这非常依赖于它们所处的格式。下面是一个假设2字节宽的小尾数样本的示例:

import wave

w1 = wave.open("/path/to/wav/1")
w2 = wave.open("/path/to/wav/2")

#get samples formatted as a string.
samples1 = w1.readframes(w1.getnframes())
samples2 = w2.readframes(w2.getnframes())

#takes every 2 bytes and groups them together as 1 sample. ("123456" -> ["12", "34", "56"])
samples1 = [samples1[i:i+2] for i in xrange(0, len(samples1), 2)]
samples2 = [samples2[i:i+2] for i in xrange(0, len(samples2), 2)]

#convert samples from strings to ints
def bin_to_int(bin):
    as_int = 0
    for char in bin[::-1]: #iterate over each char in reverse (because little-endian)
        #get the integer value of char and assign to the lowest byte of as_int, shifting the rest up
        as_int <<= 8
        as_int += ord(char) 
    return as_int

samples1 = [bin_to_int(s) for s in samples1] #['\x04\x08'] -> [0x0804]
samples2 = [bin_to_int(s) for s in samples2]

#average the samples:
samples_avg = [(s1+s2)/2 for (s1, s2) in zip(samples1, samples2)]

现在剩下要做的就是将samples_avg转换回二进制字符串并使用wave.writeframes将其写入文件。这恰恰与我们刚才所做的相反,所以不应该太难理解。对于你的int_to_bin函数,你可能会使用函数chr(code),它返回字符代码为code的字符(与ord相反)