gpt4 book ai didi

python - 如何保存同时播放两个轨道的wav文件?不同体积的

转载 作者:太空宇宙 更新时间:2023-11-03 15:25:47 31 4
gpt4 key购买 nike

我正在使用 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),该函数返回字符代码为 code 的字符(与 ord 相反)

关于python - 如何保存同时播放两个轨道的wav文件?不同体积的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43160498/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com