Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play mp3 with Angular 2?

Tags:

angular

ionic2

I want to write a small ionic/angular application where I load a dynamic mp3 file from a remote server and play it for pressing a button OR if it is checked I play it automaticly. I tried to use the simple <audio></audio> but i am not sure if this is the good way for this...

code:

html

<audio id="player">
<source id="source" src="http://remote.address.com/example.mp3"></source>
</audio>

javascript

play(){
var audio= document.getElementById('player');
audio.play();
}
like image 941
MegaX Avatar asked Nov 22 '15 19:11

MegaX


2 Answers

You can create a new Audio element in the Javascript code ... not in HTML

for example :

var audio = new Audio();
audio.src = "http://remote.address.com/example.mp3";
audio.load();
audio.play();
like image 60
reda igbaria Avatar answered Oct 21 '22 11:10

reda igbaria


If you want run sound in Ionic-2 / Angular-2 mobile application .

Follow Ionic 2 guide here

Install:

ionic plugin add --save cordova-plugin-nativeaudio
npm install --save @ionic-native/native-audio

Usage:

import { NativeAudio } from '@ionic-native/native-audio';

    constructor(private nativeAudio: NativeAudio) { }



    this.nativeAudio.preloadSimple('uniqueId1','path/to/file.mp3').then(onSuccess, onError);
    this.nativeAudio.preloadComplex('uniqueId2','path/to/file2.mp3', 1, 1, 0).then(onSuccess, onError);

    this.nativeAudio.play('uniqueId1').then(onSuccess, onError);

    // can optionally pass a callback to be called when the file is done playing
    this.nativeAudio.play('uniqueId1', () =>console.log('uniqueId1 is done playing'));

source-1 : https://stackoverflow.com/a/43917441/6786941

like image 34
Amr Ibrahim Avatar answered Oct 21 '22 12:10

Amr Ibrahim