如何在 Python 中将 WAV 从立体声转换为单声道?

问题描述 投票:0回答:3

我不想使用任何其他应用程序(例如 sox) - 我想用纯 Python 来完成此操作。安装所需的 Python 库就可以了。

python audio wav
3个回答
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
。打开源文件和目标文件,读取样本,对通道进行平均,然后将其写出。


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)
© www.soinside.com 2019 - 2024. All rights reserved.