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

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


当前回答

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

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

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>

其他回答

如果你想在页面打开时播放音频,那么就像这样做。

<脚本> 函数playMusic () { music.play (); } > < /脚本 < html > <audio id="music"循环src="sounds/music.wav" autoplay> </audio> .wav . < / html > 并在游戏代码中调用这个playMusic()。

以下是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。

就用这个吧:

<video controls="" autoplay="" name="media"><source src="Sound URL Here" type="audio/mpeg" /></video>

或者,简单点说:

<video controls="" autoplay="" name="media">

<source src="Sound URL Here" type="audio/mpeg" />

</video>

示例: <视频控制="" autoplay="" name="media"> <source src="https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3" type="audio/mpeg"> . < /视频>

不知道这是否适用于除Chrome 73之外的其他浏览器!!

这很简单,只需要获取音频元素并调用play()方法:

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

看看这个例子:http://www.storiesinflight.com/html5/audio.html

这个站点还提供了一些其他很酷的功能,比如load()、pause()和音频元素的其他一些属性。

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