Changes

Jump to: navigation, search

Audio Data API

1,174 bytes added, 23:44, 30 August 2010
Complete Example: Creating a Web Based Tone Generator
<button onclick="stop()">stop</button>
<script type="text/javascript"> var function AudioDataDestination(sampleRate = 44100,readFn) { portionSize = sampleRate // 10, Initialize the audio output. prebufferSize var audio = new Audio(); audio.mozSetup(1, sampleRate / 2, freq = undefined); // no sound
var audio currentWritePosition = new Audio()0; audio.mozSetup(1, var prebufferSize = sampleRate)/ 2;// buffer 500ms var currentWritePosition tail = 0null;
// The function called with regular interval to populate // the audio output buffer. setInterval(function getSoundData(t, size) { var soundData = new Float32Array(size)written; // Check if some data was not written in previous attempts. if (freqtail) { var k written = 2* Mathaudio.PI * freq / sampleRatemozWriteAudio(tail); for (var i currentWritePosition +=0written; i if(written <size; i++tail.length) { soundData[i] // Not all the data was written, saving the tail... tail = Mathtail.sinslice(k * (i + t)written); return; // ... and exit the function. } tail = null;
}
// Check if we need add some data to the audio output. var currentPosition = audio.mozCurrentSampleOffset(); var available = currentPosition + prebufferSize - currentWritePosition; if(available > 0) { // Request some sound data from the callback function. var soundData = new Float32Array(available); readFn(soundData);  // Writting the data. written = audio.mozWriteAudio(soundData); if(written < soundData.length) { // Not all the data was written, saving the tail. tail = soundData.slice(written); } currentWritePosition += written; } return soundData}, 100);
}
function writeData() {// Control and generate the sound.  while(audio.mozCurrentSampleOffset() + prebufferSize > var frequency = currentWritePosition) {0, currentSoundSample; var soundData sampleRate = getSoundData44100;  function requestSoundData(currentWritePosition, portionSizesoundData);{ audio.mozWriteAudio if (soundData!frequency);{ currentWritePosition += portionSizereturn;// no sound selected
}
 
var k = 2* Math.PI * frequency / sampleRate;
for (var i=0, size=soundData.length; i<size; i++) {
soundData[i] = Math.sin(k * currentSoundSample++);
}
}
// initial write writeData(); var writeInterval audioDestination = Math.floornew AudioDataDestination(1000 * portionSize / sampleRate); setInterval(writeData, writeIntervalrequestSoundData);
function start() {
freq currentSoundSample = 0; frequency = parseFloat(document.getElementById("freq").value);
}
function stop() {
freq frequency = undefined0;
}
</script>
50
edits

Navigation menu