PageRenderTime 32ms 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
  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 ($dataOffset < 0 || $dataOffset % $this->getBlockAlign() > 0) {
  1050. throw new WavFileException('Invalid data offset. Has to be a multiple of BlockAlign.');
  1051. }
  1052. if (is_null($dataSize)) {
  1053. $dataSize = $this->_dataSize_fp - ($this->_dataSize_fp % $this->getBlockAlign()); // only read complete blocks
  1054. } elseif ($dataSize < 0 || $dataSize % $this->getBlockAlign() > 0) {
  1055. throw new WavFileException('Invalid data size to read. Has to be a multiple of BlockAlign.');
  1056. }
  1057. // skip offset
  1058. if ($dataOffset > 0 && fseek($this->_fp, $dataOffset, SEEK_CUR) !== 0) {
  1059. throw new WavFileException('Seeking to data offset failed.');
  1060. }
  1061. // read data
  1062. $this->_samples .= fread($this->_fp, $dataSize); // allow appending
  1063. $this->setDataSize(); // implicit setSize(), setActualSize(), setNumBlocks()
  1064. // close file or memory stream
  1065. return $this->closeWav();
  1066. }
  1067. /*%******************************************************************************************%*/
  1068. // Sample manipulation methods
  1069. /**
  1070. * Return a single sample block from the file.
  1071. *
  1072. * @param int $blockNum (Required) The sample block number. Zero based.
  1073. * @return string The binary sample block (all channels). Returns null if the sample block number was out of range.
  1074. */
  1075. public function getSampleBlock($blockNum)
  1076. {
  1077. // check preconditions
  1078. if (!$this->_dataSize_valid) {
  1079. $this->setDataSize(); // implicit setSize(), setActualSize(), setNumBlocks()
  1080. }
  1081. $offset = $blockNum * $this->_blockAlign;
  1082. if ($offset + $this->_blockAlign > $this->_dataSize || $offset < 0) {
  1083. return null;
  1084. }
  1085. // read data
  1086. return substr($this->_samples, $offset, $this->_blockAlign);
  1087. }
  1088. /**
  1089. * Set a single sample block. <br />
  1090. * Allows to append a sample block.
  1091. *
  1092. * @param string $sampleBlock (Required) The binary sample block (all channels).
  1093. * @param int $blockNum (Required) The sample block number. Zero based.
  1094. * @throws WavFileException
  1095. */
  1096. public function setSampleBlock($sampleBlock, $blockNum)
  1097. {
  1098. // check preconditions
  1099. $blockAlign = $this->_blockAlign;
  1100. if (!isset($sampleBlock[$blockAlign - 1]) || isset($sampleBlock[$blockAlign])) { // faster than: if (strlen($sampleBlock) != $blockAlign)
  1101. throw new WavFileException('Incorrect sample block size. Got ' . strlen($sampleBlock) . ', expected ' . $blockAlign . '.');
  1102. }
  1103. if (!$this->_dataSize_valid) {
  1104. $this->setDataSize(); // implicit setSize(), setActualSize(), setNumBlocks()
  1105. }
  1106. $numBlocks = (int)($this->_dataSize / $blockAlign);
  1107. $offset = $blockNum * $blockAlign;
  1108. if ($blockNum > $numBlocks || $blockNum < 0) { // allow appending
  1109. throw new WavFileException('Sample block number is out of range.');
  1110. }
  1111. // replace or append data
  1112. if ($blockNum == $numBlocks) {
  1113. // append
  1114. $this->_samples .= $sampleBlock;
  1115. $this->_dataSize += $blockAlign;
  1116. $this->_chunkSize += $blockAlign;
  1117. $this->_actualSize += $blockAlign;
  1118. $this->_numBlocks++;
  1119. } else {
  1120. // replace
  1121. for ($i = 0; $i < $blockAlign; ++$i) {
  1122. $this->_samples[$offset + $i] = $sampleBlock[$i];
  1123. }
  1124. }
  1125. return $this;
  1126. }
  1127. /**
  1128. * Get a float sample value for a specific sample block and channel number.
  1129. *
  1130. * @param int $blockNum (Required) The sample block number to fetch. Zero based.
  1131. * @param int $channelNum (Required) The channel number within the sample block to fetch. First channel is 1.
  1132. * @return float The float sample value. Returns null if the sample block number was out of range.
  1133. * @throws WavFileException
  1134. */
  1135. public function getSampleValue($blockNum, $channelNum)
  1136. {
  1137. // check preconditions
  1138. if ($channelNum < 1 || $channelNum > $this->_numChannels) {
  1139. throw new WavFileException('Channel number is out of range.');
  1140. }
  1141. if (!$this->_dataSize_valid) {
  1142. $this->setDataSize(); // implicit setSize(), setActualSize(), setNumBlocks()
  1143. }
  1144. $sampleBytes = $this->_bitsPerSample / 8;
  1145. $offset = $blockNum * $this->_blockAlign + ($channelNum - 1) * $sampleBytes;
  1146. if ($offset + $sampleBytes > $this->_dataSize || $offset < 0) {
  1147. return null;
  1148. }
  1149. // read binary value
  1150. $sampleBinary = substr($this->_samples, $offset, $sampleBytes);
  1151. // convert binary to value
  1152. switch ($this->_bitsPerSample) {
  1153. case 8:
  1154. // unsigned char
  1155. return (float)((ord($sampleBinary) - 0x80) / 0x80);
  1156. case 16:
  1157. // signed short, little endian
  1158. $data = unpack('v', $sampleBinary);
  1159. $sample = $data[1];
  1160. if ($sample >= 0x8000) {
  1161. $sample -= 0x10000;
  1162. }
  1163. return (float)($sample / 0x8000);
  1164. case 24:
  1165. // 3 byte packed signed integer, little endian
  1166. $data = unpack('C3', $sampleBinary);
  1167. $sample = $data[1] | ($data[2] << 8) | ($data[3] << 16);
  1168. if ($sample >= 0x800000) {
  1169. $sample -= 0x1000000;
  1170. }
  1171. return (float)($sample / 0x800000);
  1172. case 32:
  1173. // 32-bit float
  1174. $data = unpack('f', $sampleBinary);
  1175. return (float)$data[1];
  1176. default:
  1177. return null;
  1178. }
  1179. }
  1180. /**
  1181. * Sets a float sample value for a specific sample block number and channel. <br />
  1182. * Converts float values to appropriate integer values and clips properly. <br />
  1183. * Allows to append samples (in order).
  1184. *
  1185. * @param float $sampleFloat (Required) The float sample value to set. Converts float values and clips if necessary.
  1186. * @param int $blockNum (Required) The sample block number to set or append. Zero based.
  1187. * @param int $channelNum (Required) The channel number within the sample block to set or append. First channel is 1.
  1188. * @throws WavFileException
  1189. */
  1190. public function setSampleValue($sampleFloat, $blockNum, $channelNum)
  1191. {
  1192. // check preconditions
  1193. if ($channelNum < 1 || $channelNum > $this->_numChannels) {
  1194. throw new WavFileException('Channel number is out of range.');
  1195. }
  1196. if (!$this->_dataSize_valid) {
  1197. $this->setDataSize(); // implicit setSize(), setActualSize(), setNumBlocks()
  1198. }
  1199. $dataSize = $this->_dataSize;
  1200. $bitsPerSample = $this->_bitsPerSample;
  1201. $sampleBytes = $bitsPerSample / 8;
  1202. $offset = $blockNum * $this->_blockAlign + ($channelNum - 1) * $sampleBytes;
  1203. if (($offset + $sampleBytes > $dataSize && $offset != $dataSize) || $offset < 0) { // allow appending
  1204. throw new WavFileException('Sample block or channel number is out of range.');
  1205. }
  1206. // convert to value, quantize and clip
  1207. if ($bitsPerSample == 32) {
  1208. $sample = $sampleFloat < -1.0 ? -1.0 : ($sampleFloat > 1.0 ? 1.0 : $sampleFloat);
  1209. } else {
  1210. $p = 1 << ($bitsPerSample - 1); // 2 to the power of _bitsPerSample divided by 2
  1211. // project and quantize (round) float to integer values
  1212. $sample = $sampleFloat < 0 ? (int)($sampleFloat * $p - 0.5) : (int)($sampleFloat * $p + 0.5);
  1213. // clip if necessary to [-$p, $p - 1]
  1214. if ($sample < -$p) {
  1215. $sample = -$p;
  1216. } elseif ($sample > $p - 1) {
  1217. $sample = $p - 1;
  1218. }
  1219. }
  1220. // convert to binary
  1221. switch ($bitsPerSample) {
  1222. case 8:
  1223. // unsigned char
  1224. $sampleBinary = chr($sample + 0x80);
  1225. break;
  1226. case 16:
  1227. // signed short, little endian
  1228. if ($sample < 0) {
  1229. $sample += 0x10000;
  1230. }
  1231. $sampleBinary = pack('v', $sample);
  1232. break;
  1233. case 24:
  1234. // 3 byte packed signed integer, little endian
  1235. if ($sample < 0) {
  1236. $sample += 0x1000000;
  1237. }
  1238. $sampleBinary = pack('C3', $sample & 0xff, ($sample >> 8) & 0xff, ($sample >> 16) & 0xff);
  1239. break;
  1240. case 32:
  1241. // 32-bit float
  1242. $sampleBinary = pack('f', $sample);
  1243. break;
  1244. default:
  1245. $sampleBinary = null;
  1246. $sampleBytes = 0;
  1247. break;
  1248. }
  1249. // replace or append data
  1250. if ($offset == $dataSize) {
  1251. // append
  1252. $this->_samples .= $sampleBinary;
  1253. $this->_dataSize += $sampleBytes;
  1254. $this->_chunkSize += $sampleBytes;
  1255. $this->_actualSize += $sampleBytes;
  1256. $this->_numBlocks = (int)($this->_dataSize / $this->_blockAlign);
  1257. } else {
  1258. // replace
  1259. for ($i = 0; $i < $sampleBytes; ++$i) {
  1260. $this->_samples{$offset + $i} = $sampleBinary{$i};
  1261. }
  1262. }
  1263. return $this;
  1264. }
  1265. /*%******************************************************************************************%*/
  1266. // Audio processing methods
  1267. /**
  1268. * Run samples through audio processing filters.
  1269. *
  1270. * <code>
  1271. * $wav->filter(
  1272. * array(
  1273. * WavFile::FILTER_MIX => array( // Filter for mixing 2 WavFile instances.
  1274. * 'wav' => $wav2, // (Required) The WavFile to mix into this WhavFile. If no optional arguments are given, can be passed without the array.
  1275. * 'loop' => true, // (Optional) Loop the selected portion (with warping to the beginning at the end).
  1276. * 'blockOffset' => 0, // (Optional) Block number to start mixing from.
  1277. * 'numBlocks' => null // (Optional) Number of blocks to mix in or to select for looping. Defaults to the end or all data for looping.
  1278. * ),
  1279. * WavFile::FILTER_NORMALIZE => 0.6, // (Required) Normalization of (mixed) audio samples - see threshold parameter for normalizeSample().
  1280. * WavFile::FILTER_DEGRADE => 0.9 // (Required) Introduce random noise. The quality relative to the amplitude. 1 = no noise, 0 = max. noise.
  1281. * ),
  1282. * 0, // (Optional) The block number of this WavFile to start with.
  1283. * null // (Optional) The number of blocks to process.
  1284. * );
  1285. * </code>
  1286. *
  1287. * @param array $filters (Required) An array of 1 or more audio processing filters.
  1288. * @param int $blockOffset (Optional) The block number to start precessing from.
  1289. * @param int $numBlocks (Optional) The maximum number of blocks to process.
  1290. * @throws WavFileException
  1291. */
  1292. public function filter($filters, $blockOffset = 0, $numBlocks = null)
  1293. {
  1294. // check preconditions
  1295. $totalBlocks = $this->getNumBlocks();
  1296. $numChannels = $this->getNumChannels();
  1297. if (is_null($numBlocks)) $numBlocks = $totalBlocks - $blockOffset;
  1298. if (!is_array($filters) || empty($filters) || $blockOffset < 0 || $blockOffset > $totalBlocks || $numBlocks <= 0) {
  1299. // nothing to do
  1300. return $this;
  1301. }
  1302. // check filtes
  1303. $filter_mix = false;
  1304. if (array_key_exists(self::FILTER_MIX, $filters)) {
  1305. if (!is_array($filters[self::FILTER_MIX])) {
  1306. // assume the 'wav' parameter
  1307. $filters[self::FILTER_MIX] = array('wav' => $filters[self::FILTER_MIX]);
  1308. }
  1309. $mix_wav = @$filters[self::FILTER_MIX]['wav'];
  1310. if (!($mix_wav instanceof WavFile)) {
  1311. throw new WavFileException("WavFile to mix is missing or invalid.");
  1312. } elseif ($mix_wav->getSampleRate() != $this->getSampleRate()) {
  1313. throw new WavFileException("Sample rate of WavFile to mix does not match.");
  1314. } else if ($mix_wav->getNumChannels() != $this->getNumChannels()) {
  1315. throw new WavFileException("Number of channels of WavFile to mix does not match.");
  1316. }
  1317. $mix_loop = @$filters[self::FILTER_MIX]['loop'];
  1318. if (is_null($mix_loop)) $mix_loop = false;
  1319. $mix_blockOffset = @$filters[self::FILTER_MIX]['blockOffset'];
  1320. if (is_null($mix_blockOffset)) $mix_blockOffset = 0;
  1321. $mix_totalBlocks = $mix_wav->getNumBlocks();
  1322. $mix_numBlocks = @$filters[self::FILTER_MIX]['numBlocks'];
  1323. if (is_null($mix_numBlocks)) $mix_numBlocks = $mix_loop ? $mix_totalBlocks : $mix_totalBlocks - $mix_blockOffset;
  1324. $mix_maxBlock = min($mix_blockOffset + $mix_numBlocks, $mix_totalBlocks);
  1325. $filter_mix = true;
  1326. }
  1327. $filter_normalize = false;
  1328. if (array_key_exists(self::FILTER_NORMALIZE, $filters)) {
  1329. $normalize_threshold = @$filters[self::FILTER_NORMALIZE];
  1330. if (!is_null($normalize_threshold) && abs($normalize_threshold) != 1) $filter_normalize = true;
  1331. }
  1332. $filter_degrade = false;
  1333. if (array_key_exists(self::FILTER_DEGRADE, $filters)) {
  1334. $degrade_quality = @$filters[self::FILTER_DEGRADE];
  1335. if (is_null($degrade_quality)) $degrade_quality = 1;
  1336. if ($degrade_quality >= 0 && $degrade_quality < 1) $filter_degrade = true;
  1337. }
  1338. // loop through all sample blocks
  1339. for ($block = 0; $block < $numBlocks; ++$block) {
  1340. // loop through all channels
  1341. for ($channel = 1; $channel <= $numChannels; ++$channel) {
  1342. // read current sample
  1343. $currentBlock = $blockOffset + $block;
  1344. $sampleFloat = $this->getSampleValue($currentBlock, $channel);
  1345. /************* MIX FILTER ***********************/
  1346. if ($filter_mix) {
  1347. if ($mix_loop) {
  1348. $mixBlock = ($mix_blockOffset + ($block % $mix_numBlocks)) % $mix_totalBlocks;
  1349. } else {
  1350. $mixBlock = $mix_blockOffset + $block;
  1351. }
  1352. if ($mixBlock < $mix_maxBlock) {
  1353. $sampleFloat += $mix_wav->getSampleValue($mixBlock, $channel);
  1354. }
  1355. }
  1356. /************* NORMALIZE FILTER *******************/
  1357. if ($filter_normalize) {
  1358. $sampleFloat = $this->normalizeSample($sampleFloat, $normalize_threshold);
  1359. }
  1360. /************* DEGRADE FILTER *******************/
  1361. if ($filter_degrade) {
  1362. $sampleFloat += rand(1000000 * ($degrade_quality - 1), 1000000 * (1 - $degrade_quality)) / 1000000;
  1363. }
  1364. // write current sample
  1365. $this->setSampleValue($sampleFloat, $currentBlock, $channel);
  1366. }
  1367. }
  1368. return $this;
  1369. }
  1370. /**
  1371. * Append a wav file to the current wav. <br />
  1372. * The wav files must have the same sample rate, number of bits per sample, and number of channels.
  1373. *
  1374. * @param WavFile $wav (Required) The wav file to append.
  1375. * @throws WavFileException
  1376. */
  1377. public function appendWav(WavFile $wav) {
  1378. // basic checks
  1379. if ($wav->getSampleRate() != $this->getSampleRate()) {
  1380. throw new WavFileException("Sample rate for wav files do not match.");
  1381. } else if ($wav->getBitsPerSample() != $this->getBitsPerSample()) {
  1382. throw new WavFileException("Bits per sample for wav files do not match.");
  1383. } else if ($wav->getNumChannels() != $this->getNumChannels()) {
  1384. throw new WavFileException("Number of channels for wav files do not match.");
  1385. }
  1386. $this->_samples .= $wav->_samples;
  1387. $this->setDataSize(); // implicit setSize(), setActualSize(), setNumBlocks()
  1388. return $this;
  1389. }
  1390. /**
  1391. * Mix 2 wav files together. <br />
  1392. * Both wavs must have the same sample rate and same number of channels.
  1393. *
  1394. * @param WavFile $wav (Required) The WavFile to mix.
  1395. * @param float $normalizeThreshold (Optional) See normalizeSample for an explanation.
  1396. * @throws WavFileException
  1397. */
  1398. public function mergeWav(WavFile $wav, $normalizeThreshold = null) {
  1399. return $this->filter(array(
  1400. WavFile::FILTER_MIX => $wav,
  1401. WavFile::FILTER_NORMALIZE => $normalizeThreshold
  1402. ));
  1403. }
  1404. /**
  1405. * Add silence to the wav file.
  1406. *
  1407. * @param float $duration (Optional) How many seconds of silence. If negative, add to the beginning of the file. Defaults to 1s.
  1408. */
  1409. public function insertSilence($duration = 1.0)
  1410. {
  1411. $numSamples = (int)($this->getSampleRate() * abs($duration));
  1412. $numChannels = $this->getNumChannels();
  1413. $data = str_repeat(self::packSample($this->getZeroAmplitude(), $this->getBitsPerSample()), $numSamples * $numChannels);
  1414. if ($duration >= 0) {
  1415. $this->_samples .= $data;
  1416. } else {
  1417. $this->_samples = $data . $this->_samples;
  1418. }
  1419. $this->setDataSize(); // implicit setSize(), setActualSize(), setNumBlocks()
  1420. return $this;
  1421. }
  1422. /**
  1423. * Degrade the quality of the wav file by introducing random noise.
  1424. *
  1425. * @param float quality (Optional) The quality relative to the amplitude. 1 = no noise, 0 = max. noise.
  1426. */
  1427. public function degrade($quality = 1.0)
  1428. {
  1429. return $this->filter(self::FILTER_DEGRADE, array(
  1430. WavFile::FILTER_DEGRADE => $quality
  1431. ));
  1432. }
  1433. /**
  1434. * Generate noise at the end of the wav for the specified duration and volume.
  1435. *
  1436. * @param float $duration (Optional) Number of seconds of noise to generate.
  1437. * @param float $percent (Optional) The percentage of the maximum amplitude to use. 100 = full amplitude.
  1438. */
  1439. public function generateNoise($duration = 1.0, $percent = 100)
  1440. {
  1441. $numChannels = $this->getNumChannels();
  1442. $numSamples = $this->getSampleRate() * $duration;
  1443. $minAmp = $this->getMinAmplitude();
  1444. $maxAmp = $this->getMaxAmplitude();
  1445. $bitDepth = $this->getBitsPerSample();
  1446. for ($s = 0; $s < $numSamples; ++$s) {
  1447. if ($bitDepth == 32) {
  1448. $val = rand(-$percent * 10000, $percent * 10000) / 1000000;
  1449. } else {
  1450. $val = rand($minAmp, $maxAmp);
  1451. $val = (int)($val * $percent / 100);
  1452. }
  1453. $this->_samples .= str_repeat(self::packSample($val, $bitDepth), $numChannels);
  1454. }
  1455. $this->setDataSize(); // implicit setSize(), setActualSize(), setNumBlocks()
  1456. return $this;
  1457. }
  1458. /**
  1459. * Convert sample data to different bits per sample.
  1460. *
  1461. * @param int $bitsPerSample (Required) The new number of bits per sample;
  1462. * @throws WavFileException
  1463. */
  1464. public function convertBitsPerSample($bitsPerSample) {
  1465. if ($this->getBitsPerSample() == $bitsPerSample) {
  1466. return $this;
  1467. }
  1468. $tempWav = new WavFile($this->getNumChannels(), $this->getSampleRate(), $bitsPerSample);
  1469. $tempWav->filter(
  1470. array(self::FILTER_MIX => $this),
  1471. 0,
  1472. $this->getNumBlocks()
  1473. );
  1474. $this->setSamples() // implicit setDataSize(), setSize(), setActualSize(), setNumBlocks()
  1475. ->setBitsPerSample($bitsPerSample); // implicit setValidBitsPerSample(), setAudioFormat(), setAudioSubFormat(), setFmtChunkSize(), setFactChunkSize(), setSize(), setActualSize(), setDataOffset(), setByteRate(), setBlockAlign(), setNumBlocks()
  1476. $this->_samples = $tempWav->_samples;
  1477. $this->setDataSize(); // implicit setSize(), setActualSize(), setNumBlocks()
  1478. return $this;
  1479. }
  1480. /*%******************************************************************************************%*/
  1481. // Miscellaneous methods
  1482. /**
  1483. * Output information about the wav object.
  1484. */
  1485. public function displayInfo()
  1486. {
  1487. $s = "File Size: %u\n"
  1488. ."Chunk Size: %u\n"
  1489. ."fmt Subchunk Size: %u\n"
  1490. ."Extended fmt Size: %u\n"
  1491. ."fact Subchunk Size: %u\n"
  1492. ."Data Offset: %u\n"
  1493. ."Data Size: %u\n"
  1494. ."Audio Format: %s\n"
  1495. ."Audio SubFormat: %s\n"
  1496. ."Channels: %u\n"
  1497. ."Channel Mask: 0x%s\n"
  1498. ."Sample Rate: %u\n"
  1499. ."Bits Per Sample: %u\n"
  1500. ."Valid Bits Per Sample: %u\n"
  1501. ."Sample Block Size: %u\n"
  1502. ."Number of Sample Blocks: %u\n"
  1503. ."Byte Rate: %uBps\n";
  1504. $s = sprintf($s, $this->getActualSize(),
  1505. $this->getChunkSize(),
  1506. $this->getFmtChunkSize(),
  1507. $this->getFmtExtendedSize(),
  1508. $this->getFactChunkSize(),
  1509. $this->getDataOffset(),
  1510. $this->getDataSize(),
  1511. $this->getAudioFormat() == self::WAVE_FORMAT_PCM ? 'PCM' : ($this->getAudioFormat() == self::WAVE_FORMAT_IEEE_FLOAT ? 'IEEE FLOAT' : 'EXTENSIBLE'),
  1512. $this->getAudioSubFormat() == self::WAVE_SUBFORMAT_PCM ? 'PCM' : 'IEEE FLOAT',
  1513. $this->getNumChannels(),
  1514. dechex($this->getChannelMask()),
  1515. $this->getSampleRate(),
  1516. $this->getBitsPerSample(),
  1517. $this->getValidBitsPerSample(),
  1518. $this->getBlockAlign(),
  1519. $this->getNumBlocks(),
  1520. $this->getByteRate());
  1521. if (php_sapi_name() == 'cli') {
  1522. return $s;
  1523. } else {
  1524. return nl2br($s);
  1525. }
  1526. }
  1527. }
  1528. /*%******************************************************************************************%*/
  1529. // Exceptions
  1530. /**
  1531. * WavFileException indicates an illegal state or argument in this class.
  1532. */
  1533. class WavFileException extends Exception {}
  1534. /**
  1535. * WavFormatException indicates a malformed or unsupported wav file header.
  1536. */
  1537. class WavFormatException extends WavFileException {}