<p> 用Php分析并绘制音频文件的波形图,网上还是很少见到。其实只要根据wav文件的规范,用Php的fseek,fopen,fopen,pack/unpack等函数,以及强大的gd图形库,这些都是很容易的。很多人可能对pack/unpack函数不熟悉;这其实是Php借用perl的,他们提供了使用脚本语言访问复杂二进制数据结构的方法。我的这段简化的程序只能处理PCM格式的RIFF音频文件(这也是最常见的wav格式) ,不限声道,但是比特率(BitsPerSample)最好是16。</p><p> 这里有wave file format 和 MicroSoft wave soundfile format可以参考。这里是一个实际的例子(下载放大看)</p><code> 1 <?Php<br /> 2<br /> 3 function wav_graph($file, $f=0, $w=0)<br /> 4 {<br /> 5 global $DATA_DIR;<br /> 6<br /> 7 if(!is_file($file)) return 0;<br /> 8 $fp = fopen($DATA_DIR.$file, 'r');<br /> 9 $raw = fread($fp, 36);<br /> 10 $str = '';<br /> 11 $header = unpack('A4Riff/VSize/A4Wav/A4Head/VHeadSize/vPCM/vChannels/VSampleRate/VByteRate/vBlockAlign/vSampleBits', $raw);<br /> 12 foreach($header as $k=>$v)<br /> 13 $str .= $k.': '. $v.' ';<br /> 14 fseek($fp, 36 + $header['HeadSize'] - 16);<br /> 15 $raw = fread($fp, 8);<br /> 16 $data = unpack('A4Data/VDataSize', $raw);<br /> 17 foreach($data as $k=>$v)<br /> 18 $str .= $k.': '. $v.' ';<br /> 19<br /> 20 $b = $header['SampleBits'];<br /> 21 $c = $header['Channels'];<br /> 22 $l = $b * $c / 8; // sample frame length in bytes<br /> 23 $s = $data['DataSize'] / $l; // total number of samples<br /> 24 $r = $header['SampleRate'];<br /> 25 if($f) $h = pow(2, $b) / $f;<br /> 26 else { $h = 200; $f = pow(2, $b - 1) / $h; }<br /> 27 if($w == 0) $w = round($r / 1000); // default to show 1k sample frames per minute<br /> 28<br /> 29 header("Content-type: image/png");<br /> 30 $im = imagecreate($s / $w, $h * $c * 2);<br /> 31 imagecolorallocate($im, 0xff, 0xff, 0xff); // white bg<br /> 32 $color = imagecolorallocate($im, 0, 0, 255); // black<br /> 33 //imagestring($im, 5, 5, 5, $str, $color);<br /> 34<br /> 35 $x=0; $y = array(); $yn = array();<br /> 36 for($i = 0; $i < $c; $i++) $y[$i] = $h * $i + $h;<br /> 37 $n = $l * $w;<br /> 38 while(1)<br /> 39 {<br /> 40 if($s == 0) break;<br /> 41 if($s < $n) $n = $s;<br /> 42 $samples = fread($fp, 1000 * $n);<br /> 43 if($samples === FALSE) break;<br /> 44 $packed = unpack("s*", $samples);<br /> 45 foreach($packed as $k=>$v)<br /> 46 {<br /> 47 $cnt = ($k-1) % ($w * $l) ;<br /> 48 if( $cnt > $c - 1) continue;<br /> 49 $yn[$cnt] = $h * $cnt + $h - $v / $f;<br /> 50 imageline($im, $x, $y[$cnt], $x+1, $yn[$cnt], $color);<br /> 51 $y[$cnt] = $yn[$cnt];<br /> 52 $x++;<br /> 53 }<br /> 54 $s -= $n;<br /> 55 }<br /> 56<br /> 57 imagepng($im);<br /> 58 imagedestroy($im);<br /> 59 }<br /> 60<br /> 61 //wav_graph('audio2.wav');<br /> 62 ?></code></p>