Deutsch | English

Generating spectrograms with arecord, sox and ffmpeg/avconv

Generating spectrograms with arecord, sox and ffmpeg/avconv

2019-09-19 - Andreas Wittmann - Tags: publish

1. Create a spectrogram (Image)

The following command records a WAV file using ALSA (Device 2.0). In this example, Sox is piped into the process — which is actually unnecessary in this case — but could still be used to apply various filters to the resulting test.wav file:

arecord -D hw:2,0 -r 32000 -f S16_LE -c 1 -t wav | sox -t wav -c 1 -L -b 16 -r 32000 - test.wav

Now, using the newly created test.wav file, a spectrogram can be generated:

sox test.wav -n spectrogram -o image.png

The following command creates a WAV file using Alsa (Device 2.0). In this case, Sox is additionally piped, which is completely unnecessary here, however, Sox could still add various filters to the resulting test.wav change:

arecord -D hw:2,0 -r 32000 -f S16_LE -c 1 -t wav | sox -t wav -c 1 -L -b 16 -r 32000 - test.wav

Using the file test.wav that has just been created, a spectrogram is now generated:

sox test.wav -n spectrogram -o image.png

content.org_20180225_093605_15135M7Y.png

A similar spectrogram image can be created directly from a video file using avconv:

avconv -i test.avi -lavfi showspectrumpic=s=hd480:legend=0,format=yuv420p out.png

avconv_spec.png

2. Create a spectrogram (Video)

The following instruction creates a spectrogram from a video test.avi. This is saved as a video under the name out.avi.

screenshot_20190101_095339.png

Instead of avconv, ffmpeg could also have been used. The Debian version does not currently support all parameters here.

Alternatives with MPlayer and Sox

You can also generate a spectrogram from a video using mplayer, or a combination of mplayer and sox.

First, extract a WAV file using mplayer:

mplayer test.mp4 -ao pcm:file=/dev/stdout -vo null > test.wav

Then generate the spectrogram:

sox test.wav -n spectrogram -o test.png

3. Comparing Spectrograms

Spectrograms created this way can be directly compared. However, even with seemingly identical WAV files, this comparison can be tricky.

To make differences more visible, creating a spectrogram diff is recommended.

First, create a diff WAV file:

sox -m -v 1 source1.wav -v -1 source2.wav diff.wav

Then generate the spectrogram diff:

sox diff.wav -n spectrogram -o diff.png