如何暂停从其他地方开始播放的音频?

时间:2019-12-01 22:55:56

标签: javascript

我的音频是在对象属性的功能内创建的,但我需要在单独的对象属性的功能内将其暂停。有没有一种简便的方法,而无需重新构造我的代码?

let audio = {
  train: function() {
    let train = new Audio(
      "audio link"
    );
    train.play();
  }
}

let otherObject = {
   pauseAudio: function() {
   Audio.pause();
}

1 个答案:

答案 0 :(得分:0)

由于正常的作用域规则,train元素需要暴露在audio对象之外,以便其他外部变量(如otherObject)能够看到它。一种可能性是audio拥有另一个属性,一个子对象,其属性指向Audio实例:

const audio = {
  audioElements: {},
  train: function() {
    this.audioElements.train = new Audio(
      "audio link"
    );
    this.audioElements.train.play();
  }
}

const otherObject = {
  pauseAudio: function() {
    for (const audioElm of Object.values(audio.audioElements)) {
      audioElm.pause();
    }
  }
}

尚不清楚每次调用train时是否真的要制作单独的音频元素。如果没有,请首先检查该属性是否存在于音频持有人对象上:

const audio = {
  audioElements: {},
  train: function() {
    if (!this.audioElements.train) {
      this.audioElements.train = new Audio(
        "audio link"
      );
    }
    this.audioElements.train.play();
  }
}

let otherObject = {
  pauseAudio: function() {
    for (const audioElm of Object.values(audio.audioElements)) {
      audioElm.pause();
    }
  }
}

这将很容易扩展为任何数量的音频元素/方法。