PageRenderTime 52ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/WavFile.php

https://github.com/kppf/securimage
PHP | 1864 lines | 1098 code | 327 blank | 439 comment | 290 complexity | 2323d9ab9bef747e33800c1b8b54ed16 MD5 | raw file
Possible License(s): BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. // error_reporting(E_ALL); ini_set('display_errors', 1); // uncomment this line for debugging
  3. /**
  4. * Project: PHPWavUtils: Classes for creating, reading, and manipulating WAV files in PHP<br />
  5. * File: WavFile.php<br />
  6. *
  7. * Copyright (c) 2012, Drew Phillips
  8. * All rights reserved.
  9. *
  10. * Redistribution and use in source and binary forms, with or without modification,
  11. * are permitted provided that the following conditions are met:
  12. *
  13. * - Redistributions of source code must retain the above copyright notice,
  14. * this list of conditions and the following disclaimer.
  15. * - Redistributions in binary form must reproduce the above copyright notice,
  16. * this list of conditions and the following disclaimer in the documentation
  17. * and/or other materials provided with the distribution.
  18. *
  19. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  20. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  21. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  22. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  23. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  24. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  25. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  26. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  27. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  28. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  29. * POSSIBILITY OF SUCH DAMAGE.
  30. *
  31. * Any modifications to the library should be indicated clearly in the source code
  32. * to inform users that the changes are not a part of the original software.<br /><br />
  33. *
  34. * @copyright 2012 Drew Phillips
  35. * @author Drew Phillips <drew@drew-phillips.com>
  36. * @author Paul Voegler <http://www.voegler.eu/>
  37. * @version 1.0 (October 2012)
  38. * @package PHPWavUtils
  39. * @license BSD License
  40. *
  41. * Changelog:
  42. *
  43. * 1.0 (10/2/2012)
  44. * - Fix insertSilence() creating invalid block size
  45. *
  46. * 1.0 RC1 (4/20/2012)
  47. * - Initial release candidate
  48. * - Supports 8, 16, 24, 32 bit PCM, 32-bit IEEE FLOAT, Extensible Format
  49. * - Support for 18 channels of audio
  50. * - Ability to read an offset from a file to reduce memory footprint with large files
  51. * - Single-pass audio filter processing
  52. * - Highly accurate and efficient mix and normalization filters (http://www.voegler.eu/pub/audio/)
  53. * - Utility filters for degrading audio, and inserting silence
  54. *
  55. * 0.6 (4/12/2012)
  56. * - Support 8, 16, 24, 32 bit and PCM float (Paul Voegler)
  57. * - Add normalize filter, misc improvements and fixes (Paul Voegler)
  58. * - Normalize parameters to filter() to use filter constants as array indices
  59. * - Add option to mix filter to loop the target file if the source is longer
  60. *
  61. * 0.5 (4/3/2012)
  62. * - Fix binary pack routine (Paul Voegler)
  63. * - Add improved mixing function (Paul Voegler)
  64. *
  65. */
  66. class WavFile
  67. {
  68. /*%******************************************************************************************%*/
  69. // Class constants
  70. /** @var int Filter flag for mixing two files */
  71. const FILTER_MIX = 0x01;
  72. /** @var int Filter flag for normalizing audio data */
  73. const FILTER_NORMALIZE = 0x02;
  74. /** @var int Filter flag for degrading audio data */
  75. const FILTER_DEGRADE = 0x04;
  76. /** @var int Maximum number of channels */
  77. const MAX_CHANNEL = 18;
  78. /** @var int Maximum sample rate */
  79. const MAX_SAMPLERATE = 192000;
  80. /** Channel Locations for ChannelMask */
  81. const SPEAKER_DEFAULT = 0x000000;
  82. const SPEAKER_FRONT_LEFT = 0x000001;
  83. const SPEAKER_FRONT_RIGHT = 0x000002;
  84. const SPEAKER_FRONT_CENTER = 0x000004;
  85. const SPEAKER_LOW_FREQUENCY = 0x000008;
  86. const SPEAKER_BACK_LEFT = 0x000010;
  87. const SPEAKER_BACK_RIGHT = 0x000020;
  88. const SPEAKER_FRONT_LEFT_OF_CENTER = 0x000040;
  89. const SPEAKER_FRONT_RIGHT_OF_CENTER = 0x000080;
  90. const SPEAKER_BACK_CENTER = 0x000100;
  91. const SPEAKER_SIDE_LEFT = 0x000200;
  92. const SPEAKER_SIDE_RIGHT = 0x000400;
  93. const SPEAKER_TOP_CENTER = 0x000800;
  94. const SPEAKER_TOP_FRONT_LEFT = 0x001000;
  95. const SPEAKER_TOP_FRONT_CENTER = 0x002000;
  96. const SPEAKER_TOP_FRONT_RIGHT = 0x004000;
  97. const SPEAKER_TOP_BACK_LEFT = 0x008000;
  98. const SPEAKER_TOP_BACK_CENTER = 0x010000;
  99. const SPEAKER_TOP_BACK_RIGHT = 0x020000;
  100. const SPEAKER_ALL = 0x03FFFF;
  101. /** @var int PCM Audio Format */
  102. const WAVE_FORMAT_PCM = 0x0001;
  103. /** @var int IEEE FLOAT Audio Format */
  104. const WAVE_FORMAT_IEEE_FLOAT = 0x0003;
  105. /** @var int EXTENSIBLE Audio Format - actual audio format defined by SubFormat */
  106. const WAVE_FORMAT_EXTENSIBLE = 0xFFFE;
  107. /** @var string PCM Audio Format SubType - LE hex representation of GUID {00000001-0000-0010-8000-00AA00389B71} */
  108. const WAVE_SUBFORMAT_PCM = "0100000000001000800000aa00389b71";
  109. /** @var string IEEE FLOAT Audio Format SubType - LE hex representation of GUID {00000003-0000-0010-8000-00AA00389B71} */
  110. const WAVE_SUBFORMAT_IEEE_FLOAT = "0300000000001000800000aa00389b71";
  111. /*%******************************************************************************************%*/
  112. // Properties
  113. /** @var array Log base modifier lookup table for a given threshold (in 0.05 steps) used by normalizeSample.
  114. * Adjusts the slope (1st derivative) of the log function at the threshold to 1 for a smooth transition
  115. * from linear to logarithmic amplitude output. */
  116. protected static $LOOKUP_LOGBASE = array(
  117. 2.513, 2.667, 2.841, 3.038, 3.262,
  118. 3.520, 3.819, 4.171, 4.589, 5.093,
  119. 5.711, 6.487, 7.483, 8.806, 10.634,
  120. 13.302, 17.510, 24.970, 41.155, 96.088
  121. );
  122. /** @var int The actual physical file size */
  123. protected $_actualSize;
  124. /** @var int The size of the file in RIFF header */
  125. protected $_chunkSize;
  126. /** @var int The size of the "fmt " chunk */
  127. protected $_fmtChunkSize;
  128. /** @var int The size of the extended "fmt " data */
  129. protected $_fmtExtendedSize;
  130. /** @var int The size of the "fact" chunk */
  131. protected $_factChunkSize;
  132. /** @var int Size of the data chunk */
  133. protected $_dataSize;
  134. /** @var int Size of the data chunk in the opened wav file */
  135. protected $_dataSize_fp;
  136. /** @var int Does _dataSize really reflect strlen($_samples)? Case when a wav file is read with readData = false */
  137. protected $_dataSize_valid;
  138. /** @var int Starting offset of data chunk */
  139. protected $_dataOffset;
  140. /** @var int The audio format - WavFile::WAVE_FORMAT_* */
  141. protected $_audioFormat;
  142. /** @var int The audio subformat - WavFile::WAVE_SUBFORMAT_* */
  143. protected $_audioSubFormat;
  144. /** @var int Number of channels in the audio file */
  145. protected $_numChannels;
  146. /** @var int The channel mask */
  147. protected $_channelMask;
  148. /** @var int Samples per second */
  149. protected $_sampleRate;
  150. /** @var int Number of bits per sample */
  151. protected $_bitsPerSample;
  152. /** @var int Number of valid bits per sample */
  153. protected $_validBitsPerSample;
  154. /** @var int NumChannels * BitsPerSample/8 */
  155. protected $_blockAlign;
  156. /** @var int Number of sample blocks */
  157. protected $_numBlocks;
  158. /** @var int Bytes per second */
  159. protected $_byteRate;
  160. /** @var string Binary string of samples */
  161. protected $_samples;
  162. /** @var resource The file pointer used for reading wavs from file or memory */
  163. protected $_fp;
  164. /*%******************************************************************************************%*/
  165. // Special methods
  166. /**
  167. * WavFile Constructor.
  168. *
  169. * <code>
  170. * $wav1 = new WavFile(2, 44100, 16); // new wav with 2 channels, at 44100 samples/sec and 16 bits per sample
  171. * $wav2 = new WavFile('./audio/sound.wav'); // open and read wav file
  172. * </code>
  173. *
  174. * @param string|int $numChannelsOrFileName (Optional) If string, the filename of the wav file to open. The number of channels otherwise. Defaults to 1.
  175. * @param int|bool $sampleRateOrReadData (Optional) If opening a file and boolean, decides whether to read the data chunk or not. Defaults to true. The sample rate in samples per second otherwise. 8000 = standard telephone, 16000 = wideband telephone, 32000 = FM radio and 44100 = CD quality. Defaults to 8000.
  176. * @param int $bitsPerSample (Optional) The number of bits per sample. Has to be 8, 16 or 24 for PCM audio or 32 for IEEE FLOAT audio. 8 = telephone, 16 = CD and 24 or 32 = studio quality. Defaults to 8.
  177. * @throws WavFormatException
  178. * @throws WavFileException
  179. */
  180. public function __construct($numChannelsOrFileName = null, $sampleRateOrReadData = null, $bitsPerSample = null)
  181. {
  182. $this->_actualSize = 44;
  183. $this->_chunkSize = 36;
  184. $this->_fmtChunkSize = 16;
  185. $this->_fmtExtendedSize = 0;
  186. $this->_factChunkSize = 0;
  187. $this->_dataSize = 0;
  188. $this->_dataSize_fp = 0;
  189. $this->_dataSize_valid = true;
  190. $this->_dataOffset = 44;
  191. $this->_audioFormat = self::WAVE_FORMAT_PCM;
  192. $this->_audioSubFormat = null;
  193. $this->_numChannels = 1;
  194. $this->_channelMask = self::SPEAKER_DEFAULT;
  195. $this->_sampleRate = 8000;
  196. $this->_bitsPerSample = 8;
  197. $this->_validBitsPerSample = 8;
  198. $this->_blockAlign = 1;
  199. $this->_numBlocks = 0;
  200. $this->_byteRate = 8000;
  201. $this->_samples = '';
  202. $this->_fp = null;
  203. if (is_string($numChannelsOrFileName)) {
  204. $this->openWav($numChannelsOrFileName, is_bool($sampleRateOrReadData) ? $sampleRateOrReadData : true);
  205. } else {
  206. $this->setNumChannels(is_null($numChannelsOrFileName) ? 1 : $numChannelsOrFileName)
  207. ->setSampleRate(is_null($sampleRateOrReadData) ? 8000 : $sampleRateOrReadData)
  208. ->setBitsPerSample(is_null($bitsPerSample) ? 8 : $bitsPerSample);
  209. }
  210. }
  211. public function __destruct() {
  212. if (is_resource($this->_fp)) $this->closeWav();
  213. }
  214. public function __clone() {
  215. $this->_fp = null;
  216. }
  217. /**
  218. * Output the wav file headers and data.
  219. *
  220. * @return string The encoded file.
  221. */
  222. public function __toString()
  223. {
  224. return $this->makeHeader() .
  225. $this->getDataSubchunk();
  226. }
  227. /*%******************************************************************************************%*/
  228. // Static methods
  229. /**
  230. * Unpacks a single binary sample to numeric value.
  231. *
  232. * @param string $sampleBinary (Required) The sample to decode.
  233. * @param int $bitDepth (Optional) The bits per sample to decode. If omitted, derives it from the length of $sampleBinary.
  234. * @return int|float The numeric sample value. Float for 32-bit samples. Returns null for unsupported bit depths.
  235. */
  236. public static function unpackSample($sampleBinary, $bitDepth = null)
  237. {
  238. if ($bitDepth === null) {
  239. $bitDepth = strlen($sampleBinary) * 8;
  240. }
  241. switch ($bitDepth) {
  242. case 8:
  243. // unsigned char
  244. return ord($sampleBinary);
  245. case 16:
  246. // signed short, little endian
  247. $data = unpack('v', $sampleBinary);
  248. $sample = $data[1];
  249. if ($sample >= 0x8000) {
  250. $sample -= 0x10000;
  251. }
  252. return $sample;
  253. case 24:
  254. // 3 byte packed signed integer, little endian
  255. $data = unpack('C3', $sampleBinary);
  256. $sample = $data[1] | ($data[2] << 8) | ($data[3] << 16);
  257. if ($sample >= 0x800000) {
  258. $sample -= 0x1000000;
  259. }
  260. return $sample;
  261. case 32:
  262. // 32-bit float
  263. $data = unpack('f', $sampleBinary);
  264. return $data[1];
  265. default:
  266. return null;
  267. }
  268. }
  269. /**
  270. * Packs a single numeric sample to binary.
  271. *
  272. * @param int|float $sample (Required) The sample to encode. Has to be within valid range for $bitDepth. Float values only for 32 bits.
  273. * @param int $bitDepth (Required) The bits per sample to encode with.
  274. * @return string The encoded binary sample. Returns null for unsupported bit depths.
  275. */
  276. public static function packSample($sample, $bitDepth)
  277. {
  278. switch ($bitDepth) {
  279. case 8:
  280. // unsigned char
  281. return chr($sample);
  282. case 16:
  283. // signed short, little endian
  284. if ($sample < 0) {
  285. $sample += 0x10000;
  286. }
  287. return pack('v', $sample);
  288. case 24:
  289. // 3 byte packed signed integer, little endian
  290. if ($sample < 0) {
  291. $sample += 0x1000000;
  292. }
  293. return pack('C3', $sample & 0xff, ($sample >> 8) & 0xff, ($sample >> 16) & 0xff);
  294. case 32:
  295. // 32-bit float
  296. return pack('f', $sample);
  297. default:
  298. return null;
  299. }
  300. }
  301. /**
  302. * Unpacks a binary sample block to numeric values.
  303. *
  304. * @param string $sampleBlock (Required) The binary sample block (all channels).
  305. * @param int $bitDepth (Required) The bits per sample to decode.
  306. * @param int $numChannels (Optional) The number of channels to decode. If omitted, derives it from the length of $sampleBlock and $bitDepth.
  307. * @return array The sample values as an array of integers of floats for 32 bits. First channel is array index 1.
  308. */
  309. public static function unpackSampleBlock($sampleBlock, $bitDepth, $numChannels = null) {
  310. $sampleBytes = $bitDepth / 8;
  311. if ($numChannels === null) {
  312. $numChannels = strlen($sampleBlock) / $sampleBytes;
  313. }
  314. $samples = array();
  315. for ($i = 0; $i < $numChannels; $i++) {
  316. $sampleBinary = substr($sampleBlock, $i * $sampleBytes, $sampleBytes);
  317. $samples[$i + 1] = self::unpackSample($sampleBinary, $bitDepth);
  318. }
  319. return $samples;
  320. }
  321. /**
  322. * Packs an array of numeric channel samples to a binary sample block.
  323. *
  324. * @param array $samples (Required) The array of channel sample values. Expects float values for 32 bits and integer otherwise.
  325. * @param int $bitDepth (Required) The bits per sample to encode with.
  326. * @return string The encoded binary sample block.
  327. */
  328. public static function packSampleBlock($samples, $bitDepth) {
  329. $sampleBlock = '';
  330. foreach($samples as $sample) {
  331. $sampleBlock .= self::packSample($sample, $bitDepth);
  332. }
  333. return $sampleBlock;
  334. }
  335. /**
  336. * Normalizes a float audio sample. Maximum input range assumed for compression is [-2, 2].
  337. * See http://www.voegler.eu/pub/audio/ for more information.
  338. *
  339. * @param float $sampleFloat (Required) The float sample to normalize.
  340. * @param float $threshold (Required) The threshold or gain factor for normalizing the amplitude. <ul>
  341. * <li> >= 1 - Normalize by multiplying by the threshold (boost - positive gain). <br />
  342. * A value of 1 in effect means no normalization (and results in clipping). </li>
  343. * <li> <= -1 - Normalize by dividing by the the absolute value of threshold (attenuate - negative gain). <br />
  344. * A factor of 2 (-2) is about 6dB reduction in volume.</li>
  345. * <li> [0, 1) - (open inverval - not including 1) - The threshold
  346. * above which amplitudes are comressed logarithmically. <br />
  347. * e.g. 0.6 to leave amplitudes up to 60% "as is" and compress above. </li>
  348. * <li> (-1, 0) - (open inverval - not including -1 and 0) - The threshold
  349. * above which amplitudes are comressed linearly. <br />
  350. * e.g. -0.6 to leave amplitudes up to 60% "as is" and compress above. </li></ul>
  351. * @return float The normalized sample.
  352. **/
  353. public static function normalizeSample($sampleFloat, $threshold) {
  354. // apply positive gain
  355. if ($threshold >= 1) {
  356. return $sampleFloat * $threshold;
  357. }
  358. // apply negative gain
  359. if ($threshold <= -1) {
  360. return $sampleFloat / -$threshold;
  361. }
  362. $sign = $sampleFloat < 0 ? -1 : 1;
  363. $sampleAbs = abs($sampleFloat);
  364. // logarithmic compression
  365. if ($threshold >= 0 && $threshold < 1 && $sampleAbs > $threshold) {
  366. $loga = self::$LOOKUP_LOGBASE[(int)($threshold * 20)]; // log base modifier
  367. return $sign * ($threshold + (1 - $threshold) * log(1 + $loga * ($sampleAbs - $threshold) / (2 - $threshold)) / log(1 + $loga));
  368. }
  369. // linear compression
  370. $thresholdAbs = abs($threshold);
  371. if ($threshold > -1 && $threshold < 0 && $sampleAbs > $thresholdAbs) {
  372. return $sign * ($thresholdAbs + (1 - $thresholdAbs) / (2 - $thresholdAbs) * ($sampleAbs - $thresholdAbs));
  373. }
  374. // else ?
  375. return $sampleFloat;
  376. }
  377. /*%******************************************************************************************%*/
  378. // Getter and Setter methods for properties
  379. public function getActualSize() {
  380. return $this->_actualSize;
  381. }
  382. protected function setActualSize($actualSize = null) {
  383. if (is_null($actualSize)) {
  384. $this->_actualSize = 8 + $this->_chunkSize; // + "RIFF" header (ID + size)
  385. } else {
  386. $this->_actualSize = $actualSize;
  387. }
  388. return $this;
  389. }
  390. public function getChunkSize() {
  391. return $this->_chunkSize;
  392. }
  393. protected function setChunkSize($chunkSize = null) {
  394. if (is_null($chunkSize)) {
  395. $this->_chunkSize = 4 + // "WAVE" chunk
  396. 8 + $this->_fmtChunkSize + // "fmt " subchunk
  397. ($this->_factChunkSize > 0 ? 8 + $this->_factChunkSize : 0) + // "fact" subchunk
  398. 8 + $this->_dataSize + // "data" subchunk
  399. ($this->_dataSize & 1); // padding byte
  400. } else {
  401. $this->_chunkSize = $chunkSize;
  402. }
  403. $this->setActualSize();
  404. return $this;
  405. }
  406. public function getFmtChunkSize() {
  407. return $this->_fmtChunkSize;
  408. }
  409. protected function setFmtChunkSize($fmtChunkSize = null) {
  410. if (is_null($fmtChunkSize)) {
  411. $this->_fmtChunkSize = 16 + $this->_fmtExtendedSize;
  412. } else {
  413. $this->_fmtChunkSize = $fmtChunkSize;
  414. }
  415. $this->setChunkSize() // implicit setActualSize()
  416. ->setDataOffset();
  417. return $this;
  418. }
  419. public function getFmtExtendedSize() {
  420. return $this->_fmtExtendedSize;
  421. }
  422. protected function setFmtExtendedSize($fmtExtendedSize = null) {
  423. if (is_null($fmtExtendedSize)) {
  424. if ($this->_audioFormat == self::WAVE_FORMAT_EXTENSIBLE) {
  425. $this->_fmtExtendedSize = 2 + 22; // extension size for WAVE_FORMAT_EXTENSIBLE
  426. } elseif ($this->_audioFormat != self::WAVE_FORMAT_PCM) {
  427. $this->_fmtExtendedSize = 2 + 0; // empty extension
  428. } else {
  429. $this->_fmtExtendedSize = 0; // no extension, only for WAVE_FORMAT_PCM
  430. }
  431. } else {
  432. $this->_fmtExtendedSize = $fmtExtendedSize;
  433. }
  434. $this->setFmtChunkSize(); // implicit setSize(), setActualSize(), setDataOffset()
  435. return $this;
  436. }
  437. public function getFactChunkSize() {
  438. return $this->_factChunkSize;
  439. }
  440. protected function setFactChunkSize($factChunkSize = null) {
  441. if (is_null($factChunkSize)) {
  442. if ($this->_audioFormat != self::WAVE_FORMAT_PCM) {
  443. $this->_factChunkSize = 4;
  444. } else {
  445. $this->_factChunkSize = 0;
  446. }
  447. } else {
  448. $this->_factChunkSize = $factChunkSize;
  449. }
  450. $this->setChunkSize() // implicit setActualSize()
  451. ->setDataOffset();
  452. return $this;
  453. }
  454. public function getDataSize() {
  455. return $this->_dataSize;
  456. }
  457. protected function setDataSize($dataSize = null) {
  458. if (is_null($dataSize)) {
  459. $this->_dataSize = strlen($this->_samples);
  460. } else {
  461. $this->_dataSize = $dataSize;
  462. }
  463. $this->setChunkSize() // implicit setActualSize()
  464. ->setNumBlocks();
  465. $this->_dataSize_valid = true;
  466. return $this;
  467. }
  468. public function getDataOffset() {
  469. return $this->_dataOffset;
  470. }
  471. protected function setDataOffset($dataOffset = null) {
  472. if (is_null($dataOffset)) {
  473. $this->_dataOffset = 8 + // "RIFF" header (ID + size)
  474. 4 + // "WAVE" chunk
  475. 8 + $this->_fmtChunkSize + // "fmt " subchunk
  476. ($this->_factChunkSize > 0 ? 8 + $this->_factChunkSize : 0) + // "fact" subchunk
  477. 8; // "data" subchunk
  478. } else {
  479. $this->_dataOffset = $dataOffset;
  480. }
  481. return $this;
  482. }
  483. public function getAudioFormat() {
  484. return $this->_audioFormat;
  485. }
  486. protected function setAudioFormat($audioFormat = null) {
  487. if (is_null($audioFormat)) {
  488. if (($this->_bitsPerSample <= 16 || $this->_bitsPerSample == 32)
  489. && $this->_validBitsPerSample == $this->_bitsPerSample
  490. && $this->_channelMask == self::SPEAKER_DEFAULT
  491. && $this->_numChannels <= 2) {
  492. if ($this->_bitsPerSample <= 16) {
  493. $this->_audioFormat = self::WAVE_FORMAT_PCM;
  494. } else {
  495. $this->_audioFormat = self::WAVE_FORMAT_IEEE_FLOAT;
  496. }
  497. } else {
  498. $this->_audioFormat = self::WAVE_FORMAT_EXTENSIBLE;
  499. }
  500. } else {
  501. $this->_audioFormat = $audioFormat;
  502. }
  503. $this->setAudioSubFormat()
  504. ->setFactChunkSize() // implicit setSize(), setActualSize(), setDataOffset()
  505. ->setFmtExtendedSize(); // implicit setFmtChunkSize(), setSize(), setActualSize(), setDataOffset()
  506. return $this;
  507. }
  508. public function getAudioSubFormat() {
  509. return $this->_audioSubFormat;
  510. }
  511. protected function setAudioSubFormat($audioSubFormat = null) {
  512. if (is_null($audioSubFormat)) {
  513. if ($this->_bitsPerSample == 32) {
  514. $this->_audioSubFormat = self::WAVE_SUBFORMAT_IEEE_FLOAT; // 32 bits are IEEE FLOAT in this class
  515. } else {
  516. $this->_audioSubFormat = self::WAVE_SUBFORMAT_PCM; // 8, 16 and 24 bits are PCM in this class
  517. }
  518. } else {
  519. $this->_audioSubFormat = $audioSubFormat;
  520. }
  521. return $this;
  522. }
  523. public function getNumChannels() {
  524. return $this->_numChannels;
  525. }
  526. public function setNumChannels($numChannels) {
  527. if ($numChannels < 1 || $numChannels > self::MAX_CHANNEL) {
  528. throw new WavFileException('Unsupported number of channels. Only up to ' . self::MAX_CHANNEL . ' channels are supported.');
  529. } elseif ($this->_samples !== '') {
  530. trigger_error('Wav already has sample data. Changing the number of channels does not convert and may corrupt the data.', E_USER_NOTICE);
  531. }
  532. $this->_numChannels = (int)$numChannels;
  533. $this->setAudioFormat() // implicit setAudioSubFormat(), setFactChunkSize(), setFmtExtendedSize(), setFmtChunkSize(), setSize(), setActualSize(), setDataOffset()
  534. ->setByteRate()
  535. ->setBlockAlign(); // implicit setNumBlocks()
  536. return $this;
  537. }
  538. public function getChannelMask() {
  539. return $this->_channelMask;
  540. }
  541. public function setChannelMask($channelMask = self::SPEAKER_DEFAULT) {
  542. if ($channelMask != 0) {
  543. // count number of set bits - Hamming weight
  544. $c = (int)$channelMask;
  545. $n = 0;
  546. while ($c > 0) {
  547. $n += $c & 1;
  548. $c >>= 1;
  549. }
  550. if ($n != $this->_numChannels || (((int)$channelMask | self::SPEAKER_ALL) != self::SPEAKER_ALL)) {
  551. throw new WavFileException('Invalid channel mask. The number of channels does not match the number of locations in the mask.');
  552. }
  553. }
  554. $this->_channelMask = (int)$channelMask;
  555. $this->setAudioFormat(); // implicit setAudioSubFormat(), setFactChunkSize(), setFmtExtendedSize(), setFmtChunkSize(), setSize(), setActualSize(), setDataOffset()
  556. return $this;
  557. }
  558. public function getSampleRate() {
  559. return $this->_sampleRate;
  560. }
  561. public function setSampleRate($sampleRate) {
  562. if ($sampleRate < 1 || $sampleRate > self::MAX_SAMPLERATE) {
  563. throw new WavFileException('Invalid sample rate.');
  564. } elseif ($this->_samples !== '') {
  565. trigger_error('Wav already has sample data. Changing the sample rate does not convert the data and may yield undesired results.', E_USER_NOTICE);
  566. }
  567. $this->_sampleRate = (int)$sampleRate;
  568. $this->setByteRate();
  569. return $this;
  570. }
  571. public function getBitsPerSample() {
  572. return $this->_bitsPerSample;
  573. }
  574. public function setBitsPerSample($bitsPerSample) {
  575. if (!in_array($bitsPerSample, array(8, 16, 24, 32))) {
  576. throw new WavFileException('Unsupported bits per sample. Only 8, 16, 24 and 32 bits are supported.');
  577. } elseif ($this->_samples !== '') {
  578. trigger_error('Wav already has sample data. Changing the bits per sample does not convert and may corrupt the data.', E_USER_NOTICE);
  579. }
  580. $this->_bitsPerSample = (int)$bitsPerSample;
  581. $this->setValidBitsPerSample() // implicit setAudioFormat(), setAudioSubFormat(), setFmtChunkSize(), setFactChunkSize(), setSize(), setActualSize(), setDataOffset()
  582. ->setByteRate()
  583. ->setBlockAlign(); // implicit setNumBlocks()
  584. return $this;
  585. }
  586. public function getValidBitsPerSample() {
  587. return $this->_validBitsPerSample;
  588. }
  589. protected function setValidBitsPerSample($validBitsPerSample = null) {
  590. if (is_null($validBitsPerSample)) {
  591. $this->_validBitsPerSample = $this->_bitsPerSample;
  592. } else {
  593. if ($validBitsPerSample < 1 || $validBitsPerSample > $this->_bitsPerSample) {
  594. throw new WavFileException('ValidBitsPerSample cannot be greater than BitsPerSample.');
  595. }
  596. $this->_validBitsPerSample = (int)$validBitsPerSample;
  597. }
  598. $this->setAudioFormat(); // implicit setAudioSubFormat(), setFactChunkSize(), setFmtExtendedSize(), setFmtChunkSize(), setSize(), setActualSize(), setDataOffset()
  599. return $this;
  600. }
  601. public function getBlockAlign() {
  602. return $this->_blockAlign;
  603. }
  604. protected function setBlockAlign($blockAlign = null) {
  605. if (is_null($blockAlign)) {
  606. $this->_blockAlign = $this->_numChannels * $this->_bitsPerSample / 8;
  607. } else {
  608. $this->_blockAlign = $blockAlign;
  609. }
  610. $this->setNumBlocks();
  611. return $this;
  612. }
  613. public function getNumBlocks()
  614. {
  615. return $this->_numBlocks;
  616. }
  617. protected function setNumBlocks($numBlocks = null) {
  618. if (is_null($numBlocks)) {
  619. $this->_numBlocks = (int)($this->_dataSize / $this->_blockAlign); // do not count incomplete sample blocks
  620. } else {
  621. $this->_numBlocks = $numBlocks;
  622. }
  623. return $this;
  624. }
  625. public function getByteRate() {
  626. return $this->_byteRate;
  627. }
  628. protected function setByteRate($byteRate = null) {
  629. if (is_null($byteRate)) {
  630. $this->_byteRate = $this->_sampleRate * $this->_numChannels * $this->_bitsPerSample / 8;
  631. } else {
  632. $this->_byteRate = $byteRate;
  633. }
  634. return $this;
  635. }
  636. public function getSamples() {
  637. return $this->_samples;
  638. }
  639. public function setSamples(&$samples = '') {
  640. if (strlen($samples) % $this->_blockAlign != 0) {
  641. throw new WavFileException('Incorrect samples size. Has to be a multiple of BlockAlign.');
  642. }
  643. $this->_samples = $samples;
  644. $this->setDataSize(); // implicit setSize(), setActualSize(), setNumBlocks()
  645. return $this;
  646. }
  647. /*%******************************************************************************************%*/
  648. // Getters
  649. public function getMinAmplitude()
  650. {
  651. if ($this->_bitsPerSample == 8) {
  652. return 0;
  653. } elseif ($this->_bitsPerSample == 32) {
  654. return -1.0;
  655. } else {
  656. return -(1 << ($this->_bitsPerSample - 1));
  657. }
  658. }
  659. public function getZeroAmplitude()
  660. {
  661. if ($this->_bitsPerSample == 8) {
  662. return 0x80;
  663. } elseif ($this->_bitsPerSample == 32) {
  664. return 0.0;
  665. } else {
  666. return 0;
  667. }
  668. }
  669. public function getMaxAmplitude()
  670. {
  671. if($this->_bitsPerSample == 8) {
  672. return 0xFF;
  673. } elseif($this->_bitsPerSample == 32) {
  674. return 1.0;
  675. } else {
  676. return (1 << ($this->_bitsPerSample - 1)) - 1;
  677. }
  678. }
  679. /*%******************************************************************************************%*/
  680. // Wave file methods
  681. /**
  682. * Construct a wav header from this object. Includes "fact" chunk in necessary.
  683. * http://www-mmsp.ece.mcgill.ca/documents/audioformats/wave/wave.html
  684. *
  685. * @return string The RIFF header data.
  686. */
  687. public function makeHeader()
  688. {
  689. // reset and recalculate
  690. $this->setAudioFormat(); // implicit setAudioSubFormat(), setFactChunkSize(), setFmtExtendedSize(), setFmtChunkSize(), setSize(), setActualSize(), setDataOffset()
  691. $this->setNumBlocks();
  692. // RIFF header
  693. $header = pack('N', 0x52494646); // ChunkID - "RIFF"
  694. $header .= pack('V', $this->getChunkSize()); // ChunkSize
  695. $header .= pack('N', 0x57415645); // Format - "WAVE"
  696. // "fmt " subchunk
  697. $header .= pack('N', 0x666d7420); // SubchunkID - "fmt "
  698. $header .= pack('V', $this->getFmtChunkSize()); // SubchunkSize
  699. $header .= pack('v', $this->getAudioFormat()); // AudioFormat
  700. $header .= pack('v', $this->getNumChannels()); // NumChannels
  701. $header .= pack('V', $this->getSampleRate()); // SampleRate
  702. $header .= pack('V', $this->getByteRate()); // ByteRate
  703. $header .= pack('v', $this->getBlockAlign()); // BlockAlign
  704. $header .= pack('v', $this->getBitsPerSample()); // BitsPerSample
  705. if($this->getFmtExtendedSize() == 24) {
  706. $header .= pack('v', 22); // extension size = 24 bytes, cbSize: 24 - 2 = 22 bytes
  707. $header .= pack('v', $this->getValidBitsPerSample()); // ValidBitsPerSample
  708. $header .= pack('V', $this->getChannelMask()); // ChannelMask
  709. $header .= pack('H32', $this->getAudioSubFormat()); // SubFormat
  710. } elseif ($this->getFmtExtendedSize() == 2) {
  711. $header .= pack('v', 0); // extension size = 2 bytes, cbSize: 2 - 2 = 0 bytes
  712. }
  713. // "fact" subchunk
  714. if ($this->getFactChunkSize() == 4) {
  715. $header .= pack('N', 0x66616374); // SubchunkID - "fact"
  716. $header .= pack('V', 4); // SubchunkSize
  717. $header .= pack('V', $this->getNumBlocks()); // SampleLength (per channel)
  718. }
  719. return $header;
  720. }
  721. /**
  722. * Construct wav DATA chunk.
  723. *
  724. * @return string The DATA header and chunk.
  725. */
  726. public function getDataSubchunk()
  727. {
  728. // check preconditions
  729. if (!$this->_dataSize_valid) {
  730. $this->setDataSize(); // implicit setSize(), setActualSize(), setNumBlocks()
  731. }
  732. // create subchunk
  733. return pack('N', 0x64617461) . // SubchunkID - "data"
  734. pack('V', $this->getDataSize()) . // SubchunkSize
  735. $this->_samples . // Subchunk data
  736. ($this->getDataSize() & 1 ? chr(0) : ''); // padding byte
  737. }
  738. /**
  739. * Save the wav data to a file.
  740. *
  741. * @param string $filename (Required) The file path to save the wav to.
  742. * @throws WavFileException
  743. */
  744. public function save($filename)
  745. {
  746. $fp = @fopen($filename, 'w+b');
  747. if (!is_resource($fp)) {
  748. throw new WavFileException('Failed to open "' . $filename . '" for writing.');
  749. }
  750. fwrite($fp, $this->makeHeader());
  751. fwrite($fp, $this->getDataSubchunk());
  752. fclose($fp);
  753. return $this;
  754. }
  755. /**
  756. * Reads a wav header and data from a file.
  757. *
  758. * @param string $filename (Required) The path to the wav file to read.
  759. * @param bool $readData (Optional) If true, also read the data chunk.
  760. * @throws WavFormatException
  761. * @throws WavFileException
  762. */
  763. public function openWav($filename, $readData = true)
  764. {
  765. // check preconditions
  766. if (!file_exists($filename)) {
  767. throw new WavFileException('Failed to open "' . $filename . '". File not found.');
  768. } elseif (!is_readable($filename)) {
  769. throw new WavFileException('Failed to open "' . $filename . '". File is not readable.');
  770. } elseif (is_resource($this->_fp)) {
  771. $this->closeWav();
  772. }
  773. // open the file
  774. $this->_fp = @fopen($filename, 'rb');
  775. if (!is_resource($this->_fp)) {
  776. throw new WavFileException('Failed to open "' . $filename . '".');
  777. }
  778. // read the file
  779. return $this->readWav($readData);
  780. }
  781. /**
  782. * Close a with openWav() previously opened wav file or free the buffer of setWavData().
  783. * Not necessary if the data has been read (readData = true) already.
  784. */
  785. public function closeWav() {
  786. if (is_resource($this->_fp)) fclose($this->_fp);
  787. return $this;
  788. }
  789. /**
  790. * Set the wav file data and properties from a wav file in a string.
  791. *
  792. * @param string $data (Required) The wav file data. Passed by reference.
  793. * @param bool $free (Optional) True to free the passed $data after copying.
  794. * @throws WavFormatException
  795. * @throws WavFileException
  796. */
  797. public function setWavData(&$data, $free = true)
  798. {
  799. // check preconditions
  800. if (is_resource($this->_fp)) $this->closeWav();
  801. // open temporary stream in memory
  802. $this->_fp = @fopen('php://memory', 'w+b');
  803. if (!is_resource($this->_fp)) {
  804. throw new WavFileException('Failed to open memory stream to write wav data. Use openWav() instead.');
  805. }
  806. // prepare stream
  807. fwrite($this->_fp, $data);
  808. rewind($this->_fp);
  809. // free the passed data
  810. if ($free) $data = null;
  811. // read the stream like a file
  812. return $this->readWav(true);
  813. }
  814. /**
  815. * Read wav file from a stream.
  816. *
  817. * @param $readData (Optional) If true, also read the data chunk.
  818. * @throws WavFormatException
  819. * @throws WavFileException
  820. */
  821. protected function readWav($readData = true)
  822. {
  823. if (!is_resource($this->_fp)) {
  824. throw new WavFileException('No wav file open. Use openWav() first.');
  825. }
  826. try {
  827. $this->readWavHeader();
  828. } catch (WavFileException $ex) {
  829. $this->closeWav();
  830. throw $ex;
  831. }
  832. if ($readData) return $this->readWavData();
  833. return $this;
  834. }
  835. /**
  836. * Parse a wav header.
  837. * http://www-mmsp.ece.mcgill.ca/documents/audioformats/wave/wave.html
  838. *
  839. * @throws WavFormatException
  840. * @throws WavFileException
  841. */
  842. protected function readWavHeader()
  843. {
  844. if (!is_resource($this->_fp)) {
  845. throw new WavFileException('No wav file open. Use openWav() first.');
  846. }
  847. // get actual file size
  848. $stat = fstat($this->_fp);
  849. $actualSize = $stat['size'];
  850. $this->_actualSize = $actualSize;
  851. // read the common header
  852. $header = fread($this->_fp, 36); // minimum size of the wav header
  853. if (strlen($header) < 36) {
  854. throw new WavFormatException('Not wav format. Header too short.', 1);
  855. }
  856. // check "RIFF" header
  857. $RIFF = unpack('NChunkID/VChunkSize/NFormat', $header);
  858. if ($RIFF['ChunkID'] != 0x52494646) { // "RIFF"
  859. throw new WavFormatException('Not wav format. "RIFF" signature missing.', 2);
  860. }
  861. if ($actualSize - 8 < $RIFF['ChunkSize']) {
  862. trigger_error('"RIFF" chunk size does not match actual file size. Found ' . $RIFF['ChunkSize'] . ', expected ' . ($actualSize - 8) . '.', E_USER_NOTICE);
  863. $RIFF['ChunkSize'] = $actualSize - 8;
  864. //throw new WavFormatException('"RIFF" chunk size does not match actual file size. Found ' . $RIFF['ChunkSize'] . ', expected ' . ($actualSize - 8) . '.', 3);
  865. }
  866. if ($RIFF['Format'] != 0x57415645) { // "WAVE"
  867. throw new WavFormatException('Not wav format. "RIFF" chunk format is not "WAVE".', 4);
  868. }
  869. $this->_chunkSize = $RIFF['ChunkSize'];
  870. // check common "fmt " subchunk
  871. $fmt = unpack('NSubchunkID/VSubchunkSize/vAudioFormat/vNumChannels/'
  872. .'VSampleRate/VByteRate/vBlockAlign/vBitsPerSample',
  873. substr($header, 12));
  874. if ($fmt['SubchunkID'] != 0x666d7420) { // "fmt "
  875. throw new WavFormatException('Bad wav header. Expected "fmt " subchunk.', 11);
  876. }
  877. if ($fmt['SubchunkSize'] < 16) {
  878. throw new WavFormatException('Bad "fmt " subchunk size.', 12);
  879. }
  880. if ( $fmt['AudioFormat'] != self::WAVE_FORMAT_PCM
  881. && $fmt['AudioFormat'] != self::WAVE_FORMAT_IEEE_FLOAT
  882. && $fmt['AudioFormat'] != self::WAVE_FORMAT_EXTENSIBLE)
  883. {
  884. throw new WavFormatException('Unsupported audio format. Only PCM or IEEE FLOAT (EXTENSIBLE) audio is supported.', 13);
  885. }
  886. if ($fmt['NumChannels'] < 1 || $fmt['NumChannels'] > self::MAX_CHANNEL) {
  887. throw new WavFormatException('Invalid number of channels in "fmt " subchunk.', 14);
  888. }
  889. if ($fmt['SampleRate'] < 1 || $fmt['SampleRate'] > self::MAX_SAMPLERATE) {
  890. throw new WavFormatException('Invalid sample rate in "fmt " subchunk.', 15);
  891. }
  892. if ( ($fmt['AudioFormat'] == self::WAVE_FORMAT_PCM && !in_array($fmt['BitsPerSample'], array(8, 16, 24)))
  893. || ($fmt['AudioFormat'] == self::WAVE_FORMAT_IEEE_FLOAT && $fmt['BitsPerSample'] != 32)
  894. || ($fmt['AudioFormat'] == self::WAVE_FORMAT_EXTENSIBLE && !in_array($fmt['BitsPerSample'], array(8, 16, 24, 32))))
  895. {
  896. throw new WavFormatException('Only 8, 16 and 24-bit PCM and 32-bit IEEE FLOAT (EXTENSIBLE) audio is supported.', 16);
  897. }
  898. $blockAlign = $fmt['NumChannels'] * $fmt['BitsPerSample'] / 8;
  899. if ($blockAlign != $fmt['BlockAlign']) {
  900. trigger_error('Invalid block align in "fmt " subchunk. Found ' . $fmt['BlockAlign'] . ', expected ' . $blockAlign . '.', E_USER_NOTICE);
  901. $fmt['BlockAlign'] = $blockAlign;
  902. //throw new WavFormatException('Invalid block align in "fmt " subchunk. Found ' . $fmt['BlockAlign'] . ', expected ' . $blockAlign . '.', 17);
  903. }
  904. $byteRate = $fmt['SampleRate'] * $blockAlign;
  905. if ($byteRate != $fmt['ByteRate']) {
  906. trigger_error('Invalid average byte rate in "fmt " subchunk. Found ' . $fmt['ByteRate'] . ', expected ' . $byteRate . '.', E_USER_NOTICE);
  907. $fmt['ByteRate'] = $byteRate;
  908. //throw new WavFormatException('Invalid average byte rate in "fmt " subchunk. Found ' . $fmt['ByteRate'] . ', expected ' . $byteRate . '.', 18);
  909. }
  910. $this->_fmtChunkSize = $fmt['SubchunkSize'];
  911. $this->_audioFormat = $fmt['AudioFormat'];
  912. $this->_numChannels = $fmt['NumChannels'];
  913. $this->_sampleRate = $fmt['SampleRate'];
  914. $this->_byteRate = $fmt['ByteRate'];
  915. $this->_blockAlign = $fmt['BlockAlign'];
  916. $this->_bitsPerSample = $fmt['BitsPerSample'];
  917. // read extended "fmt " subchunk data
  918. $extendedFmt = '';
  919. if ($fmt['SubchunkSize'] > 16) {
  920. // possibly handle malformed subchunk without a padding byte
  921. $extendedFmt = fread($this->_fp, $fmt['SubchunkSize'] - 16 + ($fmt['SubchunkSize'] & 1)); // also read padding byte
  922. if (strlen($extendedFmt) < $fmt['SubchunkSize'] - 16) {
  923. throw new WavFormatException('Not wav format. Header too short.', 1);
  924. }
  925. }
  926. // check extended "fmt " for EXTENSIBLE Audio Format
  927. if ($fmt['AudioFormat'] == self::WAVE_FORMAT_EXTENSIBLE) {
  928. if (strlen($extendedFmt) < 24) {
  929. throw new WavFormatException('Invalid EXTENSIBLE "fmt " subchunk size. Found ' . $fmt['SubchunkSize'] . ', expected at least 40.', 19);
  930. }
  931. $extensibleFmt = unpack('vSize/vValidBitsPerSample/VChannelMask/H32SubFormat', substr($extendedFmt, 0, 24));
  932. if ( $extensibleFmt['SubFormat'] != self::WAVE_SUBFORMAT_PCM
  933. && $extensibleFmt['SubFormat'] != self::WAVE_SUBFORMAT_IEEE_FLOAT)
  934. {
  935. throw new WavFormatException('Unsupported audio format. Only PCM or IEEE FLOAT (EXTENSIBLE) audio is supported.', 13);
  936. }
  937. if ( ($extensibleFmt['SubFormat'] == self::WAVE_SUBFORMAT_PCM && !in_array($fmt['BitsPerSample'], array(8, 16, 24)))
  938. || ($extensibleFmt['SubFormat'] == self::WAVE_SUBFORMAT_IEEE_FLOAT && $fmt['BitsPerSample'] != 32))
  939. {
  940. throw new WavFormatException('Only 8, 16 and 24-bit PCM and 32-bit IEEE FLOAT (EXTENSIBLE) audio is supported.', 16);
  941. }
  942. if ($extensibleFmt['Size'] != 22) {
  943. trigger_error('Invaid extension size in EXTENSIBLE "fmt " subchunk.', E_USER_NOTICE);
  944. $extensibleFmt['Size'] = 22;
  945. //throw new WavFormatException('Invaid extension size in EXTENSIBLE "fmt " subchunk.', 20);
  946. }
  947. if ($extensibleFmt['ValidBitsPerSample'] != $fmt['BitsPerSample']) {
  948. trigger_error('Invaid or unsupported valid bits per sample in EXTENSIBLE "fmt " subchunk.', E_USER_NOTICE);
  949. $extensibleFmt['ValidBitsPerSample'] = $fmt['BitsPerSample'];
  950. //throw new WavFormatException('Invaid or unsupported valid bits per sample in EXTENSIBLE "fmt " subchunk.', 21);
  951. }
  952. if ($extensibleFmt['ChannelMask'] != 0) {
  953. // count number of set bits - Hamming weight
  954. $c = (int)$extensibleFmt['ChannelMask'];
  955. $n = 0;
  956. while ($c > 0) {
  957. $n += $c & 1;
  958. $c >>= 1;
  959. }
  960. if ($n != $fmt['NumChannels'] || (((int)$extensibleFmt['ChannelMask'] | self::SPEAKER_ALL) != self::SPEAKER_ALL)) {
  961. trigger_error('Invalid channel mask in EXTENSIBLE "fmt " subchunk. The number of channels does not match the number of locations in the mask.', E_USER_NOTICE);
  962. $extensibleFmt['ChannelMask'] = 0;
  963. //throw new WavFormatException('Invalid channel mask in EXTENSIBLE "fmt " subchunk. The number of channels does not match the number of locations in the mask.', 22);
  964. }
  965. }
  966. $this->_fmtExtendedSize = strlen($extendedFmt);
  967. $this->_validBitsPerSample = $extensibleFmt['ValidBitsPerSample'];
  968. $this->_channelMask = $extensibleFmt['ChannelMask'];
  969. $this->_audioSubFormat = $extensibleFmt['SubFormat'];
  970. } else {
  971. $this->_fmtExtendedSize = strlen($extendedFmt);
  972. $this->_validBitsPerSample = $fmt['BitsPerSample'];
  973. $this->_channelMask = 0;
  974. $this->_audioSubFormat = null;
  975. }
  976. // read additional subchunks until "data" subchunk is found
  977. $factSubchunk = array();
  978. $dataSubchunk = array();
  979. while (!feof($this->_fp)) {
  980. $subchunkHeader = fread($this->_fp, 8);
  981. if (strlen($subchunkHeader) < 8) {
  982. throw new WavFormatException('Missing "data" subchunk.', 101);
  983. }
  984. $subchunk = unpack('NSubchunkID/VSubchunkSize', $subchunkHeader);
  985. if ($subchunk['SubchunkID'] == 0x66616374) { // "fact"
  986. // possibly handle malformed subchunk without a padding byte
  987. $subchunkData = fread($this->_fp, $subchunk['SubchunkSize'] + ($subchunk['SubchunkSize'] & 1)); // also read padding byte
  988. if (strlen($subchunkData) < 4) {
  989. throw new WavFormatException('Invalid "fact" subchunk.', 102);
  990. }
  991. $factParams = unpack('VSampleLength', substr($subchunkData, 0, 4));
  992. $factSubchunk = array_merge($subchunk, $factParams);
  993. } elseif ($subchunk['SubchunkID'] == 0x64617461) { // "data"
  994. $dataSubchunk = $subchunk;
  995. break;
  996. } elseif ($subchunk['SubchunkID'] == 0x7761766C) { // "wavl"
  997. throw new WavFormatException('Wave List Chunk ("wavl" subchunk) is not supported.', 106);
  998. } else {
  999. // skip all other (unknown) subchunks
  1000. // possibly handle malformed subchunk without a padding byte
  1001. if ( $subchunk['SubchunkSize'] < 0
  1002. || fseek($this->_fp, $subchunk['SubchunkSize'] + ($subchunk['SubchunkSize'] & 1), SEEK_CUR) !== 0) { // also skip padding byte
  1003. throw new WavFormatException('Invalid subchunk (0x' . dechex($subchunk['SubchunkID']) . ') encountered.', 103);
  1004. }
  1005. }
  1006. }
  1007. if (empty($dataSubchunk)) {
  1008. throw new WavFormatException('Missing "data" subchunk.', 101);
  1009. }
  1010. // check "data" subchunk
  1011. $dataOffset = ftell($this->_fp);
  1012. if ($dataSubchunk['SubchunkSize'] < 0 || $actualSize - $dataOffset < $dataSubchunk['SubchunkSize']) {
  1013. trigger_error('Invalid "data" subchunk size.', E_USER_NOTICE);
  1014. $dataSubchunk['SubchunkSize'] = $actualSize - $dataOffset;
  1015. //throw new WavFormatException('Invalid "data" subchunk size.', 104);
  1016. }
  1017. $this->_dataOffset = $dataOffset;
  1018. $this->_dataSize = $dataSubchunk['SubchunkSize'];
  1019. $this->_dataSize_fp = $dataSubchunk['SubchunkSize'];
  1020. $this->_dataSize_valid = false;
  1021. $this->_samples = '';
  1022. // check "fact" subchunk
  1023. $numBlocks = (int)($dataSubchunk['SubchunkSize'] / $fmt['BlockAlign']);
  1024. if (empty($factSubchunk)) { // construct fake "fact" subchunk
  1025. $factSubchunk = array('SubchunkSize' => 0, 'SampleLength' => $numBlocks);
  1026. }
  1027. if ($factSubchunk['SampleLength'] != $numBlocks) {
  1028. trigger_error('Invalid sample length in "fact" subchunk.', E_USER_NOTICE);
  1029. $factSubchunk['SampleLength'] = $numBlocks;
  1030. //throw new WavFormatException('Invalid sample length in "fact" subchunk.', 105);
  1031. }
  1032. $this->_factChunkSize = $factSubchunk['SubchunkSize'];
  1033. $this->_numBlocks = $factSubchunk['SampleLength'];
  1034. return $this;
  1035. }
  1036. /**
  1037. * Read the wav data from the file into the buffer.
  1038. *
  1039. * @param $dataOffset (Optional) The byte offset to skip before starting to read. Must be a multiple of BlockAlign.
  1040. * @param $dataSize (Optional) The size of the data to read in bytes. Must be a multiple of BlockAlign. Defaults to all data.
  1041. * @throws WavFileException
  1042. */
  1043. public function readWavData($dataOffset = 0, $dataSize = null)
  1044. {
  1045. // check preconditions
  1046. if (!is_resource($this->_fp)) {
  1047. throw new WavFileException('No wav file open. Use openWav() first.');
  1048. }
  1049. if ($

Large files files are truncated, but you can click here to view the full file