1

我知道我需要用户操作才能在移动设备上启动 Web Audio。但是,我已按照建议在用户操作上恢复(在 Tone.js 调用 Tone.start() 的情况下),但它仍然不起作用。以下是我的代码的相关部分:

keyElement.addEventListener("touchstart", notePressed, false);
keyElement.addEventListener("touchend", noteReleased, false);

function notePressed(event) {
        let dataset = event.target.dataset;
        if (!dataset["pressed"]) {
            let octave = +dataset["octave"];
            oscList[octave][dataset["note"]] = playTone(dataset["frequency"]);
            dataset["pressed"] = "yes";
        }
        event.preventDefault(); event.stopPropagation();
    }
function noteReleased(event) {
      let dataset = event.target.dataset;

      if (dataset && dataset["pressed"]) {
        let octave = +dataset["octave"];
        oscList[octave][dataset["note"]].triggerRelease();
        delete oscList[octave][dataset["note"]];
        delete dataset["pressed"];
      }
    } 
function playTone(freq) {
        let synth = new Tone.Synth().toDestination();
        let now = Tone.now();
        Tone.start();
        synth.triggerAttack(freq, now);
        return synth;
    } 

它在第二次触摸时工作正常,但在第一次触摸后,我收到有关音频上下文被暂停的警告,即使标准是当用户操作调用 start() 时它会恢复。我被难住了。

4

1 回答 1

0

那个音代码看起来是正确的。我在 CodePen 中对其进行了简化,它在第一次点击(iOS)时就可以在移动设备上运行。

var keyElement = document.getElementById("play");

keyElement.addEventListener("touchstart", notePressed, false);
keyElement.addEventListener("touchend", noteReleased, false);

// Added mouse ELs to test on non-mobile.
keyElement.addEventListener("mousedown", notePressed, false); 
keyElement.addEventListener("mouseup", noteReleased, false);

var pressedTone;

function notePressed(event) {
  console.log("notePressed");
  pressedTone = playTone(440);
  event.preventDefault();
  event.stopPropagation();
}
function noteReleased(event) {
  pressedTone.triggerRelease();
}
function playTone(freq) {
  console.log("playTone", freq);
  let synth = new Tone.Synth().toDestination();
  let now = Tone.now();
  Tone.start();
  synth.triggerAttack(freq, now);
  return synth;
}

这是 CodePen 的链接:https ://codepen.io/joeweiss/pen/gOmeQVW

于 2021-06-04T13:05:55.297 回答