var ArrayBufferStream = require('./ArrayBufferStream'); var Tone = require('tone'); var log = require('./log'); /** * Decode wav audio files that have been compressed with the ADPCM format. * This is necessary because, while web browsers have native decoders for many audio * formats, ADPCM is a non-standard format used by Scratch since its early days. * This decoder is based on code from Scratch-Flash: * https://github.com/LLK/scratch-flash/blob/master/src/sound/WAVFile.as * @constructor */ function ADPCMSoundDecoder () { } /** * Decode an ADPCM sound stored in an ArrayBuffer and return a promise * with the decoded audio buffer. * @param {ArrayBuffer} audioData - containing ADPCM encoded wav audio * @return {Tone.Buffer} */ ADPCMSoundDecoder.prototype.decode = function (audioData) { return new Promise(function (resolve, reject) { var stream = new ArrayBufferStream(audioData); var riffStr = stream.readUint8String(4); if (riffStr != 'RIFF') { log.warn('incorrect adpcm wav header'); reject(); } var lengthInHeader = stream.readInt32(); if ((lengthInHeader + 8) != audioData.byteLength) { log.warn('adpcm wav length in header: ' + lengthInHeader + ' is incorrect'); } var wavStr = stream.readUint8String(4); if (wavStr != 'WAVE') { log.warn('incorrect adpcm wav header'); reject(); } var formatChunk = this.extractChunk('fmt ', stream); this.encoding = formatChunk.readUint16(); this.channels = formatChunk.readUint16(); this.samplesPerSecond = formatChunk.readUint32(); this.bytesPerSecond = formatChunk.readUint32(); this.blockAlignment = formatChunk.readUint16(); this.bitsPerSample = formatChunk.readUint16(); formatChunk.position += 2; // skip extra header byte count this.samplesPerBlock = formatChunk.readUint16(); this.adpcmBlockSize = ((this.samplesPerBlock - 1) / 2) + 4; // block size in bytes var samples = this.imaDecompress(this.extractChunk('data', stream), this.adpcmBlockSize); // todo: this line is the only place Tone is used here, should be possible to remove var buffer = Tone.context.createBuffer(1, samples.length, this.samplesPerSecond); // todo: optimize this? e.g. replace the divide by storing 1/32768 and multiply? for (var i=0; i 88) index = 88; out.push(sample); } else { // read 4-bit code and compute delta from previous sample if (lastByte < 0) { if (compressedData.getBytesAvailable() == 0) break; lastByte = compressedData.readUint8(); code = lastByte & 0xF; } else { code = (lastByte >> 4) & 0xF; lastByte = -1; } step = this.stepTable[index]; delta = 0; if (code & 4) delta += step; if (code & 2) delta += step >> 1; if (code & 1) delta += step >> 2; delta += step >> 3; // compute next index index += this.indexTable[code]; if (index > 88) index = 88; if (index < 0) index = 0; // compute and output sample sample += (code & 8) ? -delta : delta; if (sample > 32767) sample = 32767; if (sample < -32768) sample = -32768; out.push(sample); } } var samples = Int16Array.from(out); return samples; }; module.exports = ADPCMSoundDecoder;