I would like a way to change the pitch of an Audio()
element through JavaScript. Something simple like:
var audio = new Audio()
audio.src = "sound_effect.wav"
audio.pitch = 0.5 //Halving the frequency
audio.play()
EDIT: I now discovered AudioContext()
, and I have the following code:
//Import sounds
var SOUNDS = {};
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var audioContext = new AudioContext();
function loadSound(name,success,err) {
var request = new XMLHttpRequest();
request.open('GET', 'sounds/'+name+'.wav')
request.responseType = 'arraybuffer'
request.onload = function() {
audioContext.decodeAudioData(request.response, function(buffer) {
SOUNDS[name] = buffer;
(success || (function(){}))()
}, err || function(msg) {console.error(msg)});
}
request.send();
}
function playSound(name,param) {
param = param || {}
var s = SOUNDS[name]
var source = audioContext.createBufferSource()
source.buffer = s
if (param.loop) {
source.loop = true
}
source.connect(audioContext.destination);
source.start(0);
}
loadSound("laser",function() {
//Onload
playSound('laser')
})
loadSound("thump")
However I do not know how to change the pitch yet.
I would like a way to change the pitch of an Audio()
element through JavaScript. Something simple like:
var audio = new Audio()
audio.src = "sound_effect.wav"
audio.pitch = 0.5 //Halving the frequency
audio.play()
EDIT: I now discovered AudioContext()
, and I have the following code:
//Import sounds
var SOUNDS = {};
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var audioContext = new AudioContext();
function loadSound(name,success,err) {
var request = new XMLHttpRequest();
request.open('GET', 'sounds/'+name+'.wav')
request.responseType = 'arraybuffer'
request.onload = function() {
audioContext.decodeAudioData(request.response, function(buffer) {
SOUNDS[name] = buffer;
(success || (function(){}))()
}, err || function(msg) {console.error(msg)});
}
request.send();
}
function playSound(name,param) {
param = param || {}
var s = SOUNDS[name]
var source = audioContext.createBufferSource()
source.buffer = s
if (param.loop) {
source.loop = true
}
source.connect(audioContext.destination);
source.start(0);
}
loadSound("laser",function() {
//Onload
playSound('laser')
})
loadSound("thump")
However I do not know how to change the pitch yet.
You've done all of the heavy lifting. The last part is to add the pitch value in your code. More info from MDN.
https://developer.mozilla/en-US/docs/Web/API/AudioBufferSourceNode/detune
function playSound(name,param) {
param = param || {}
var s = SOUNDS[name]
var source = audioContext.createBufferSource()
source.buffer = s
if (param.loop) {
source.loop = true
}
source.connect(audioContext.destination);
// set the value of the pitch here
source.detune.value = // value of pitch
source.start(0);
}