APC Australia

HACKING WAV FILES

-

Now that we can read a WAV file header, let’s try hacking one. One of the sneaky things you can do relatively easily is change the sample rate, which changes the pitch and speed of the file when you play it back. Now, you will need to be careful doing this because any sample rate change is permanent — until you write back the original sample rate, so only use copies of WAV files and not originals.

Open up ‘modheader.py’ and you’ll see it’s not much larger than readheader.py — that’s because, again, we import the functions from the wavheader.py file. This is a perfect example of how to use Python’s ‘import’ struct — we need the functions in wavheader.py for both reading and modding WAV files, but it doesn’t make sense to code those functions twice, so we dump them into a separate file that we import as required.

But to modify the sample rate, we must also adjust the byte rate, the expected number of bytes per second — this is where we now use the numChannel­s and bitsPerSam­ple return data to calculate this and modify the appropriat­e bytes.

What’s cool about this trick is that you can modify the WAV file to whatever sample rate you like — you don’t have to stick with the typical 44.1kHz or 48kHz rates. Want the file to playback at 42.987kHz? Easy, just load in your WAV file, enter the new sample rate as ‘42987’, press the Enter key and you’re done. VLC Media Player handles any sample rate up to 192kHz, while Windows Media Player goes right up to a crazy 384kHz (yes, we tested it). However, be warned some apps may complain about whacky sample rates.

Why would you need this? Let’s say you have an Australian-standard PAL/25Hz DVD video of something originally shot at 24Hz film-rate. To convert film-rate to PAL-rate, the typical trick is to just speed up the 24Hz film to the 25Hz PAL-rate. Problem is, while the picture still looks great, the audio is now 4% too fast, becoming the ‘4% speed up’ problem and it’s a real issue with music. But if you have the audio track as a separate WAV file to listen to, you can correct this by simply changing the sample rate. For example, assuming your WAV file sample rate is 48kHz, knock it down by 4% to 46.08kHz (46,080Hz) and audio playback returns to its correct speed. Yep, you’d have to be a fussy audiophile to do this, but it works.

WORKING WITH FILES

Finally, there’s one other important thing to remember when working with files — and that’s always close a file when you’re through using it. Be a good coding citizen and work well with other apps.

Having the ability to work with files will take your Python apps to the next level. We’ve barely scratched the surface of what you can do with files, but you now have enough working tools to take advantage of local storage.

Newspapers in English

Newspapers from Australia