我正在使用HTML5和JavaScript制作游戏。

如何通过JavaScript播放游戏音频?


当前回答

如果你想在当前浏览器选项卡未被选中的情况下也能播放声音,你必须在页面加载时加载音频资源。

像这样:

var audio = new Audio('audio/path.mp3');

function playSound(){
    audio.play();
}

请参阅这个问题了解更多细节

其他回答

非常简单的解决方案,如果你有一个像下面这样的HTML标签:

<audio id="myAudio" src="some_audio.mp3"></audio>

只需使用JavaScript来播放它,就像这样:

document.getElementById('myAudio').play();

我有一些关于音频承诺对象返回的问题和一些关于用户与声音交互的问题,我最终使用了这个小对象,

我建议执行最接近用户使用的交互事件的播放声音。

var soundPlayer = {
  audio: null,
  muted: false,
  playing: false,
  _ppromis: null,
  puse: function () {
      this.audio.pause();
  },
  play: function (file) {
      if (this.muted) {
          return false;
      }
      if (!this.audio && this.playing === false) {
          this.audio = new Audio(file);
          this._ppromis = this.audio.play();
          this.playing = true;

          if (this._ppromis !== undefined) {
              this._ppromis.then(function () {
                  soundPlayer.playing = false;
              });
          }

      } else if (!this.playing) {

          this.playing = true;
          this.audio.src = file;
          this._ppromis = soundPlayer.audio.play();
          this._ppromis.then(function () {
              soundPlayer.playing = false;
          });
      }
  }
};

并执行如下:

<button onclick="soundPlayer.play('https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3');">Play</button>

我用这个方法播放了一个声音…

var audioElement;
if(!audioElement) {
  audioElement = document.createElement('audio');
  audioElement.innerHTML = '<source src="' + '/audio/sound.mp3'+ '" type="audio/mpeg" />'
}
audioElement.play();

以下是2020年你看到错误时的解决方案:

[Error] Unhandled Promise Rejection: NotSupportedError:不支持该操作。 (匿名函数) rejectPromise 玩 (匿名函数)(testaudio.html:96) 调度(jquery-3.4.1.min.js 2:42577):


<div onclick="new Audio('/assets/test.mp3').play()">aaa</div>

不要太圆滑,觉得这是老式的oclick,我把它移到下面的jQuery或外部JavaScript文件中。没有。它需要是一个onclick。

new Audio('./file.mp3').play()