How to reverse a WAV file

John Salamon

2024-09-03

You don’t need audacity. You don’t even need sox! In fact, I’m here to tell you that with just the coreutils (almost), you too can impress your friends and cower your foes by entirely reversing the data content of a WAV file. Behold:

cat <(head -c 44 audio.wav) <(tail -c +45 audio.wav | xxd -p -c 0 | fold -w 4 | tac | tr -d '\n' | xxd -r -p)

Now pipe that into aplay and you have yourself a nice solution for playing WAV files backwards from the command line, a task I’m sure you’re likely to encounter frequently.

The details

WAV files have a header, and then some data. This is assuming there’s a single header of 44 bytes (extracted with head, followed by some 16-bit PCM (extracted with tail). This actually works on stereo or mono, because it’s just interleaved. You might flip left and right though.

Now, I know WAV headers aren’t always exactly 44 bytes. If you cared you could parse the header, but let’s be honest, you’re a busy person trying to listen to all this stuff in reverse and you don’t have time for that. Just double the size and try again, it’ll probably work. Is there really going to be anything important in the first few hundred bytes anyway?

xxd is used to convert binary to text, so that the other utilities don’t get completely stumped, then vice versa on the other side.

fold can cut up input at a particular width. I gave it 4 hex digits (2 bytes, 16 bits, one sample).

tac is cat, but backwards. Honestly it’s the reason I’m writing this. I just found out it existed and this was the funniest thing I could think to do with it.

tr strips out the newlines that tac added in.

Finally, all of this is wrapped in a cat which concatenates the header with the reversed data. I used the <() operator, which does process substitution, which is useful if a command expects a file but you can’t be bothered to make one.

There are countless other possibilities for audio editing in this fashion, for example, chuck in a shuf and produce a random remix!