Using PHP to analyze and draw the waveform of audio files, the Internet is still rarely seen. In fact, as long as the specification of WAV files, using PHP fseek,fopen,fopen,pack/unpack functions, as well as the powerful GD graphics library, these are very easy. Many people may be unfamiliar with the pack/unpack function; this is actually PHP borrowed from Perl, and they provide a way to access complex binary data structures using scripting languages. My simplified program can only handle PCM-formatted riff audio files (this is also the most common WAV format), with no channels, but the bit rate (bitspersample) is best 16.
Here are the wave file format and MicroSoft Wave Soundfile format to refer to. Here is a practical example (download enlarge see)
1.? Php
2
3 function Wav_graph ($file, $f =0, $w =0)
4 {
5 Global $DATA _dir;
6
7 if (!is_file ($file)) return 0;
8 $fp = fopen ($DATA _dir. $file, ' R ');
9 $raw = fread ($fp, 36);
$str = ';
One $header = Unpack (' a4riff/vsize/a4wav/a4head/vheadsize/vpcm/vchannels/vsamplerate/vbyterate/vblockalign/ Vsamplebits ', $raw);
foreach ($header as $k => $v)
$str. = $k. ': '. $v. ';
Fseek ($fp, + $header [' headsize ']-16);
$raw = Fread ($fp, 8);
$data = Unpack (' a4data/vdatasize ', $raw);
foreach ($data as $k => $v)
$str. = $k. ': '. $v. ';
19
$b = $header [' samplebits '];
$c = $header [' channels '];
$l = $b * $c/8; Sample frame length in bytes
$s = $data [' datasize ']/$l; Total number of samples
$r = $header [' samplerate '];
if ($f) $h = POW (2, $b)/$f;
/else {$h = $f = Pow (2, $b-1)/$h;}
if ($w = = 0) $w = round ($r/1000); Default to show 1k sample frames per minute
28
Header ("Content-type:image/png");
$im = Imagecreate ($s/$w, $h * $c * 2);
Imagecolorallocate ($im, 0xFF, 0xFF, 0xff); White BG
$color = imagecolorallocate ($im, 0, 0, 255); Black
//imagestring ($im, 5, 5, 5, $STR, $color);
34
$x = 0; $y = Array (); $yn = Array ();
for ($i = 0; $i < $c; $i + +) $y [$i] = $h * $i + $h;
$n of Panax Notoginseng = $l * $W;
while (1)
39 {
if ($s = = 0) break;
if ($s < $n) $n = $s;
$samples = Fread ($fp, 1000 * $n);
if ($samples = = FALSE) break;
$packed = Unpack ("s*", $samples);
foreach ($packed as $k => $v)
46 {
$cnt = ($k-1)% ($w * $l);
if ($cnt > $c-1) continue;
$yn [$CNT] = $h * $cnt + $h-$v/$f;
Imageline ($im, $x, $y [$cnt], $x +1, $yn [$cnt], $color);
Wuyi $y [$cnt] = $yn [$cnt];
$x + +;
53}
$s-= $n;
55}
56
Imagepng ($im);
Imagedestroy ($im);
59}
60
//wav_graph (' audio2.wav ');
?>