How to play audio?

前端 未结 20 3230
抹茶落季
抹茶落季 2020-11-21 13:37

I am making a game with HTML5 and JavaScript.

How could I play game audio via JavaScript?

20条回答
  •  别那么骄傲
    2020-11-21 14:07

    I had some issues related to audio promise object returns and some issues related to user interaction with sounds I end up using this small object,

    I would recommend to implement the play sounds the closest to the interaction event user is using.

    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;
              });
          }
      }
    };
    

    And implement it as follow:

    
    

提交回复
热议问题