DEV Community

waisam
waisam Subscriber

Posted on

Checking a WAV file before it goes on a USB drive: a tiny Python validator

Some devices are strict about the audio files they accept. A car that plays a custom lock sound is a good example: it wants one file, with an exact name, in a specific format, under a size limit. When the file is wrong, you usually get no error message, just silence. So I wrote a small Python script that checks a file before it ever reaches the USB drive.

The rules I check

For a Tesla custom lock sound, the requirements are well documented:

  • the file is named exactly LockChime.wav
  • it is a real WAV container with uncompressed PCM audio
  • it is smaller than 1 MB
  • it sits in the root of the drive

The standard library's wave module handles most of this. It only opens PCM WAV files, which is exactly the check we want.

The script

import os, sys, wave

def check(path):
    problems = []
    name = os.path.basename(path)
    if name != "LockChime.wav":
        problems.append(f"name is {name!r}, expected 'LockChime.wav'")
    size = os.path.getsize(path)
    if size >= 1_000_000:
        problems.append(f"size is {size} bytes, must be under 1 MB")
    try:
        with wave.open(path, "rb") as w:
            ch, width, rate, frames = w.getnchannels(), w.getsampwidth(), w.getframerate(), w.getnframes()
            print(f"{ch} ch, {width*8}-bit, {rate} Hz, {frames/rate:.2f} s")
            if ch != 1:
                problems.append("stereo file: mono is smaller and plays the same on one speaker")
    except wave.Error as e:
        problems.append(f"not a PCM WAV ({e}); was an MP3 renamed?")
    return problems

if __name__ == "__main__":
    issues = check(sys.argv[1])
    print("OK" if not issues else "\n".join("- " + i for i in issues))
Enter fullscreen mode Exit fullscreen mode

Why each check matters

The name check catches the classic LockChime.wav.wav problem that hidden extensions cause on Windows and macOS. The wave module raises an error for compressed or non-WAV data, which catches renamed MP3s. The size check is simple arithmetic: 16-bit mono at 44.1 kHz is about 88 KB per second, so anything longer than roughly 11 seconds will not fit.

Checking the drive itself

You can extend the script to take a mount point instead of a file, then confirm LockChime.wav is in the root and that there is only one. Checking the file system type is platform-specific; on Linux, reading /proc/mounts works, and you are looking for vfat, exfat, ext3 or ext4 rather than ntfs.

Where this came from

I help run Tesla Lock Sounds, a free library where every download is already a PCM WAV under 1 MB named LockChime.wav. Even with consistent files, the most common support question is still "why doesn't my car see it?", and nearly every answer is one of the checks above. The car side matters too: custom lock sounds need the external pedestrian warning speaker and supported software, which no script can fix.

Top comments (0)