Cordova provides a plugin to play sounds in your mobile application. It can record an audio file and also play back audio file on the device.
Installing the plugin:
cordova plugin add cordova-plugin-media
It has a Media constructor. You can check by showing it on device ready.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(Media);
}
var media = new Media(src, mediaSuccess, [mediaError], [mediaStatus]);
where:
src : It is a path for audio file.
mediaSuccess : optional. It is a callback function that is executed when a media file completes its current action.
mediaError : optional. It is executed when there is some error.
mediaStatus : optional. It is executed when there is need to change status of audio file.
mediaStatus constants:
* Media.MEDIA_NONE = 0;
* Media.MEDIA_STARTING = 1;
* Media.MEDIA_RUNNING = 2;
* Media.MEDIA_PAUSED = 3;
* Media.MEDIA_STOPPED = 4;
There are some methods which can be used for audio files:
media.play: It is used to start audio file.
media.pause: It is used to pause playback audio file.
media.stop: It is used to stop audio file.
media.setVolume: It is used to set the audio file volume.
Example:
// Play audio file
function playAudio(url) {
// Play the audio file at url
var my_media = new Media(url,
// success callback
function() {
console.log("playAudio():Audio Success");
},
// error callback
function(err) {
console.log("playAudio():Audio Error: "+err);
});
// Play audio
my_media.play();
// Mute volume after 2 seconds
setTimeout(function() {
my_media.setVolume('0.0');
}, 2000);
// Set volume to 1.0 after 5 seconds
setTimeout(function() {
my_media.setVolume('1.0');
}, 5000);
}
0 Comment(s)