in reply to Reading WAV files

You probably want to read the header, then unpack the data based on that, it might be 8 bit or 16 bit, mono or stereo, etc. Here is a way to read the header and determine it's playlength based on byte size, number of channels, etc.
#!/usr/bin/perl -w use strict; use Fcntl; my $fnm = shift; sysopen WAV,$fnm,O_RDONLY; my $riff; sysread WAV,$riff,12; my $fmt; sysread WAV,$fmt,24; my $data; sysread WAV,$data,8; close WAV; # RIFF header: 'RIFF', long length, type='WAVE' my ($r1,$r2,$r3) = unpack "A4VA4", $riff; # WAV header, 'fmt ', long length, short unused, short channels, # long samples/second, long bytes per second, short bytes per sample, # short bits per sample my ($f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8) = unpack "A4VvvVVvv",$fmt; # DATA header, 'DATA', long length my ($d1,$d2) = unpack "A4V", $data; my $playlength = $d2/$f6; print << "EOF"; RIFF header: $r1, length $r2, type $r3 Format: $f1, length $f2, always $f3, channels $f4, sample rate $f5, bytes per second $f6, bytes per sample $f7, bits per sample $f8 Data: $d1, length $d2 Playlength: $playlength seconds EOF

I'm not really a human, but I play one on earth. flash japh

Replies are listed 'Best First'.
Re: Re: Reading WAV files
by cormanaz (Deacon) on Mar 11, 2004 at 22:54 UTC
    Thanks for all the suggestions. I was able to get it working with unpack. The header occupies bytes 0-46 of the file and from there
    read IN,$buffer,2; $value = unpack('s',$buffer);
    enclosed in a suitable loop yields the data values (for a 16-bit file).

    I never was able to find Audio-Wav on Activestate. When I search using keyword "Audio" on Komodo/VPM, it doesn't show up. I tried the same thing with command line PPM and got same result. There is Audio-(Daemon, FLAC, Play-MPG123, PSID, Radio-V4L, SID, Tools, WMA) but no Wav.

    Anyway, reading it as above is pretty straighforward so mission accomplished.