在没有外部库的情况下更改音频元素的音高?

时间:2016-05-13 09:30:15

标签: javascript html5-audio

我想通过JavaScript改变Audio()元素的音高。简单的事情:

var audio = new Audio()
audio.src = "sound_effect.wav"
audio.pitch = 0.5 //Halving the frequency
audio.play()

编辑:我现在发现了AudioContext(),我有以下代码:

//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")

但是我不知道如何更改音调。

1 个答案:

答案 0 :(得分:1)

您已经完成了所有繁重的工作。最后一部分是在代码中添加音高值。来自MDN的更多信息。

https://developer.mozilla.org/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);
 }