WebAudio - Oscillator
HTML
<form id="playerForm">
<h1>Play sound file using Web Audio API</h1>
<p>This example will show you how to decode an MP3 file using the Web Audio API.<p>
<p><input type="file" id="FileSelect" /></p>
<p><input type="button" id="playButton" value="Play" /></p>
</form>
<button>▶</button>
JavaScript
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var audioContext = new AudioContext();
var button = document.querySelector('button');
button.addEventListener('click', playNewSound);
function playNewSound() {
var oscillator = audioContext.createOscillator();
//oscillator.type = 'square';'square';'sawtooth', 'triangle','
oscillator.type = 'sine';
oscillator.frequency.value = 440; // value in hertz
var gain = audioContext.createGain();
oscillator.connect(gain);
gain.connect(audioContext.destination);
oscillator.start(0);
oscillator.stop(audioContext.currentTime + 0.2);
}
var source = null;
function obtainBytes(selectedFile, callback) {
var reader = new FileReader();
reader.onload = function (ev) {
var Bytes = reader.result;
callback(Bytes);
}
reader.readAsArrayBuffer(selectedFile);
}
playerForm.playButton.onclick = function (event) {
event.stopPropagation();
var fileInput = document.forms[0].FileSelect;
if (fileInput.files.length > 0 && ["audio/mpeg", "audio/mp3", "audio/wav"].includes(fileInput.files[0].type)) {
obtainBytes(fileInput.files[0], function (Bytes) {
decodeBytesAndPlay(Bytes);
});
}
else alert("Error! No attached file or attached file was of the wrong type!");
}
function decodeBytesAndPlay(Bytes) {
audioContext.decodeAudioData(Bytes, function (decodedSamplesAsAudioBuffer) {
if (source != null) {
source.disconnect(audioContext.destination);
source = null;
}
source = audioContext.createBufferSource();
source.buffer = decodedSamplesAsAudioBuffer; // set the buffer to play to our audio buffer
source.connect(audioContext.destination); // connect the source to the output destinarion
source.start(0); // tell the audio buffer to play from the beginning
source.stop(audioContext.currentTime + 5);
});
}