After some great comments in the original PHP MP3 Waveform Generator blog post, I decided to go ahead and do my best to optimize the script as much as possible. This included, as a commenter named Bruce pointed out, that it wasn’t very efficient on memory to perform a extraction of a large set of amplitude data points for the waveform only to discard them later when drawing on the canvas (given the DETAIL constant setting).
My revised script now estimates the number of amplitude points of the resulting decoded WAV file (data size) and extracts those points while at the same time plotting them onto the canvas. This eliminates the need for a second loop and reduces overall memory and performance.
UPDATE 2012-12-08: I’ve also added support for stereo (2-channel) waveform processing!
Based on a couple quick tests, the revised script reduced execution time by 20% and overall memory usage by 15%. Unfortunately the most time consuming portion of the script is still the lame resampling and decoding, but this really is a necessary evil: to take the MP3 and turn it into a usable, processable WAV file.
I also made a separate SVG version of the script which generates an SVG/XML file — this is definitely more usable for circumstances where you might not know the required dimensions of your image ahead of time. The resulting SVG can be resized any amount and will not lose quality.
In addition to optimizing the script, I’ve also added support (to both PNG and SVG versions) for generating 2-channel stereo waveforms. This can take a single MP3, split it into both left and right channels, and generate a single image with both waveforms.
These two projects have been uploaded (finally) to my github account: