具有网络音频 API 的异步事件



如何使用网络音频 API 对振荡器停止播放后发生的事件进行编程? 我试图通过更新我的 Vue 组件,在播放音符时让数据在 DOM 中显示。 我的代码如下所示:

<template>
<div id="player">
<div>{{ currentTime }}</div>
<button @click="start">play</button>
<div>{{ sequence }}</div>
</div>
</template>
<script>
var audioContext = new AudioContext()
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}
export default {
name: 'player',
data: function(){
return {
sequence: [],
toRecall: null,
frequencies: [110, 220, 440, 880],
lives: 3,
n: 2,
currentTime: null,
stop: false
}
},
methods: {
playNote: function(startTime, delay, duration){
var self=this
return new Promise(function(accept, reject){
var pitch = getRandomInt(-12, 13)
self.sequence.push(pitch)
var startTime = audioContext.currentTime + delay
var endTime = startTime + duration
var oscillator = audioContext.createOscillator()
oscillator.connect(audioContext.destination)
oscillator.type = 'sawtooth'
oscillator.start(startTime)
oscillator.stop(endTime)
accept()
})                          
},
start: function(){
var self=this
this.currentTime = audioContext.currentTime
this.playNote(0, 0, 1).then(function(){
// do once the note is done playing
self.sequence.pop()
})
}
}
}

具体来说,我希望音高sequence(目前只有一个)在音符播放的 1 秒内出现在屏幕上,然后消失——只是为了证明只有在音符演奏完成后才会调用pop。 谁能帮我解决这个问题? 谢谢。

请参阅 https://webaudio.github.io/web-audio-api/#dom-audioscheduledsourcenode-onended。 而且由于OscillatorNodeAudioScheduledSourceNode,您可以执行以下操作:

oscillator.onended = function () { /* Remove note from display, or whatever */ };

最新更新