I'm trying to use librosa to split a stereo audio file into separate channels. I have this code:
import librosa
audio, sr = librosa.load('trumpet.wav')
canal_esquerdo, canal_direito = librosa.effects.split_stereo(audio)
librosa.output.write_wav('canal_esquerdo.wav', canal_esquerdo, sr)
librosa.output.write_wav('canal_direito.wav', canal_direito, sr)
but I get an error:
Traceback (most recent call last):
File "audio.py", line 7, in <module>
canal_esquerdo, canal_direito = librosa.effects.split_stereo(audio)
AttributeError: module 'librosa.effects' has no attribute 'split_stereo'
What is wrong with the code? Is it possible to split the audio using librosa? If so, how?
The error message means exactly what it says: .split_stereo
isn't provided here, so that can't be used to split the stereo file.
To find out how to use a library for a given task, do not guess at names for functions - search for, and read, documentation.
The relevant documentation explains:
When working with multi-channel signals, we may choose to skip the default down-mixing step by specifying
mono=False
in the call tolibrosa.load
, as in the following:import librosa # Get the "high-quality" multi-channel version of # an example track filename = librosa.ex('trumpet', hq=True) # Load as multi-channel data y_stereo, sr = librosa.load(filename, mono=False)
The resulting object now has two dimensions instead of one, with
y_stereo.shape == (N_channels, N_samples)
. This way, we can access the first channel asy_stereo[0]
, the second channel asy_stereo[1]
, and so on if there are more than two channels.
That is to say: librosa does not treat "stereo" as a special case; as long as mono=False
is specified, loading just gives a 2d array representing however many channels there are.
Adapting that to the original code:
import librosa
audio, sr = librosa.load('trumpet.wav', mono=False)
librosa.output.write_wav('canal_esquerdo.wav', audio[0], sr)
librosa.output.write_wav('canal_direito.wav', audio[1], sr)