AudioContext.currentTime +变量时间

时间:2016-07-08 12:53:48

标签: javascript html5 audio web-audio-api

使用Web Audio API使用振荡器生成基本音调,并且在播放音符的持续时间(以秒为单位)时会出现问题。

问题在于“维持”变量无法正常工作以停止振荡器。该变量对于播放的一个音符按预期工作,然后其余音符播放无限期。如果我删除变量并硬编码持续时间而不是使用变量,它工作正常。 context.currentTime的日志显示变量或硬编码持续时间之间没有差异。过度思考。我错过了什么?

JS:

//start new audio session. Do this only once

var context = new window.webkitAudioContext();

function playSound(note){     oscillator = context.createOscillator();

//create volume controller
var gainNode = context.createGain();

//connect signal to audio output(speakers by default)
oscillator.connect(gainNode);
gainNode.connect(context.destination);

//adjusts frequency played by 50%, 100% or 200% 
var octave = document.getElementById('octave').value;

//sets oscillator frequency
oscillator.frequency.value = frequencies[note] * octave;

//oscillator wave type
oscillator.type = document.getElementById('waveSelect').value;

//starts oscillator. Delayed start can be achieved by adding time(in secs) after currentTime
oscillator.start(context.currentTime + 0.01);

//determines note duration
var sustain = document.getElementById('sustain').value;

//stops oscillator by exponentially ramping down sound over .015 seconds to avoid audible click
gainNode.gain.setTargetAtTime(0, context.currentTime + sustain, 0.0015);


//for testing
console.log("Hz:" + frequencies[note] * octave + " octave:" + octave + " wave:" + oscillator.type + "duration: " + sustain + " time:" + context.currentTime);

}

HTML:

<select class="lists" id="sustain">
            <option value="0.5">EIGHTH NOTE</option>
            <option value="1.0">QUARTER NOTE</option>
            <option value="2.0">HALF NOTE</option>
            <option value="4.0">WHOLE NOTE</option>             
        </select>

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

您需要将维持select-element的结果值解析为浮点数,因为它返回一个字符串值。 如果你将字符串与javascript中的数字组合在一起,它将计算为字符串。 看看这个jsbin是否有一个实际的例子:

http://jsbin.com/qexusoyida/edit?html,js,console,output

只需编辑此行

即可
var sustain = document.getElementById('sustain').value;
像这样

var sustain = parseFloat(document.getElementById('sustain').value);