Draw a wav file's waveform

Share your advanced PureBasic knowledge/code with the community.
Seymour Clufley
Addict
Addict
Posts: 1233
Joined: Wed Feb 28, 2007 9:13 am
Location: London

Draw a wav file's waveform

Post by Seymour Clufley »

Other people have posted code for doing this, but only with the use of external utilities. This code does it all inside PB. It relies on the WavFiles include.

The waveform will be drawn at the specified dimensions and as a transparent image. The specified colour should be 32-bit.

The procedure uses a separate procedure, GetWavFilePeaks(), to get the actual volume data. This procedure can be used independently for other purposes. It just needs a .d array and to know how many "slices" to divide the wave into (eg. how many volume levels you actually want to work with).

The "exact" flag, if set to #True, will cause the procedure to read every single sample in the wav file. If it is #False (the default), the procedure will skip samples depending on the audio duration, in order to massively reduce the processing time.

If the wav file is stereo, there are several modes available for how to handle the channels - left only, right only, average, etc. The default is "louder".

The "normalise" flag can be used to ensure the waveform occupies the whole height of the image.

Code: Select all

XIncludeFile "WavFiles.pbi"

wavfn.s = OpenFileRequester("Choose a wav","","Wav files|*.wav|",0)
If wavfn="" : End : EndIf
iw = 1600
ih = 800
img.i = GetWavFileWaveform(wavfn,iw,ih,RGBA(0,0,0,255))
win = OpenWindow(#PB_Any,0,0,iw,ih,"Waveform",#PB_Window_ScreenCentered)
g = ImageGadget(#PB_Any,0,0,iw,ih,ImageID(img))
Repeat : Delay(50) : Until GetAsyncKeyState_(#VK_ESCAPE)
JACK WEBB: "Coding in C is like sculpting a statue using only sandpaper. You can do it, but the result wouldn't be any better. So why bother? Just use the right tools and get the job done."