如何播放音频?

991

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

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


13
由于这是HTML5,所以有<audio>元素。该元素将具有适当的JS钩子,用于'play','pause'等操作... - Marc B
17
我敢打赌你正在想知道所有音频方法的文档在哪里:https://dev59.com/T2455IYBdhLWcg3wAvRI - Bryan Downing
22个回答

7
var song = new Audio();
song.src = 'file.mp3';
song.play();

5
我遇到了一些与音频Promise对象返回相关的问题,以及一些与用户交互声音相关的问题。最终我使用了这个小对象。
我建议在用户使用交互事件时尽可能接近播放声音。
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>

如果我使用JS触发自动播放,它在Safari上不能正常工作。 - maki10
1
@maki10 你好,我在 Safari 桌面版 12.0.3 (14606.4.5) 上测试了一下,这里可以正常工作: https://jsfiddle.net/xf5zyv4q/5/ - talsibony
我更新了我的问题链接 https://jsfiddle.net/6431mfb5/。对我来说,在Safari和更新版本中,自动播放只有第一次有效。 - maki10
由于您在没有用户交互的情况下调用它,自动播放不会在没有用户点击或触摸的情况下工作,请删除最后一行:soundPlayer.play('https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3'); - talsibony

4

我使用这种方法来播放声音...

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

3
const playAudio = (path = 'defaultPath') => new Audio(path).play()
playAudio('path')

欢迎来到 Stack Overflow!您的答案可以通过添加更多支持信息来改进。请[编辑]以添加进一步的细节,例如引用或文档,以便他人可以确认您的答案是正确的。您可以在帮助中心中找到有关如何编写良好答案的更多信息。 - Ethan
5
尽管额外的信息“可能”会改善这个答案,但这正是我在寻找的。有时候代码本身就是一个好答案 :-) - Loudenvier
3
尽管额外的信息“可能会”改善这个答案,但这正是我所寻找的。有时候代码本身就是一个很好的答案 :-) - Loudenvier

3
如果您希望在浏览器选项卡当前未被选择时仍能播放声音,则需要在页面加载时加载音频资源,如下所示:
var audio = new Audio('audio/path.mp3');

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

请查看此问题以获取更多详细信息。


2
您可以使用Web Audio API播放声音。有很多音频库,如howler.js、soundjs等。如果您不担心旧浏览器,则还可以检查http://musquitojs.com/。它提供了一个简单的API来创建和播放声音。
例如,要播放声音,您只需执行以下操作。
import $buzz from 'musquito';

const buzz = $buzz('gunfire.mp3');

buzz.play();

该库还支持音频精灵。

2
如果您希望在页面打开时播放音频,可以按照以下方法操作。

<script>
  function playMusic(){
  music.play();
  }
  </script>
<html>
  <audio id="music" loop src="sounds/music.wav" autoplay> </audio>
  </html>

and call this playMusic() whenever you need in your game code.


1

Just use this:

<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>

Sample:

<video controls="" autoplay="" name="media">
<source src="https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3" type="audio/mpeg">
</video>

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


这是一个简单、干净的答案。完全没有jQuery! - user11178735

0
在React中,您可以使用ref:
// typescript
const audRef = useRef(null);
const playAudio = () => {
  (audRef.current as any).play();
}
...
// html
<audio controls src={your_audio} ref={audRef} />
<button onClick={playAudio}>Play</button>

0

这是我在一项与婴儿人工智能相关的项目中想出来的一些 JavaScript 代码。希望这能对你有所帮助。

<!DOCTYPE html>
<html>
<head>
    <title>
        js prompt AI
    </title>
    <style>
        #button {
            border: 1px solid black;
            border-radius: 10px;
            font-size: 22px;
            height:65px;
            width:100px;
            text-align: center;
            line-height: 65px;
        }
    </style>
</head>
<body>

    <audio id="myAudio" src="./how_are_you.m4a"></audio>
    <p>To Interact with the AI please click the button</p>
    <div id=button>click</div>

    <script>

       var button = document.getElementById("button");
       function playBack() {
           button.addEventListener("click", function (){
            var talk = prompt("If you wish for the AI to respond type hi");
            var myAudio = document.getElementById("myAudio");

            if(talk === "hi") {
                    myAudio.play();
            }
           }) ;



       }
       playBack();
   </script>
</body>

</html>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接