A memo when writing the code to display the waveform of the voice. It is easy to use librosa.display.waveplot of the library called librosa, but since an error occurs when the number of data in the audio file is large, the method of displaying using matplotlib.pyplot is also described.
The easiest way.
import librosa
def make_waveform_librosa(filename):
y, sr = librosa.load(filename)
librosa.display.waveplot(y, sr=sr)
make_waveform_librosa("test.mp3")
However, if the number of data in the audio file to be read is large, OverflowError: Exceeded cell block limit may occur and the waveform may not be displayed properly.
Since the chunk size of the agg running on the back end of matplotlib can be changed, it is possible to handle even when the number of data in the audio file is large.
import matplotlib.pyplot as plt
import matplotlib
import librosa
def make_waveform_pyplot(filename):
y, sr = librosa.load(filename)
totaltime = len(y)/sr
time_array = np.arange(0, totaltime, 1/sr)
mpl.rcParams['agg.path.chunksize'] = 100000
fig, ax = plt.subplots()
formatter = mpl.ticker.FuncFormatter(lambda s, x: time.strftime('%M:%S', time.gmtime(s)))
ax.xaxis.set_major_formatter(formatter)
ax.set_xlim(0, totaltime)
ax.set_xlabel("Time")
ax.plot(time_array, y)
plt.show()
make_waveform_pyplot("test.mp3")
The chunk size was written as follows when referring to here, so I set it to 100000 as appropriate.
### Agg rendering
### Warning: experimental, 2008/10/10
#agg.path.chunksize : 0 # 0 to disable; values in the range
# 10000 to 100000 can improve speed slightly
# and prevent an Agg rendering failure
# when plotting very large data sets,
# especially if they are very gappy.
# It may cause minor artifacts, though.
# A value of 20000 is probably a good
# starting point.
I was able to output the same thing as librosa.display.waveplot.
Since librosa.display.waveplot also uses matplotlib internally, I think that it will be possible to display it by playing with chunksize in the same way, but I think that it is necessary to play with the code of the library directly.
Recommended Posts