我不想使用任何其他应用程序(例如 sox) - 我想用纯 Python 来完成此操作。安装所需的 Python 库就可以了。
我维护一个开源库,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。
wave
。打开源文件和目标文件,读取样本,对通道进行平均,然后将其写出。
我能想到的最简单的方法是使用 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)