使用WebAudio API的异步事件

时间:2018-04-04 04:45:02

标签: javascript asynchronous vue.js web-audio web-audio-api

如果使用webaudio 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是只有在音符完成播放后才被调用。谁能帮我这个?感谢。

1 个答案:

答案 0 :(得分:1)

https://webaudio.github.io/web-audio-api/#dom-audioscheduledsourcenode-onended。由于OscillatorNodeAudioScheduledSourceNode,您可以执行类似

的操作

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