如何不间断地播放声音? [英] How to play a sound continuously without break?

查看:282
本文介绍了如何不间断地播放声音?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在基于浏览器的游戏中播放车辆驱动的声音(连续不断)。

我的.wav文件长度为1秒,从头到尾的频率相同。但是在下一次迭代之前声音会稍微休息一下。

这是代码:

I am trying to play a vehicle driven sound in a browser based game (continuously without break).
My .wav file length is 1 second and has same frequency from beginning to end. But sound takes a little break before next iteration.
Here is code:

function playSound()
{
    //alert("");
    myAudio = new Audio('http://ithmbwp.com/feedback/SoundsTest/sounds/tank_driven.wav'); 
    if (typeof myAudio.loop == 'boolean')
    {
        myAudio.loop = true;
    }
    else
    {
        myAudio.addEventListener('ended', function() {
            this.currentTime = 0;
            this.play();
        }, false);
    }
    myAudio.volume = 0.3;
    myAudio.play();
}

任何人都可以帮我连续播放声音吗?

版本


您可以访问我的页面此处观察问题。

Can anyone help me to play the sound continuously?

Edition

You can visit my page here to observe the problem.

window.onload = function() {
  playSound();
};

function playSound()
{
	//alert("");
	myAudio = new Audio('http://ithmbwp.com/feedback/SoundsTest/sounds/tank_driven.wav'); 
	if (typeof myAudio.loop == 'boolean')
	{
		myAudio.loop = true;
	}
	else
	{
		myAudio.addEventListener('ended', function() {
			this.currentTime = 0;
			this.play();
		}, false);
	}
	myAudio.volume = 0.3;
	myAudio.play();
}

<h3 style="font-family:verdana;">Please listen the sound break.</h3>
<h3 style="font-family:verdana;">It should be continuous.</h3>

推荐答案

使用AudioContext API及其< a href =https://developer.mozilla.org/en-US/docs/Web/API/AudioBufferSourceNode =nofollow noreferrer> bufferSourceNode 界面,可以无缝循环播放声音。

Use the AudioContext API and its bufferSourceNode interface, to have seamlessly looped sounds.

请注意,您还需要正确编辑音频以避免噼啪声和声音片段,但您的音频似乎不错。

Note that you'll also need your audio to be correctly edited to avoid crackles and sound clips, but yours seems good.

const aCtx = new AudioContext();
let source = aCtx.createBufferSource();
let buf;
fetch('https://dl.dropboxusercontent.com/s/knpo4d2yooe2u4h/tank_driven.wav') // can be XHR as well
  .then(resp => resp.arrayBuffer())
  .then(buf => aCtx.decodeAudioData(buf)) // can be callback as well
  .then(decoded => {
    source.buffer = buf = decoded;
    source.loop = true;
    source.connect(aCtx.destination);
    check.disabled = false;
  });

check.onchange = e => {
  if (check.checked) {
    source.start(0); // start our bufferSource
  } else {
    source.stop(0); // this destroys the buffer source
    source = aCtx.createBufferSource(); // so we need to create a new one
    source.buffer = buf;
    source.loop = true;
    source.connect(aCtx.destination);
  }
};

<label>play audioBuffer</label>
<input type="checkbox" id="check" disabled><br><br>
Just to compare <audio src="https://dl.dropboxusercontent.com/s/knpo4d2yooe2u4h/tank_driven.wav" loop controls>

或使用您的代码段:

window.onload = function() {
  playSound();
};

function playSound() {
  if (AudioContext) {
    out.textContent = "yeah now it's continuous !!!";
    playAsAudioBuffer();
  } else {
    out.textContent = "you should consider updating your browser...";
    playNormally();
  }
}

function playAsAudioBuffer() {
  var aCtx = new AudioContext();
  // here is the real audioBuffer to sound part
  function ondecoded(buf) {
    var source = aCtx.createBufferSource();
    source.buffer = buf;
    source.loop = true;
    var gainNode = aCtx.createGain();
    gainNode.gain.value = .3; // here you set the volume
    source.connect(gainNode);
    gainNode.connect(aCtx.destination);
    source.start(0);
  }

  var xhr = new XMLHttpRequest();
  xhr.onload = function() {
    aCtx.decodeAudioData(this.response, ondecoded);
  };
  xhr.onerror = playNormally;
  xhr.responseType = 'arraybuffer';
  xhr.open('get', 'https://dl.dropboxusercontent.com/s/knpo4d2yooe2u4h/tank_driven.wav');
  xhr.send();
}

// An ugly workaround in case of old browsers
function playNormally() {
  var myAudios = [new Audio('https://dl.dropboxusercontent.com/s/knpo4d2yooe2u4h/tank_driven.wav')];
  myAudios.push(new Audio(myAudios[0].src));
  myAudios.forEach(function(a){
    a.addEventListener('timeupdate', checkTime);
    a.volume = 0.3;
    });
   
  function checkTime(){
    if(this.currentTime > this.duration - 0.4){
      startNext(this);
      }
    }
  var current = 0;
  function startNext(el){
    current = (current + 1) % 2;
    myAudios[current].play();
    el.currentTime = 0;
    el.pause();
    }
  myAudios[0].play();
}

<h3 id="out"></h3>

这篇关于如何不间断地播放声音?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆