簡體   English   中英

在HTML5中,我可以同時多次播放同一個聲音嗎?

[英]In HTML5, can I play the same sound more than once at the same time?

我正在制作一個游戲,其中經常播放聲音。 我注意到聲音在播放時不會再次播放。 例如,玩家與牆壁發生碰撞,播放“砰”的一聲。 但是,如果玩家撞到一堵牆,然后又迅速撞到另一堵牆,只會播放“砰”的一聲,我相信這是因為第一個聲音沒有結束。 真的嗎? 我應該如何避免這種情況? 我想將聲音預加載三次,總是播放那個聲音的不同副本,但這似乎很愚蠢......

解決了:

事實證明我是對的......你需要預加載多個版本的聲音然后循環播放它們。

代碼:

var ns = 3; //The number of sounds to preload. This depends on how often the sounds need to be played, but if too big it will probably cause lond loading times.
var sounds = []; //This will be a matrix of all the sounds

for (i = 0; i < ns; i ++) //We need to have ns different copies of each sound, hence:
    sounds.push([]);

for (i = 0; i < soundSources.length; i ++)
    for (j = 0; j < ns; j ++)
        sounds[j].push(new Audio(sources[i])); //Assuming that you hold your sound sauces in a "sources" array, for example ["bla.wav", "smile.dog" "scream.wav"] 

var playing = []; //This will be our play index, so we know which version has been played the last.

for (i = 0; i < soundSources.length; i ++)
    playing[i] = 0; 

playSound = function(id, vol) //id in the sounds[i] array., vol is a real number in the [0, 1] interval
{
    if (vol <= 1 && vol >= 0)
        sounds[playing[id]][id].volume = vol;
    else
        sounds[playing[id]][id].volume = 1;

    sounds[playing[id]][id].play();
    ++ playing[id]; //Each time a sound is played, increment this so the next time that sound needs to be played, we play a different version of it,

    if (playing[id] >= ns)
        playing[id] = 0;
}

您可以克隆音頻元素。 我不知道您是否可以同時播放多個聲音,但是這是您可以多次播放聲音而不下載一次的方法。

var sound = document.getElementById("incomingMessageSound")
var sound2 = sound.cloneNode()
sound.play()
sound2.play()

我知道這適用於chrome,這是我唯一需要的地方。 祝好運!

多次加載聲音以模擬復音。 以循環方式播放它們。 matthewtoledo.com上查看我的演示。 具體來說,函數_initSoundBank()

是的,單個<audio>對象一次只能播放一個曲目。 請考慮<audio>對象具有currentTime屬性,該屬性指示音頻軌道的當前位置:如果<audio>對象可以播放多個軌道一次,那么currentTime將反映什么值?

請參閱我的解決方案,以獲取有關此問題的超集,有關Java演奏中的聲音播放是否繁重? (基本上,添加具有相同聲音的重復<audio>標簽。)

盡管目前僅在FireFox和Chrome中實現,但將來您應該使用WebAudio API ,該API專為瀏覽器中的游戲和音頻應用程序而設計。

您可以在那里多次播放任何聲音,並用它來做其他有趣的事情。

一個很好的教程在這里: http : //www.html5rocks.com/en/tutorials/webaudio/games/

class SoundPool {
  pool : HTMLAudioElement[] = [];
  constructor(sound:HTMLAudioElement) {
    this.pool.push(sound);
  }

  play() {
    let found = false;
    for(var i=0; i<this.pool.length; i++) {
      if( this.pool[i].paused) {
        this.pool[i].play();
        found=true;
        break;
      }
    }
    if(!found) {
      let a = this.pool[0].cloneNode() as HTMLAudioElement;
      a.play();
      this.pool.push(a);
    }

  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM