How to play the audio in ionic?

I what to play a audio , how to use ?

You can use native plugin of ionic:

https://ionicframework.com/docs/v2/native/nativeaudio/

import {NativeAudio} from 'ionic-native';

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

NativeAudio.play('uniqueId1').then(onSuccess, onError);

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

NativeAudio.loop('uniqueId2').then(onSuccess, onError);

NativeAudio.setVolumeForComplexAsset('uniqueId2', 0.6).then(onSuccess,onError);

NativeAudio.stop('uniqueId1').then(onSuccess,onError);

NativeAudio.unload('uniqueId1').then(onSuccess,onError);

Can you out some path example ?
I put mp3 file to src/app/assets/alarm.mp3
and in code
NativeAudio.preloadSimple(‘uniqueId1’, ‘assets/alarm.mp3’).then(
but get error ‘A reference does not exist for the specified audio id.’

path: src/assets/audio/file.mp3

in code

NativeAudio.preloadSimple(‘uniqueId1’, ‘assets/audio/file.mp3’).then(…

Not sure to which version this belongs, but at the moment ( Ionic 3.x.x ) there’s no ionic-native to import from.

Can you please update your answer ?

if you’ve installed the NativeAudio plugin, try this :

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

To add to this answer, ionic-native-audio is building on the Cordova native audio plugin maintained by floatinghotpot on GitHub and it hasn’t been updated lately so you should make sure to use the complex loading if you’re going to be building your ionic app for iOS. Simple loading is broken for most purposes and it looks unlikely that it will be fixed