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

how to save a wav file that plays two tracks at the same time? at different volumes

我正在 python 中编码并使用 "wave" 库。 我已经设法用这个库保存新的波形文件,但没有两个声音文件重叠——保存后它们将一个接一个地播放。 如果有人可以帮助保存一个文件,其中两个曲目 同时播放 以不同的音量 会很棒。 谢谢。

您可以使用 pydub 库(我围绕 std 库中的 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),其中 returns 字符代码为 code 的字符(与 ord 相对)