php实现将wav文件转换成图像文件并在页面中显示的方法

这篇文章主要介绍了php实现将wav文件转换成图像文件并在页面中显示的方法,涉及php中unpack、fopen、fread等方法及图形操作的相关技巧,需要的朋友可以参考下

本文实例讲述了php实现将wav文件转换成图像文件并在页面中显示的方法,分享给大家供大家参考,具体分析如下:

需求:将wav文件转换成png文件并且显示出来。

Wav_To_Png.php:

  1. <?php
  2. function wav_graph($file, $f=0, $w=0)
  3. {
  4. global $DATA_DIR;
  5. if(!is_file($file))
  6. return 0;
  7. $fp = fopen($DATA_DIR.$file, 'r');
  8. $raw = fread($fp, 36);
  9. $str = '';
  10. $header = unpack('A4Riff/VSize/A4Wav/A4Head/VHeadSize/vPCM/vChannels/VSampleRate/VByteRate/vBlockAlign/vSampleBits', $raw);
  11. foreach($header as $k=>$v)
  12. $str .= $k.': '. $v.' ';
  13. fseek($fp, 36 + $header['HeadSize'] - 16);
  14. $raw = fread($fp, 8);
  15. $data = unpack('A4Data/VDataSize', $raw);
  16. foreach($data as $k=>$v)
  17. $str .= $k.': '. $v.' ';
  18. $b = $header['SampleBits'];
  19. $c = $header['Channels'];
  20. $l = $b * $c / 8; // sample frame length in bytes
  21. $s = $data['DataSize'] / $l; // total number of samples
  22. $r = $header['SampleRate'];
  23. if($f)
  24. $h = pow(2, $b) / $f;
  25. else
  26. { $h = 200; $f = pow(2, $b - 1) / $h; }
  27. if($w == 0)
  28. $w = round($r / 1000); // default to show 1k sample frames per minute
  29. header("Content-type: image/png");
  30. $im = imagecreate($s / $w, $h * $c * 2);
  31. imagecolorallocate($im, 0xff, 0xff, 0xff); // white bg
  32. $color = imagecolorallocate($im, 0, 0, 255); // black
  33. imagestring($im, 5, 5, 5, $str, $color);
  34. $x=0; $y = array(); $yn = array();
  35. for($i = 0; $i < $c; $i++) $y[$i] = $h * $i + $h;
  36. $n = $l * $w;
  37. while(1)
  38. {
  39. if($s == 0)
  40. break;
  41. if($s < $n)
  42. $n = $s;
  43. $samples = fread($fp, 1000 * $n);
  44. if($samples === FALSE)
  45. break;
  46. $packed = unpack("s*", $samples);
  47. foreach($packed as $k=>$v)
  48. {
  49. $cnt = ($k-1) % ($w * $l) ;
  50. if( $cnt > $c - 1)
  51. continue;
  52. $yn[$cnt] = $h * $cnt + $h - $v / $f;
  53. imageline($im, $x, $y[$cnt], $x+1, $yn[$cnt], $color);
  54. $y[$cnt] = $yn[$cnt];
  55. $x++;
  56. }
  57. $s -= $n;
  58. }
  59. imagepng($im);
  60. imagedestroy($im);
  61. }
  62. wav_graph('GetWave.wav');
  63. ?>