播放新音乐时,如何使所有其他音频播放器停止播放?(角度)

时间:2019-08-27 19:01:37

标签: html angular typescript

我正在建立一个网站来围绕用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() { }

}

1 个答案:

答案 0 :(得分:0)

无论您何时玩新的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>