html - 播放新音频时如何使所有其他音频播放器停止?(Angular)
问题描述
我正在制作一个围绕在 Angular 中播放我的音乐的网站,我想让其他音频播放器在播放新音乐时停止。有人有这个脚本吗?
HTML
<div>
<img src="{{ image }}" alt="Default Grey Box" class="mb-3" />
<h3>{{ header }}</h3>
<p>{{ description }}</p>
<audio title="{{ header }}" type="audio/mp3" preload="metadata" controls="true" src='{{ audioref }}' > Radio {{ header }} </audio>
</div>
打字稿
import { Component, OnInit, Input, ElementRef, HostListener } from '@angular/core';
@Component({
selector: 'app-grid-box',
templateUrl: './grid-box.component.html',
styleUrls: ['./grid-box.component.css']
})
export class GridBoxComponent implements OnInit {
@Input() key: number;
@Input() header: string;
@Input() description: string;
@Input() image: string;
@Input() audioref: string;
constructor() { }
ngOnInit() { }
}
解决方案
每当您玩新游戏audio
时,您都可能会触发一个事件。在该事件处理程序中访问audio
元素并显式调用pause()
其他audio
元素。
document.addEventListener('play', function(e){
var players = document.getElementsByTagName('audio');
[...players].forEach(player => {
if(e.target != player){
player.pause();
}
});
});
这是一个演示:
<audio controls="true" id="a1"
src="https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_700KB.mp3"></audio>
<audio controls="true" id="a1"
src="https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_1MG.mp3"></audio>
<audio controls="true" id="a1"
src="https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_2MG.mp3"></audio>
<script>
var players = document.getElementsByTagName('audio');
Array.from(players).forEach(player => {
player.addEventListener('play', playHandler)
});
function playHandler(e) {
[...players].forEach(player => {
if (e.target != player) {
player.pause();
}
});
}
</script>
推荐阅读
- python - 如何使用 Python API 删除 Cassandra 中的记录?
- logic - 一阶逻辑和猜想范式
- android - 空对象引用上的 Android ViewPager
- data-partitioning - dolphindb分布式数据库无法写入数据
- elasticsearch - 3 节点 Elasticsearch 集群 V 7xxx
- c# - 重定向到另一个页面时出现 ASP .NET 错误:试图读取或写入受保护的内存。这通常表明其他内存已损坏
- reactjs - 当我单击 React 中的完成按钮时如何删除帖子
- python - 比较 2 个文件中的字符串行
- angular - Angular 7:从 Angular 库中导出 Angular 元素
- angular - 任务执行完成时如何从前一个组件通知当前路由组件?