Repository navigation
Usage
メソッドの一覧は 機能、_wavChunks の形は 設計 にあります。
下の例はどれも tests/data/pcm16.wav (テストで使う合成データ。PCM 2ch 44100Hz 16bit、LIST INFO と大きさが奇数の JUNK チャンク付き) で動かした結果です。
% php sample/wavdump.php -f tests/data/pcm16.wav
RIFF container Length:128
WAVE Chunks(count:4)
Chunk[0] ID:fmt Size:16
FormatTag:1(PCM) Channels:2 SamplesPerSec:44100
AvgBytesPerSec:176400 BlockAlign:4 BitsPerSample:16
Chunk[1] ID:LIST Size:32
Data(size:32)
Chunk[2] ID:JUNK Size:3
Data(size:3)
Chunk[3] ID:data Size:40
Data(size:40)
先頭が WAVE でないと、メッセージを標準エラーに出して終了コード 1 で終わります。-h は受け付けますが、出力は変わりません。
fmt と data のチャンクを探し、フレーム数 (data の大きさ ÷ BlockAlign) と秒数を出します。
require_once 'IO/WAV.php';
$wav = new IO_WAV();
$wav->parse(file_get_contents('input.wav'));
$fmt = null;
$data = null;
foreach ($wav->_wavChunks as $chunk) {
if ($chunk['ChunkID'] === 'fmt ') {
$fmt = $chunk;
} else if ($chunk['ChunkID'] === 'data' && isset($chunk['Data'])) {
$data = $chunk['Data']; // 途中で切れたファイルでは Data が無い
}
}
$frames = (int) (strlen($data) / $fmt['BlockAlign']);
printf("%s %dch %dHz %dbit, %d frames, %.6f sec\n",
$wav->getFormatName($fmt['FormatTag']), $fmt['Channels'],
$fmt['SamplesPerSec'], $fmt['BitsPerSample'],
$frames, $frames / $fmt['SamplesPerSec']);PCM 2ch 44100Hz 16bit, 10 frames, 0.000227 sec
fmt の長さが 14 (WAVEFORMAT) のファイルには BitsPerSample がありません。isset() で確かめてから使ってください。
Data はファイルのバイト列そのままです。16 ビット PCM はリトルエンディアンの符号付き整数で、2ch ならチャンネルが交互 (L, R, L, R, ...) に並びます。
if ($fmt['FormatTag'] === IO_WAV::WAVE_FORMAT_PCM && $fmt['BitsPerSample'] === 16) {
$samples = array_values(unpack('v*', $data));
foreach ($samples as $i => $s) {
if ($s >= 0x8000) {
$samples[$i] = $s - 0x10000; // 符号付きに直す
}
}
echo "first frame: ", implode(", ", array_slice($samples, 0, $fmt['Channels'])), "\n";
}first frame: 0, 0
8 ビット PCM は符号無し (128 が無音)、WAVE_FORMAT_EXTENSIBLE のときは本当の形式が SubFormat (GUID の先頭 2 バイトが形式タグ) にあります。詳しくは WAV 形式 の「サンプルの並び」と「fmt チャンクの 3 つの長さ」にあります。
IO_WAV は LIST の中身を解釈しないので、Data を IO_Bit で読みます。INFO の後ろに、ID (4 文字)・大きさ (UI32LE)・文字列 のサブチャンクが並びます。
foreach ($wav->_wavChunks as $chunk) {
if ($chunk['ChunkID'] !== 'LIST' || substr($chunk['Data'], 0, 4) !== 'INFO') {
continue;
}
$bit = new IO_Bit();
$bit->input($chunk['Data']);
$bit->incrementOffset(4, 0); // "INFO"
while ($bit->hasNextData(8)) {
$id = $bit->getData(4);
$size = $bit->getUI32LE();
$text = $bit->getData($size);
if ($size % 2) {
$bit->incrementOffset(1, 0); // 詰め物
}
echo "$id: ", rtrim($text, "\0"), "\n";
}
}INAM: test
ISFT: make
各チャンクの _chunkOffset はファイル先頭からの位置 (チャンクヘッダの先頭) です。中身はその 8 バイト後ろから ChunkSize バイトなので、元のファイルから直接切り出すこともできます。
foreach ($wav->_wavChunks as $chunk) {
printf("%s at %d (+8), %d bytes\n", $chunk['ChunkID'], $chunk['_chunkOffset'], $chunk['ChunkSize']);
}fmt at 12 (+8), 16 bytes
LIST at 36 (+8), 32 bytes
JUNK at 76 (+8), 3 bytes
data at 88 (+8), 40 bytes