首页 > 解决方案 > 播放新音频时如何使所有其他音频播放器停止?(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() { }

}

标签: htmlangulartypescript

解决方案


每当您玩新游戏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>


推荐阅读