Admidio API
  • Package
  • Class
  • Tree
  • Deprecated
  • Todo

Packages

  • com
    • tecnick
      • tcpdf
  • None
  • PHPMailer
    • easypeasyics
  • PHPWavUtils
  • Securimage
    • classes

Classes

  • WavFile

Class WavFile

Project: PHPWavUtils: Classes for creating, reading, and manipulating WAV files in PHP
File: WavFile.php

Copyright (c) 2014, Drew Phillips All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Any modifications to the library should be indicated clearly in the source code to inform users that the changes are not a part of the original software.

Package: PHPWavUtils
Copyright: 2014 Drew Phillips
License: License Changelog: 1.1.1 (09/08/2015) - Fix degrade() method to call filter correctly (Rasmus Lerdorf) 1.1 (02/8/2014) - Add method setIgnoreChunkSizes() to allow reading of wav data with bogus chunk sizes set. This allows streamed wav data to be processed where the chunk sizes were not known when writing the header. Instead calculates the chunk sizes automatically. - Add simple volume filter to attenuate or amplify the audio signal. 1.0 (10/2/2012) - Fix insertSilence() creating invalid block size 1.0 RC1 (4/20/2012) - Initial release candidate - Supports 8, 16, 24, 32 bit PCM, 32-bit IEEE FLOAT, Extensible Format - Support for 18 channels of audio - Ability to read an offset from a file to reduce memory footprint with large files - Single-pass audio filter processing - Highly accurate and efficient mix and normalization filters (http://www.voegler.eu/pub/audio/) - Utility filters for degrading audio, and inserting silence 0.6 (4/12/2012) - Support 8, 16, 24, 32 bit and PCM float (Paul Voegler) - Add normalize filter, misc improvements and fixes (Paul Voegler) - Normalize parameters to filter() to use filter constants as array indices - Add option to mix filter to loop the target file if the source is longer 0.5 (4/3/2012) - Fix binary pack routine (Paul Voegler) - Add improved mixing function (Paul Voegler)
Author: Drew Phillips drew@drew-phillips.com
Author: Paul Voegler http://www.voegler.eu/
Version: 1.1.1 (Sep 2015)
Located at WavFile.php

Methods summary

public
# __construct( string|integer $numChannelsOrFileName = null, integer|boolean $sampleRateOrReadData = null, integer $bitsPerSample = null )

WavFile Constructor.

WavFile Constructor.

$wav1 = new WavFile(2, 44100, 16);         // new wav with 2 channels, at 44100 samples/sec and 16 bits per sample
$wav2 = new WavFile('./audio/sound.wav');  // open and read wav file

Parameters

$numChannelsOrFileName
(Optional) If string, the filename of the wav file to open. The number of channels otherwise. Defaults to 1.
$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.
$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.

Throws

WavFormatException
WavFileException
public
# __destruct( )
public
# __clone( )
public string
# __toString( )

Output the wav file headers and data.

Output the wav file headers and data.

Returns

string
The encoded file.
public static integer|float|null
# unpackSample( string $sampleBinary, integer $bitDepth = null )

Unpacks a single binary sample to numeric value.

Unpacks a single binary sample to numeric value.

Parameters

$sampleBinary
(Required) The sample to decode.
$bitDepth
(Optional) The bits per sample to decode. If omitted, derives it from the length of $sampleBinary.

Returns

integer|float|null
The numeric sample value. Float for 32-bit samples. Returns null for unsupported bit depths.
public static string|null
# packSample( integer|float $sample, integer $bitDepth )

Packs a single numeric sample to binary.

Packs a single numeric sample to binary.

Parameters

$sample
(Required) The sample to encode. Has to be within valid range for $bitDepth. Float values only for 32 bits.
$bitDepth
(Required) The bits per sample to encode with.

Returns

string|null
The encoded binary sample. Returns null for unsupported bit depths.
public static array
# unpackSampleBlock( string $sampleBlock, integer $bitDepth, integer $numChannels = null )

Unpacks a binary sample block to numeric values.

Unpacks a binary sample block to numeric values.

Parameters

$sampleBlock
(Required) The binary sample block (all channels).
$bitDepth
(Required) The bits per sample to decode.
$numChannels
(Optional) The number of channels to decode. If omitted, derives it from the length of $sampleBlock and $bitDepth.

Returns

array
The sample values as an array of integers of floats for 32 bits. First channel is array index 1.
public static string
# packSampleBlock( array $samples, integer $bitDepth )

Packs an array of numeric channel samples to a binary sample block.

Packs an array of numeric channel samples to a binary sample block.

Parameters

$samples
(Required) The array of channel sample values. Expects float values for 32 bits and integer otherwise.
$bitDepth
(Required) The bits per sample to encode with.

Returns

string
The encoded binary sample block.
public static float
# normalizeSample( float $sampleFloat, float $threshold )

Normalizes a float audio sample. Maximum input range assumed for compression is [-2, 2]. See http://www.voegler.eu/pub/audio/ for more information.

Normalizes a float audio sample. Maximum input range assumed for compression is [-2, 2]. See http://www.voegler.eu/pub/audio/ for more information.

Parameters

$sampleFloat
(Required) The float sample to normalize.
$threshold

(Required) The threshold or gain factor for normalizing the amplitude.

  • >= 1 - Normalize by multiplying by the threshold (boost - positive gain).
    A value of 1 in effect means no normalization (and results in clipping).
  • <= -1 - Normalize by dividing by the the absolute value of threshold (attenuate - negative gain).
    A factor of 2 (-2) is about 6dB reduction in volume.
  • [0, 1) - (open inverval - not including 1) - The threshold above which amplitudes are comressed logarithmically.
    e.g. 0.6 to leave amplitudes up to 60% "as is" and compress above.
  • (-1, 0) - (open inverval - not including -1 and 0) - The threshold above which amplitudes are comressed linearly.
    e.g. -0.6 to leave amplitudes up to 60% "as is" and compress above.

Returns

float
The normalized sample.
public
# getActualSize( )
protected
# setActualSize( integer $actualSize = null )

Parameters

$actualSize
public
# getChunkSize( )
protected
# setChunkSize( integer $chunkSize = null )

Parameters

$chunkSize
public
# getFmtChunkSize( )
protected
# setFmtChunkSize( integer $fmtChunkSize = null )

Parameters

$fmtChunkSize
public
# getFmtExtendedSize( )
protected
# setFmtExtendedSize( integer $fmtExtendedSize = null )

Parameters

$fmtExtendedSize
public
# getFactChunkSize( )
protected
# setFactChunkSize( integer $factChunkSize = null )

Parameters

$factChunkSize
public
# getDataSize( )
protected
# setDataSize( integer $dataSize = null )

Parameters

$dataSize
public
# getDataOffset( )
protected
# setDataOffset( integer $dataOffset = null )

Parameters

$dataOffset
public
# getAudioFormat( )
protected
# setAudioFormat( integer $audioFormat = null )

Parameters

$audioFormat
public
# getAudioSubFormat( )
protected
# setAudioSubFormat( integer $audioSubFormat = null )

Parameters

$audioSubFormat
public
# getNumChannels( )
public
# setNumChannels( integer $numChannels )

Parameters

$numChannels
public
# getChannelMask( )
public
# setChannelMask( $channelMask = self::SPEAKER_DEFAULT )
public
# getSampleRate( )
public
# setSampleRate( $sampleRate )
public
# getBitsPerSample( )
public
# setBitsPerSample( $bitsPerSample )
public
# getValidBitsPerSample( )
protected
# setValidBitsPerSample( $validBitsPerSample = null )
public
# getBlockAlign( )
protected
# setBlockAlign( integer $blockAlign = null )

Parameters

$blockAlign
public
# getNumBlocks( )
protected
# setNumBlocks( integer $numBlocks = null )

Parameters

$numBlocks
public
# getByteRate( )
protected
# setByteRate( integer $byteRate = null )

Parameters

$byteRate
public
# getIgnoreChunkSizes( )
public
# setIgnoreChunkSizes( $ignoreChunkSizes )
public
# getSamples( )
public
# setSamples( & $samples = '' )
public
# getMinAmplitude( )
public
# getZeroAmplitude( )
public
# getMaxAmplitude( )
public string
# makeHeader( )

Construct a wav header from this object. Includes "fact" chunk if necessary. http://www-mmsp.ece.mcgill.ca/documents/audioformats/wave/wave.html

Construct a wav header from this object. Includes "fact" chunk if necessary. http://www-mmsp.ece.mcgill.ca/documents/audioformats/wave/wave.html

Returns

string
The RIFF header data.
public string
# getDataSubchunk( )

Construct wav DATA chunk.

Construct wav DATA chunk.

Returns

string
The DATA header and chunk.
public
# save( string $filename )

Save the wav data to a file.

Save the wav data to a file.

Parameters

$filename
(Required) The file path to save the wav to.

Throws

WavFileException
public
# openWav( string $filename, boolean $readData = true )

Reads a wav header and data from a file.

Reads a wav header and data from a file.

Parameters

$filename
(Required) The path to the wav file to read.
$readData
(Optional) If true, also read the data chunk.

Throws

WavFormatException
WavFileException
public
# closeWav( )

Close a with openWav() previously opened wav file or free the buffer of setWavData(). Not necessary if the data has been read (readData = true) already.

Close a with openWav() previously opened wav file or free the buffer of setWavData(). Not necessary if the data has been read (readData = true) already.

public
# setWavData( string & $data, boolean $free = true )

Set the wav file data and properties from a wav file in a string.

Set the wav file data and properties from a wav file in a string.

Parameters

$data
(Required) The wav file data. Passed by reference.
$free
(Optional) True to free the passed $data after copying.

Throws

WavFormatException
WavFileException
protected
# readWav( boolean $readData = true )

Read wav file from a stream.

Read wav file from a stream.

Parameters

$readData
(Optional) If true, also read the data chunk.

Throws

WavFormatException
WavFileException
protected
# readWavHeader( )

Parse a wav header. http://www-mmsp.ece.mcgill.ca/documents/audioformats/wave/wave.html

Parse a wav header. http://www-mmsp.ece.mcgill.ca/documents/audioformats/wave/wave.html

Throws

WavFormatException
WavFileException
public
# readWavData( integer $dataOffset = 0, integer $dataSize = null )

Read the wav data from the file into the buffer.

Read the wav data from the file into the buffer.

Parameters

$dataOffset
(Optional) The byte offset to skip before starting to read. Must be a multiple of BlockAlign.
$dataSize
(Optional) The size of the data to read in bytes. Must be a multiple of BlockAlign. Defaults to all data.

Throws

WavFileException
public string|null
# getSampleBlock( integer $blockNum )

Return a single sample block from the file.

Return a single sample block from the file.

Parameters

$blockNum
(Required) The sample block number. Zero based.

Returns

string|null
The binary sample block (all channels). Returns null if the sample block number was out of range.
public
# setSampleBlock( string $sampleBlock, integer $blockNum )

Set a single sample block.
Allows to append a sample block.

Set a single sample block.
Allows to append a sample block.

Parameters

$sampleBlock
(Required) The binary sample block (all channels).
$blockNum
(Required) The sample block number. Zero based.

Throws

WavFileException
public float|null
# getSampleValue( integer $blockNum, integer $channelNum )

Get a float sample value for a specific sample block and channel number.

Get a float sample value for a specific sample block and channel number.

Parameters

$blockNum
(Required) The sample block number to fetch. Zero based.
$channelNum
(Required) The channel number within the sample block to fetch. First channel is 1.

Returns

float|null
The float sample value. Returns null if the sample block number was out of range.

Throws

WavFileException
public
# setSampleValue( float $sampleFloat, integer $blockNum, integer $channelNum )

Sets a float sample value for a specific sample block number and channel.
Converts float values to appropriate integer values and clips properly.
Allows to append samples (in order).

Sets a float sample value for a specific sample block number and channel.
Converts float values to appropriate integer values and clips properly.
Allows to append samples (in order).

Parameters

$sampleFloat
(Required) The float sample value to set. Converts float values and clips if necessary.
$blockNum
(Required) The sample block number to set or append. Zero based.
$channelNum
(Required) The channel number within the sample block to set or append. First channel is 1.

Throws

WavFileException
public
# filter( array $filters, integer $blockOffset = 0, integer $numBlocks = null )

Run samples through audio processing filters.

Run samples through audio processing filters.

$wav->filter(
     array(
         WavFile::FILTER_MIX => array(          // Filter for mixing 2 WavFile instances.
             'wav' => $wav2,                    // (Required) The WavFile to mix into this WhavFile. If no optional arguments are given, can be passed without the array.
             'loop' => true,                    // (Optional) Loop the selected portion (with warping to the beginning at the end).
             'blockOffset' => 0,                // (Optional) Block number to start mixing from.
             'numBlocks' => null                // (Optional) Number of blocks to mix in or to select for looping. Defaults to the end or all data for looping.
         ),
         WavFile::FILTER_NORMALIZE => 0.6,      // (Required) Normalization of (mixed) audio samples - see threshold parameter for normalizeSample().
         WavFile::FILTER_DEGRADE => 0.9         // (Required) Introduce random noise. The quality relative to the amplitude. 1 = no noise, 0 = max. noise.
         WavFile::FILTER_VOLUME => 1.0          // (Required) Amplify or attenuate the audio signal.  Beware of clipping when amplifying.  Values range from >= 0 - <= 2.  1 = no change in volume; 0.5 = 50% reduction of volume; 1.5 = 150% increase in volume.
     ),
     0,                                         // (Optional) The block number of this WavFile to start with.
     null                                       // (Optional) The number of blocks to process.
 );

Parameters

$filters
(Required) An array of 1 or more audio processing filters.
$blockOffset
(Optional) The block number to start precessing from.
$numBlocks
(Optional) The maximum number of blocks to process.

Throws

WavFileException
public
# appendWav( WavFile $wav )

Append a wav file to the current wav.
The wav files must have the same sample rate, number of bits per sample, and number of channels.

Append a wav file to the current wav.
The wav files must have the same sample rate, number of bits per sample, and number of channels.

Parameters

$wav
(Required) The wav file to append.

Throws

WavFileException
public
# mergeWav( WavFile $wav, float $normalizeThreshold = null )

Mix 2 wav files together.
Both wavs must have the same sample rate and same number of channels.

Mix 2 wav files together.
Both wavs must have the same sample rate and same number of channels.

Parameters

$wav
(Required) The WavFile to mix.
$normalizeThreshold
(Optional) See normalizeSample for an explanation.

Throws

WavFileException
public
# insertSilence( float $duration = 1.0 )

Add silence to the wav file.

Add silence to the wav file.

Parameters

$duration
(Optional) How many seconds of silence. If negative, add to the beginning of the file. Defaults to 1s.
public
# degrade( float $quality = 1.0 )

Degrade the quality of the wav file by introducing random noise.

Degrade the quality of the wav file by introducing random noise.

Parameters

$quality
(Optional) The quality relative to the amplitude. 1 = no noise, 0 = max. noise.
public
# generateNoise( float $duration = 1.0, float $percent = 100 )

Generate noise at the end of the wav for the specified duration and volume.

Generate noise at the end of the wav for the specified duration and volume.

Parameters

$duration
(Optional) Number of seconds of noise to generate.
$percent
(Optional) The percentage of the maximum amplitude to use. 100 = full amplitude.
public
# convertBitsPerSample( integer $bitsPerSample )

Convert sample data to different bits per sample.

Convert sample data to different bits per sample.

Parameters

$bitsPerSample
(Required) The new number of bits per sample;

Throws

WavFileException
public
# displayInfo( )

Output information about the wav object.

Output information about the wav object.

Constants summary

integer FILTER_MIX
# 0x01
integer FILTER_NORMALIZE
# 0x02
integer FILTER_DEGRADE
# 0x04
integer FILTER_VOLUME
# 0x08
integer MAX_CHANNEL
# 18
integer MAX_SAMPLERATE
# 192000
integer SPEAKER_DEFAULT

Channel Locations for ChannelMask

Channel Locations for ChannelMask

# 0x000000
integer SPEAKER_FRONT_LEFT
# 0x000001
integer SPEAKER_FRONT_RIGHT
# 0x000002
integer SPEAKER_FRONT_CENTER
# 0x000004
integer SPEAKER_LOW_FREQUENCY
# 0x000008
integer SPEAKER_BACK_LEFT
# 0x000010
integer SPEAKER_BACK_RIGHT
# 0x000020
integer SPEAKER_FRONT_LEFT_OF_CENTER
# 0x000040
integer SPEAKER_FRONT_RIGHT_OF_CENTER
# 0x000080
integer SPEAKER_BACK_CENTER
# 0x000100
integer SPEAKER_SIDE_LEFT
# 0x000200
integer SPEAKER_SIDE_RIGHT
# 0x000400
integer SPEAKER_TOP_CENTER
# 0x000800
integer SPEAKER_TOP_FRONT_LEFT
# 0x001000
integer SPEAKER_TOP_FRONT_CENTER
# 0x002000
integer SPEAKER_TOP_FRONT_RIGHT
# 0x004000
integer SPEAKER_TOP_BACK_LEFT
# 0x008000
integer SPEAKER_TOP_BACK_CENTER
# 0x010000
integer SPEAKER_TOP_BACK_RIGHT
# 0x020000
integer SPEAKER_ALL
# 0x03FFFF
integer WAVE_FORMAT_PCM
# 0x0001
integer WAVE_FORMAT_IEEE_FLOAT
# 0x0003
integer WAVE_FORMAT_EXTENSIBLE
# 0xFFFE
string WAVE_SUBFORMAT_PCM
# "0100000000001000800000aa00389b71"
string WAVE_SUBFORMAT_IEEE_FLOAT
# "0300000000001000800000aa00389b71"

Properties summary

protected static array $LOOKUP_LOGBASE

Log base modifier lookup table for a given threshold (in 0.05 steps) used by normalizeSample. Adjusts the slope (1st derivative) of the log function at the threshold to 1 for a smooth transition from linear to logarithmic amplitude output.

Log base modifier lookup table for a given threshold (in 0.05 steps) used by normalizeSample. Adjusts the slope (1st derivative) of the log function at the threshold to 1 for a smooth transition from linear to logarithmic amplitude output.

# array( 2.513, 2.667, 2.841, 3.038, 3.262, 3.520, 3.819, 4.171, 4.589, 5.093, 5.711, 6.487, 7.483, 8.806, 10.634, 13.302, 17.510, 24.970, 41.155, 96.088 )
protected integer $_actualSize

The actual physical file size

The actual physical file size

#
protected integer $_chunkSize

The size of the file in RIFF header

The size of the file in RIFF header

#
protected integer $_fmtChunkSize

The size of the "fmt " chunk

The size of the "fmt " chunk

#
protected integer $_fmtExtendedSize

The size of the extended "fmt " data

The size of the extended "fmt " data

#
protected integer $_factChunkSize

The size of the "fact" chunk

The size of the "fact" chunk

#
protected integer $_dataSize

Size of the data chunk

Size of the data chunk

#
protected integer $_dataSize_fp

Size of the data chunk in the opened wav file

Size of the data chunk in the opened wav file

#
protected boolean $_dataSize_valid

Does _dataSize really reflect strlen($_samples)? Case when a wav file is read with readData = false

Does _dataSize really reflect strlen($_samples)? Case when a wav file is read with readData = false

#
protected integer $_dataOffset

Starting offset of data chunk

Starting offset of data chunk

#
protected integer $_audioFormat

The audio format - WavFile::WAVE_FORMAT_*

The audio format - WavFile::WAVE_FORMAT_*

#
protected integer|string|null $_audioSubFormat

The audio subformat - WavFile::WAVE_SUBFORMAT_*

The audio subformat - WavFile::WAVE_SUBFORMAT_*

#
protected integer $_numChannels

Number of channels in the audio file

Number of channels in the audio file

#
protected integer $_channelMask

The channel mask

The channel mask

#
protected integer $_sampleRate

Samples per second

Samples per second

#
protected integer $_bitsPerSample

Number of bits per sample

Number of bits per sample

#
protected integer $_validBitsPerSample

Number of valid bits per sample

Number of valid bits per sample

#
protected integer $_blockAlign

NumChannels * BitsPerSample/8

NumChannels * BitsPerSample/8

#
protected integer $_numBlocks

Number of sample blocks

Number of sample blocks

#
protected integer $_byteRate

Bytes per second

Bytes per second

#
protected boolean $_ignoreChunkSizes

Ignore chunk sizes when reading wav data (useful when reading data from a stream where chunk sizes contain dummy values)

Ignore chunk sizes when reading wav data (useful when reading data from a stream where chunk sizes contain dummy values)

#
protected string $_samples

Binary string of samples

Binary string of samples

#
protected resource|null $_fp

The file pointer used for reading wavs from file or memory

The file pointer used for reading wavs from file or memory

#
Admidio API API documentation generated by ApiGen