某些音频是双方对话,有可能需要对音频作通道的分离。
示例代码如下:
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 """ 4 音频双通道分离 5 """ 6 import sys 7 import numpy as np 8 from scipy.io import wavfile 9 from converter import mp3_to_wav 10 11 12 def split_channel(wav_path, left_wav_path, right_wav_path): 13 """ 14 通道分离 15 :param wav_path: wav音频的路径 16 :param left_wav_path: 左声道的wav音频路径 17 :param right_wav_path: 右声道的wav音频路径 18 :return None: 19 """ 20 try: 21 sample_rate, wav_data = wavfile.read(wav_path) 22 left = [] 23 right = [] 24 for item in wav_data: 25 left.append(item[0]) 26 right.append(item[1]) 27 wavfile.write(left_wav_path, sample_rate, np.array(left)) 28 wavfile.write(right_wav_path, sample_rate, np.array(right)) 29 except IOError as e: 30 print('error is %s' % str(e)) 31 except: 32 print('other error', sys.exc_info()) 33 34 35 if __name__ == '__main__': 36 mp3_to_wav('input/test.mp3', 'tmp/tmp.wav') 37 split_channel('tmp/tmp.wav', 'output/left.wav', 'output/right.wav')
其中调用了一个自定义的库,converter.py 加入了代码:
1 from pydub import AudioSegment 2 3 4 def mp3_to_wav(source, destin): 5 """ 6 mp3 转 wav 7 :param source: 8 :param destin: 9 :return None: 10 """ 11 data = AudioSegment.from_mp3(source) 12 data.export(destin, format='wav')
本代码示例可以生成两个通道分离后的 wav 文件。
注意:如果源文件的格式是 wav 文件,可以省掉转换格式的过程。