Audio Dual Channel Separation Using Python
- 2021-08-31 08:33:22
- OfStack
Some audio is a dialogue between two parties, so it may be necessary to separate the audio channels.
The sample code is as follows:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Audio dual channel separation
"""
import sys
import numpy as np
from scipy.io import wavfile
from converter import mp3_to_wav
def split_channel(wav_path, left_wav_path, right_wav_path):
"""
Channel separation
:param wav_path: wav Path of audio
:param left_wav_path: Left vocal wav Audio path
:param right_wav_path: Right vocal tract wav Audio path
:return None:
"""
try:
sample_rate, wav_data = wavfile.read(wav_path)
left = []
right = []
for item in wav_data:
left.append(item[0])
right.append(item[1])
wavfile.write(left_wav_path, sample_rate, np.array(left))
wavfile.write(right_wav_path, sample_rate, np.array(right))
except IOError as e:
print('error is %s' % str(e))
except:
print('other error', sys.exc_info())
if __name__ == '__main__':
mp3_to_wav('input/test.mp3', 'tmp/tmp.wav')
split_channel('tmp/tmp.wav', 'output/left.wav', 'output/right.wav')
A custom library is called, and code is added to converter. py:
from pydub import AudioSegment
def mp3_to_wav(source, destin):
"""
mp3 Turn wav
:param source:
:param destin:
:return None:
"""
data = AudioSegment.from_mp3(source)
data.export(destin, format='wav')
This code example can generate an wav file after two channels are separated.
Note: If the format of the source file is an wav file, the process of converting the format can be omitted.
The above is the use of Python audio dual-channel separation of the details, more information about python audio separation please pay attention to other related articles on this site!