%matplotlib inline
import seaborn
import numpy, scipy, matplotlib.pyplot as plt, IPython.display as ipd
import librosa, librosa.display
plt.rcParams['figure.figsize'] = (13, 5)
In this exercise notebook, we will segment, feature extract, and analyze audio files. Goals:
Load the audio file simple_loop.wav
into an array.
x, sr = librosa.load('audio/simple_loop.wav')
Show the sample rate:
print sr
Listen to the audio signal.
ipd.Audio(x, rate=sr)
Display the audio signal.
librosa.display.waveplot(x, sr=sr)
Compute the short-time Fourier transform:
X = librosa.stft(x)
For display purposes, compute the log amplitude of the STFT:
Xmag = librosa.logamplitude(X)
Display the spectrogram.
# Play with the parameters, including x_axis and y_axis
librosa.display.specshow(Xmag, sr=sr, x_axis='time', y_axis='log')
Find the times, in seconds, when onsets occur in the audio signal.
onset_frames = librosa.onset.onset_detect(x, sr=sr)
print onset_frames
onset_times = librosa.frames_to_time(onset_frames, sr=sr)
print onset_times
Convert the onset frames into sample indices.
onset_samples = librosa.frames_to_samples(onset_frames)
print onset_samples
Play a "beep" at each onset.
# Use the `length` parameter so the click track is the same length as the original signal
clicks = librosa.clicks(times=onset_times, length=len(x))
# Play the click track "added to" the original signal
ipd.Audio(x+clicks, rate=sr)
Save into an array, segments
, 100-ms segments beginning at each onset.
frame_sz = int(0.100*sr)
segments = numpy.array([x[i:i+frame_sz] for i in onset_samples])
Here is a function that adds 300 ms of silence onto the end of each segment and concatenates them into one signal.
Later, we will use this function to listen to each segment, perhaps sorted in a different order.
def concatenate_segments(segments, sr=22050, pad_time=0.300):
padded_segments = [numpy.concatenate([segment, numpy.zeros(int(pad_time*sr))]) for segment in segments]
return numpy.concatenate(padded_segments)
concatenated_signal = concatenate_segments(segments, sr)
Listen to the newly concatenated signal.
ipd.Audio(concatenated_signal, rate=sr)
For each segment, compute the zero crossing rate.
zcrs = [sum(librosa.core.zero_crossings(segment)) for segment in segments]
print zcrs
Use argsort
to find an index array, ind
, such that segments[ind]
is sorted by zero crossing rate.
ind = numpy.argsort(zcrs)
print ind
Sort the segments by zero crossing rate, and concatenate the sorted segments.
concatenated_signal = concatenate_segments(segments[ind], sr)
Listen to the sorted segments. What do you hear?
ipd.Audio(concatenated_signal, rate=sr)
Repeat the steps above using other features from librosa.feature
, e.g. rmse
, spectral_centroid
, spectral_bandwidth
.
Repeat the steps above for other audio files:
ls audio