gpt4 book ai didi

javascript - AudioContext.currentTime + 可变时间

转载 作者:行者123 更新时间:2023-12-02 14:25:45 24 4
gpt4 key购买 nike

使用 Web Audio API 使用振荡器生成基本音调,但存在改变演奏音符的持续时间(以秒为单位)的问题。

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

JS:

//start new audio session. Do this only once

var context = new window.webkitAudioContext();

函数 playSound(注意) { 振荡器 = 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>

感谢您的帮助!

最佳答案

您需要将维持选择元素的结果值解析为 float ,因为它返回字符串值。如果在 javascript 中将字符串与数字组合,则其计算结果为字符串。看一下这个 jsbin 的实际示例:

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

只需编辑此行

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

像这样

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

关于javascript - AudioContext.currentTime + 可变时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38267218/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com