Web Audio API 播放和停止按钮

问题描述 投票:0回答:1

我创建了一个简单的程序,在其中按下“播放”按钮,它会播放一系列声音(使用 for 循环)。当我按下停止按钮时,声音就会停止。但是,当我再次按下“播放”按钮时,我需要从头开始播放声音,而当前发生的情况是旧声音与新声音一起播放。我尝试过 ctx.suspend() ,也尝试过 ctx.close() ,它不允许音频上下文重新启动。有什么建议可以让这个播放和停止按钮起作用吗?我尝试在按停止键时重新加载整个页面,但使页面不太用户友好且笨重(我想在下一个版本中添加下拉选择)。

<script>
 
    try {
      window.AudioContext = window.AudioContext || window.webkitAudioContext;
      ctx = new AudioContext();
 
    }
    catch(e) {
      alert('Web Audio API is not supported in this browser');
    }

    var btn = document.querySelector('button');
    var btn_stop = document.querySelector('button_stop');
    const gainNode = ctx.createGain();

      

    fetch("http://localhost:8000/3saudio/C4v9.wav")
      .then(data => data.arrayBuffer())
        .then(arrayBuffer => ctx.decodeAudioData(arrayBuffer))
        .then(decodedAudio => {
        c4 = decodedAudio;
        })

    function playnote(note, delay) {
      const playSound = ctx.createBufferSource();
      detune = 0;
      nt = c4;
      playSound.buffer = nt;
      var gainNode = ctx.createGain();
      var convolver = ctx.createConvolver();
      //console.log(nt)
      gainNode.gain.value = 1;
      gainNode.gain.setValueAtTime(1, ctx.currentTime+delay);
      gainNode.gain.exponentialRampToValueAtTime(0.0005, ctx.currentTime + 1.25 + delay);

     
      if (detune>0){
        playSound.detune.value = detune;

      }

      playSound.connect(gainNode).connect(ctx.destination);

      playSound.start(ctx.currentTime + delay);

    }

    function step51 () {
      var del = 0
      start = 12
      for (let i = 0; i < 10 ; i++) {
        playnote (keys[start+0],del + 0);
         playnote (keys[start+0],del + .25);
        playnote (keys[start+4],del + .5);
        playnote (keys[start+4],del + .75);
        playnote (keys[start+7],del + 1);
        playnote (keys[start+7],del + 1.25);
      }
    }

    
    document.querySelector('button');
    btn.addEventListener('click', function() {

     keys = ['c4','c4','c4','c4', 'c4']

      if (ctx.state === "suspended") {
      ctx.resume();
      }
      step51()
    });


    btn_stop.addEventListener('click', function() {
      **ctx.suspend()
      //ctx.close()**

      **//window.location.reload()**
      //history.go(0);
    });

</script>
javascript html api web audio
1个回答
0
投票

AudioContext 支持您创建的所有音频对象的整个音频图。通常,每页只有一个 AudioContext,并且只有在您不想很快播放音频的情况下才会暂停它。

也就是说,您应该停止 AudioBufferSourceNode,而不是挂起 AudioContext。

© www.soinside.com 2019 - 2024. All rights reserved.