javascript - 如何暂停在其他地方开始的音频?
问题描述
我的音频是在对象属性的函数中创建的,但我需要从单独的对象属性的函数中暂停它。有没有一种简单的方法可以在不重组我的代码的情况下做到这一点?
let audio = {
train: function() {
let train = new Audio(
"audio link"
);
train.play();
}
}
let otherObject = {
pauseAudio: function() {
Audio.pause();
}
解决方案
由于正常的范围规则,该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();
}
}
}
这将很容易扩展到任意数量的音频元素/方法。
推荐阅读
- swift - ReactiveCocoa 内存泄漏 - UIButton 的 CocoaAction 防止 MVVM 对象反初始化
- c++ - 模板内嵌套类型名称的流式运算符重载
- java - 编程端ActionBar中可绘制的后退箭头ID
- java - 如何在 JRuby 中加载已编译的 Java 类?
- java - 瞬态内存中的 Java Card 对象实例
- ruby-on-rails - Rails:对 Rack::Timeout::RequestTimeoutException 进行故障排除
- symfony - 如何使用 RabbitMQ 对 API 请求进行排队
- python - 使用 MNIST 数据格式进行机器学习分类?
- apache - 如果使用任何 IE 浏览器,将网站的所有页面重定向到页面 - htaccess
- android - 尝试在空对象引用上调用虚拟方法“java.lang.Object org.appcelerator.kroll.KrollDict.get(java.lang.Object)”