Play sound in Angular 4

I am working on an Electron app with Angular 4. I want to play sound with certain actions. Is there a module or code for this? It can be in Angular 4, or if the electron provides some service for this, it should work too

As I want to play it with some actions, I cannot use the HTML tag and javascript audio ()

I want to play only 2-3 seconds, so no other features are required.

It can be an electron or Angular 4, any of them can work ...

+23
source share
6 answers

just did it in the project i'm working on (corner 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 refers to existing audio

+36
source

According to Robin's comment, I checked this link, which we can use 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(); 
+28
source

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

app.component.ts

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

app.component.html

  <audio #audioOption> <source src='../*.mp3' type="audio/mp3"> </audio> 
+16
source

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

 var sound = new Howl({ src: ['sound.mp3'] }); sound.play(); 
+3
source

Asmon code is good, but I think the real problem is that the Google Chrome policy has been updated, on this page https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#webaudio You can find the answer. In conclusion, attention should be paid to this.

Chrome startup rules are simple:

Muted auto play is always enabled. Autostart with sound is allowed if: The user interacted with the domain (click, click, etc.). On the desktop, the user threshold for the media engagement index is exceeded, which means that the user has previously played video with sound. On the mobile phone, the user [added the site to his home screen]. Top frames can delegate autoplay permission for their frames to allow autoplay with sound.
+1
source
 playSound(sound) { sound = "../assets/sounds/" + sound + ".mp3"; sound && ( new Audio(sound) ).play() } 

Where sound is the name of the file if you need this method for reuse.

0
source

Source: https://habr.com/ru/post/1269439/


All Articles