Play sound in Angular 4

前端 未结 7 1314
暗喜
暗喜 2020-12-12 22:17

I\'m working on an Electron app with Angular 4. I want to play sound on some specific action. Is there any module or code for that? It can be in the angular 4 o

相关标签:
7条回答
  • 2020-12-12 22:44

    just did this in a project am working (angular 4) and it worked

    playAudio(){
      let audio = new Audio();
      audio.src = "../../../assets/audio/alarm.wav";
      audio.load();
      audio.play();
    }
    this.playAudio();
    

    make sure the path is correct and references an existing audio

    0 讨论(0)
  • 2020-12-12 22:51

    updated: I had the same problem and used ViewChild reference with ElementRef to solve this.

    app.component.ts

    @ViewChild('audioOption') audioPlayerRef: ElementRef;
    
    onAudioPlay(){
      this.audioPlayerRef.nativeElement.play();
    }
    

    app.component.html

       <audio #audioOption>
           <source src='../*.mp3' type="audio/mp3">
       </audio>
    
    0 讨论(0)
  • 2020-12-12 22:53

    As per Robin's comment, i have checked that link we can use it using the audio() object in the ts file like this:

    this.audio = new Audio();
    this.audio.src = "../../../assets/sounds/button_1.mp3";
    this.audio.load();
    this.audio.play();
    
    0 讨论(0)
  • 2020-12-12 22:56

    You could try using howler.js
    You can install it to your project with npm install --save howler and play a sound like this:

    var sound = new Howl({
      src: ['sound.mp3']
    });
    
    sound.play();
    
    0 讨论(0)
  • 2020-12-12 23:01

    The Asmon code is good, but I think that the real problem is that the Google Chrome policy was updated, on this page https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#webaudio you can find The answer In summary, the focus should be on this.

    Chrome's autoplay policies are simple:

  • Muted autoplay is always allowed.
  • Autoplay with sound is allowed if:
  • User has interacted with the domain (click, tap, etc.).
  • On desktop, the user's Media Engagement Index threshold has been crossed, meaning the user has previously play video with sound.
  • On mobile, the user has [added the site to their home screen].
  • Top frames can delegate autoplay permission to their iframes to allow autoplay with sound.
0 讨论(0)
  • 2020-12-12 23:03
    playSound(sound) {
        sound = "../assets/sounds/" + sound + ".mp3";
        sound && ( new Audio(sound) ).play()
      }
    

    Where sound is the file name if you need this method to be reusable.

    0 讨论(0)
  • 提交回复
    热议问题