如何在Python中将立体声WAV转换为单声道?
我不想使用其他应用程序(比如 sox)——我想用纯 Python 来完成这个。安装需要的 Python 库是可以的。
3 个回答
0
我能想到的最简单的方法就是使用PyTorch的mean函数,下面的例子就演示了这一点。
import torch
import torchaudio
def stereo_to_mono_convertor(signal):
# If there is more than 1 channel in your audio
if signal.shape[0] > 1:
# Do a mean of all channels and keep it in one channel
signal = torch.mean(signal, dim=0, keepdim=True)
return signal
# Load audio as tensor
waveform, sr = torchaudio.load('audio.wav')
# Convert it to mono channel
waveform = stereo_to_mono_convertor(waveform)
59
我在维护一个开源库,叫做 pydub,这个库让处理音频变得非常简单。
from pydub import AudioSegment
sound = AudioSegment.from_wav("/path/to/file.wav")
sound = sound.set_channels(1)
sound.export("/output/path.wav", format="wav")
有一点需要注意:这个库使用了 ffmpeg 来处理音频格式的转换,但如果你只使用 wav 格式的话,它可以完全用 Python 来实现。
11
如果WAV文件是用PCM编码的,那么你可以使用wave
这个库。你需要打开源文件和目标文件,读取音频样本,然后把不同的声道取个平均值,最后把结果写出来。