首页 > 解决方案 > 如何暂停在其他地方开始的音频?

问题描述

我的音频是在对象属性的函数中创建的,但我需要从单独的对象属性的函数中暂停它。有没有一种简单的方法可以在不重组我的代码的情况下做到这一点?

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

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

标签: javascript

解决方案


由于正常的范围规则,该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();
    }
  }
}

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


推荐阅读