Angular 中的 Howler,如何让声音停止

问题描述

我在我的 Angular 应用中使用了 howler.js。现在我有两个声音同时播放。我想要的是我的 drum 声音在 sound 停止时停止。 我确实得到了 ('stop') console.log 但我的 stop() 函数没有被触发。 我已经创建了一个按钮来触发,它工作正常,但这不是我想要实现 stop() 函数的方式。

import { Component } from '@angular/core';
import { Howl } from 'howler'

@Component({
  selector: 'my-app',templateUrl: './app.component.html',styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  sound = new Howl({
    src: ['https://www.kozco.com/tech/piano2-CoolEdit.mp3'],html5 :true,onend: function() {
      console.log('stop')
      this.stop()}
  });

  drum = new Howl({
    src: ['https://freesound.org/data/previews/381/381353_1676145-hq.mp3'],html5: true,loop: true,volume: 0.2,})

  play() {
    this.drum.play();
    this.sound.play();
    }

  stop() {
    this.drum.stop();
    this.drum.unload();
    this.sound.unload()

  }
}

当另一个声音停止时,我如何才能使声音停止?

解决方法

你应该改用箭头函数:

this.sound.on('end',() => {console.log("stop");
                            this.stop()}
);

箭头函数的全部意义在于它们使用其父作用域的 this