Music and sound effects on your Apache Cordova / Phonegap mobile application is not seem to be a headpain. The recommended plugin works great for me with both iOS and Android.
With Native Audio plugin you can integrate this feature to your project in a few minutes. I’ll show you how. Also I’ll provide you an example of AngularJS service to control audio effects in your app.
- Install native audio plugin
1 |
cordova plugin add cordova-plugin-nativeaudio |
- All sounds you’re planning to use in your app must be preloaded before use. Plugin provides two functions to do this. The first function can be used to preload short sound (for example sound effect for button click)
1 |
preloadSimple: function ( id, assetPath, successCallback, errorCallback) |
The second function is optimized for long sounds loading (such as background music)
1 |
preloadSimple: function ( id, assetPath, successCallback, errorCallback) |
Both functions are available via window.plugins.NativeAudio.preloadXXXX. id is unique sound identifier which will be used to control sound playback.
- Playback control is really simple with Cordove Native Audio plugin:
1 2 3 |
play: function (id, successCallback, errorCallback, completeCallback) loop: function (id, successCallback, errorCallback) stop: function (id, successCallback, errorCallback) |
You need to pass the same id as you passed to preloadXXX functions.
- For AngularJS/Ionic framework applications you can use a service like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
app.service('AudioService', function () { var soundsLoaded = { bg: false, click: false }, startBgPlay: false; //startBgPlay is a flag. it will be set to true if bg sound is not yet loaded, but playBg functions is called. //this allow us to start bg music as soon, as background music sample will be loaded return { init: function () { //preload all samples on load window.plugins.NativeAudio.preloadSimple('click', 'sounds/click.mp3', function (msg) { soundsLoaded.click = true; }, function(msg) {}); window.plugins.NativeAudio.preloadComplex('bg', 'sounds/bgmusic.mp3', 1, 1, 0, function (msg) { soundsLoaded.bg = true; if (startBgPlay) { window.plugins.NativeAudio.loop('bg', function(msg){}, function(msg){ console.log(msg); }); } }, function(msg) { console.log(arguments); } ); }, playClick: function () { if (soundsLoaded.click) { window.plugins.NativeAudio.play('click', function(msg){}, function(msg){}); } }, playBg: function () { if (soundsLoaded.bg) { window.plugins.NativeAudio.loop('bg', function(msg){}, function(msg){}); } else { startBgPlay = true; } }, pauseBg: function () { if (soundsLoaded.bg) { window.plugins.NativeAudio.stop('bg', function(msg){}, function(msg){}); } } } }); |
- You can read any other docs on Native Audio Plugin page on Github
One thought on “Music and Sounds With Your Cordova/Phonegap Application”