【问题标题】:Web audio api, stop sound gracefullyWeb音频api,优雅地停止声音
【发布时间】:2017-05-21 13:27:47
【问题描述】:

网络音频 api 提供方法 .stop() 来停止声音。 我希望我的声音在停止之前降低音量。为此,我使用了增益节点。但是,我遇到了一些奇怪的问题,有些声音无法播放,我不知道为什么。

这是我所做的一个简化版:

https://jsfiddle.net/01p1t09n/1/

如果您删除带有setTimeout() 的行,您会听到每个声音都会播放。当 setTimeout 存在时,并非所有声音都会播放。真正让我困惑的是,我相应地使用push 和shift 来找到正确的声音来源,但似乎是另一个停止播放。我能看到这种情况发生的唯一方法是AudioContext.decodeAudioData 不是同步的。只需尝试 jsfiddle 以更好地理解并戴上耳机。

这里是jsfiddle的代码:

  let url = "https://raw.githubusercontent.com/gleitz/midi-js-soundfonts/gh-pages/MusyngKite/acoustic_guitar_steel-mp3/A4.mp3";
  let soundContainer = {};
  let notesMap = {"A4": [] };
  let _AudioContext_ = AudioContext || webkitAudioContext;
  let audioContext = new _AudioContext_();

  var oReq = new XMLHttpRequest();
  oReq.open("GET", url, true);
  oReq.responseType = "arraybuffer";
  oReq.onload = function (oEvent) {
    var arrayBuffer = oReq.response; 
    makeLoop(arrayBuffer);
  };
  oReq.send(null);

  function makeLoop(arrayBuffer){
     soundContainer["A4"] = arrayBuffer;
     let currentTime = audioContext.currentTime;
     for(let i = 0; i < 10; i++){
        //playing at same intervals
            play("A4", currentTime + i * 0.5);
        setTimeout( () => stop("A4"), 500 + i * 500); //remove this line you will hear all the sounds.
     }
  }

  function play(notePlayed, start) {    

      audioContext.decodeAudioData(soundContainer[notePlayed], (buffer) => {
      let source; 
      let gainNode; 
        source = audioContext.createBufferSource(); 
        gainNode = audioContext.createGain();
        // pushing notes in note map
        notesMap[notePlayed].push({ source, gainNode });
        source.buffer = buffer;                   
        source.connect(gainNode);
        gainNode.connect(audioContext.destination);
        gainNode.gain.value = 1;
        source.start(start);
       });
    }

      function stop(notePlayed){    
        let note = notesMap[notePlayed].shift();

        note.source.stop();
     }


这里只是为了说明我为什么会这样,你可以跳过,只是为了说明我为什么不用stop()

我这样做的原因是因为我想优雅地停止声音,所以如果有可能在不使用 setTimeout 的情况下这样做,我很乐意接受。

基本上我在顶部有一张地图,其中包含我的声音(如 A1、A#1、B1 等音符)。

soundMap = {"A": [], "lot": [], "of": [], "sounds": []};

还有一个play() fct,我在播放声音后填充数组:

  play(sound) { 
    // sound is just { soundName, velocity, start}   
    let source; 
    let gainNode; 
    // sound container is just a map from soundname to the sound data.
    this.audioContext.decodeAudioData(this.soundContainer[sound.soundName], (buffer) => {
      source = this.audioContext.createBufferSource(); 
      gainNode = this.audioContext.createGain();
      gainNode.gain.value = sound.velocity;
      // pushing sound in sound map
      this.soundMap[sound.soundName].push({ source, gainNode });
      source.buffer = buffer;                   
      source.connect(gainNode);
      gainNode.connect(this.audioContext.destination);
      source.start(sound.start);
     });
  }

现在是停止声音的部分:

  stop(sound){   
    //remember above, soundMap is a map from "soundName" to {gain, source} 
    let dasound = this.soundMap[sound.soundName].shift();
    let gain = dasound.gainNode.gain.value - 0.1;

    // we lower the gain via incremental values to not have the sound stop abruptly
    let i = 0;
    for(; gain > 0; i++, gain -= 0.1){ // watchout funky syntax
      ((gain, i) => {
        setTimeout(() => dasound.gainNode.gain.value = gain, 50 * i );
      })(gain, i)
    }
    // we stop the source after the gain is set at 0. stop is in sec
    setTimeout(() => note.source.stop(), i * 50);
  }

【问题讨论】:

  • “我能看到这种情况发生的唯一方法是 AudioContext.decodeAudioData 不同步。”你是对的,.decodeAudioData 不同步。
  • @guest271314 好吧,该死的,我得重新设计所有东西
  • “那些没有出现在网络音频 api 文档中” 您参考的是哪些文档?见Media events
  • @guest271314 当然,当我设置好一切后,我还没有开始,但我即将开始
  • @guest271314 完成,这很容易。我删除了整个声音容器,因为它有点无关紧要。 jsfiddle 在我的答案的底部,更改顶部的 var 以更改增益减少的进度

标签: javascript audio web-audio-api


【解决方案1】:

啊,是的,是的,是的!通过最终费心阅读文档中的“所有内容”(对角线),我终于找到了很多东西。让我告诉你,这个 api 是一颗未加工的钻石。无论如何,他们实际上拥有我想要的 Audio param :

AudioParam接口表示一个与音频相关的参数,通常是一个AudioNode的参数(如GainNode.gain)。一个 AudioParam 可以设置为特定值或更改值,并且 可以安排在特定时间发生并遵循特定的 模式。

它有一个函数linearRampToValueAtTime()

他们甚至有我问的例子!

// create audio context
var AudioContext = window.AudioContext || window.webkitAudioContext;
var audioCtx = new AudioContext();

// set basic variables for example
var myAudio = document.querySelector('audio');
var pre = document.querySelector('pre');
var myScript = document.querySelector('script');

pre.innerHTML = myScript.innerHTML;

var linearRampPlus = document.querySelector('.linear-ramp-plus');
var linearRampMinus = document.querySelector('.linear-ramp-minus');

// Create a MediaElementAudioSourceNode
// Feed the HTMLMediaElement into it
var source = audioCtx.createMediaElementSource(myAudio);

// Create a gain node and set it's gain value to 0.5
var gainNode = audioCtx.createGain();

// connect the AudioBufferSourceNode to the gainNode
// and the gainNode to the destination
gainNode.gain.setValueAtTime(0, audioCtx.currentTime);
source.connect(gainNode);
gainNode.connect(audioCtx.destination);

// set buttons to do something onclick
linearRampPlus.onclick = function() {
  gainNode.gain.linearRampToValueAtTime(1.0, audioCtx.currentTime + 2);
}

linearRampMinus.onclick = function() {
  gainNode.gain.linearRampToValueAtTime(0, audioCtx.currentTime + 2);
}

Working example here

它们也有不同类型的时序,比如指数而不是线性斜坡,我想这更适合这种情况。

【讨论】:

  • 很好的例子,但是你想要做什么 -> “我希望我的声音在停止之前降低音量”。在音量降低到 0 左右后,您是否找到任何方法来停止声音 (source.stop())?我正在尝试检测 linearRamp 函数的结束。但不幸的是,DOC 中没有关于此的任何内容。我可以设置一个间隔并检查 gain.value X 次,然后一旦该值接近 0,我就可以停止源。但我更愿意在 linearRamp 过程的“真正结束”处停止源。有什么想法吗?
  • @Faks 如果持续时间为 0.3 秒,您可以在 0.3 秒后停止。我不确定它是否会完美,但如果我没记错的话,我就是这么做的。如果你再大一点,声音应该是0,所以不应该有任何问题,不是吗?就像在 0.7 秒后停止一样。
  • 谢谢 ;) 这是我已经做过的,但这并不完美,如果函数本身可以在最后淡入淡出时进行回调会更好。另外:只是为使用带有 Cordova 的 Web 音频 API 的开发人员提供的信息。在 iOS 上,linearRampToValueAtTime() 函数有效,但是,如果您同时播放多个声音,这将导致扬声器上出现随机的吱吱声/嘎吱声/咔嗒声/脏音。如果您的应用同时针对 Android 和 iOS,您应该使用 2 个不同的函数,用于 Android 的 linearRampToValueAtTime(),然后在 iOS 的 SetInterval 上使用 gainNode.gain.value(在 Chrome 64 上已弃用)。
猜你喜欢
  • 2012-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-29
相关资源
最近更新 更多