ionic 2 how to play sound effects

2019-04-11 20:33发布

I'm actually developping an application with Ionic 2 / angular2.

It's an app to learn english tenses that runs with a SQLite database.

I would like to add a background sound that plays in loop all the time.

The users can exercice themselves with a quizz. I would like to play sound effects when the user submit his answer.

Two different sounds : one for good and one for bad answers.

I've already tried with Nativeaudio, angular-audio and Ionic audio modules but each times the documentation is based on javascript and not typescript, or it is not helpfull.

With native audio, I've succeed once playing the background sound but after it didn't work at all and came up with an error : EXCEPTION: Uncaught (in promise): A reference does not exist for the specified audio id.

For the other solutions (angular-audio and ionic-audio) either i didn't get how to install it either, once installed, I had nothing : no sound and no error.

Thank you very much for your help.

标签: audio ionic2
1条回答
一纸荒年 Trace。
2楼-- · 2019-04-11 20:37

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

Reference: https://ionicframework.com/docs/native/native-audio/

查看更多
登录 后发表回答