Angular2如何播放mp3?

How to play mp3 with Angular 2?

我想写一个小的 ionic/angular 应用程序,我从远程服务器加载一个动态 mp3 文件并通过按下按钮播放它,或者如果选中它我会自动播放它。我尝试使用简单的 <audio></audio> 但我不确定这是否是解决此问题的好方法...

代码:

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();
}

您可以在 Javascript 代码中创建一个新的音频元素...而不是在 HTML

例如:

var audio = new Audio();
audio.src = "http://remote.address.com/example.mp3";
audio.load();
audio.play();

如果您想在 Ionic-2 / Angular-2 移动应用程序中获得 运行 声音。

Follow Ionic 2 guide here

安装:

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

用法:

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'));

我试过@reba 的回答,但它在移动浏览器上不起作用,或者可能有自动播放策略停止播放音频文件。所以我创建了 audio 元素并动态修改了 src,比如

<audio id="player">
   <source></source>
</audio>

在Angular,

play(){
   let audio= document.getElementById('player');
   audio.src = "http://remote.address.com/example.mp3";
   audio.load();
   audio.play();
}

注意:如果你不想在页面上显示音频标签,那么你可以[hidden]