
In this tutorial we will look at Intel XDK’s Audio APIs. Most apps require sound to be played therefore exploring this API is very important. In this tutorial we will first learn how to include Intel XDK audio plugin in our app, then explore various audio apis and then we will finish the tutorial by creating a music player app.
Including Intel XDK Player Plugin
Before we start coding you need to make sure you have included Intel XDK player plugin which exposes all the sound APIs.
Audio File Format
You should always consider to play MP3 audio format because all devices support MP3. In case you are planning to play ACC or OGG then every device won’t be able to play.
Downloading an MP3 File and Putting it in WWW Directory
Before we start exposing this plugin we need to have a MP3 file in our application’s WWW directory for testing. You can either download a mp3 file manually and copy it or else download a MP3 file using JavaScript into the WWW directory.
For this tutorial I have a sound.mp3 file in sounds directory inside WWW directory.
Playing a MP3 File in Background
Here is the code to play an MP3 file which resides in WWW directory
{
//Parameters:
//1. File path relative to the WWW directory
//2. Loop or not.
intel.xdk.player.startAudio("sounds/sound.mp3", false);
}
document.addEventListener("intel.xdk.player.audio.start", function(){
//started playing audio in background
}, false);
document.addEventListener("intel.xdk.player.audio.stop", function(){
//Playing audio finished. Its also fired when intel.xdk.player.stopAudio() is called.
}, false);
document.addEventListener("intel.xdk.player.audio.busy", function(){
//intel.xdk.player.startAudio is already playing an another audio file
}, false);
document.addEventListener("intel.xdk.player.audio.error", function(){
//an error occured so audio cannot be played
}, false);
If you want to stop the audio played by intel.xdk.player.startAudio, you can do this using this code
{
//stops audio if intel.xdk.player.startAudio is playing any. Then it fires the intel.xdk.player.audio.stop event.
intel.xdk.player.stopAudio();
}
While the MP3 file is playing you can seek using this code
intel.xdk.player.setAudioCurrentTime(30);
document.addEventListener("intel.xdk.player.audio.currenttime.set", function(){
//current position of the audio
alert('Audio Current Time: ' + intel.xdk.player.audioInfo.currentTime);
}, false);
You can continuously watch the current position of the audio using this code
alert('Audio Current Time: ' + intel.xdk.player.audioInfo.currentTime);
}
// start a watch on the current audio track. Callback is fired every 1 second. Make sure u fire this function after intel.xdk.player.startAudio
var watchID = intel.xdk.player.watchAudioCurrentTime(watch, 1000);
You can also find the length of the audio
intel.xdk.player.startAudio doesn’t provide any UI therefore you need to build your own music player UI so that user can control the playing of audio.
While playing a music using intel.xdk.player.startAudio if user locks the screen or changes app state to background then audio stops playing therefore intel.xdk.player.startAudio is not a good choice to create a music player app instead its a good choice if you want to play background music while app is running in foreground.
Playing MP3 using Default Music Player
Intel XDK does provide APIs to play music using device’s default music player. Here is the code to play a mp3 file using device’s default music player. Music player is launched inside the app and music is played.
{
//this function launches default mp3 player and plays the sound.mp3 music file.
intel.xdk.player.playPodcast("http://labs.qnimate.com/sound.mp3");
}
document.addEventListener("intel.xdk.player.podcast.start", function(){
//started playing music
alert("start");
}, false);
document.addEventListener("intel.xdk.player.podcast.stop", function(){
//music finished or player closed
alert("stop");
}, false);
document.addEventListener("intel.xdk.player.podcast.error", function(){
//error occured therefore music cannot be played
alert("error");
}, false);
document.addEventListener("intel.xdk.player.podcast.busy", function(){
//another music is already being played
alert("busy");
}, false);
The music file must be there is local or remote web server because intel.xdk.player.playPodcast takes a complete URL to a mp3 file for playing it. Some music apps allow users to download mp3 files, in that case you need to download the file into WWW directory and then provide the localhost URL to the file.
While playing a music using intel.xdk.player.playPodcast if user locks the screen or changes app state to background then also the music continues playing. This is what makes it a good choice for creating a music player app.
Here is the screenshot on how the player looks in the app
In Android the above code continues playing music even if user presses home button and takes the app to background state. But in iOS the sound stops when user presses the home button. So if you are building a cordova hybrid app then you need to use Background Audio plugin for iOS.
But when you are building a legacy app you can set background audio permission for playing audio in background.
This is how you set audio permission for iOS
This is how you set audio permission for Android
This method is great for creating a music player app. But the problem with this method is that it doesn’t allow player UI customization and also you need to pause the player to change track.
HTML5 Audio API
HTML5 audio api’s can also be used to play music but they aren’t a good choice for creating a music app. Because they stop playing when user locks the screen or changes app state to background. They are good as long as app is open.
Cordova Media Plugin
Many Intel XDK APPs use cordova media plugin to play music. Cordova Media APIs provide similar kinds of interface as intel.xdk.player.startAudio. Benefit of using cordova media plugin from intel.xdk.player.startAudio is that it continuous playing of music even if screen is locked. The default music player is displayed when screen is locked.
This plugin also lets you seek the audio manually. Therefore this plugin is considered the best way to build a music player app.
Here is an example code for playing music using Cordova Media Plugin.
<html>
<head>
<title></title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<style>
@-ms-viewport { width: 100vw ; zoom: 100% ; }
@viewport { width: 100vw ; zoom: 100% ; }
@-ms-viewport { user-zoom: fixed ; }
@viewport { user-zoom: fixed ; }
</style>
<script src="lib/ft/fastclick.js"></script>
<link rel="stylesheet" href="css/app.css">
</head>
<body>
<a href="#" class="btn large" onclick="playAudio('http://labs.qnimate.com/sound.mp3');">Play Audio</a>
<a href="#" class="btn large" onclick="pauseAudio();">Pause Playing Audio</a>
<a href="#" class="btn large" onclick="stopAudio();">Stop Playing Audio</a>
<p id="audio_position"></p>
<script src="intelxdk.js"></script>
<script src="cordova.js"></script>
<script src="xhr.js"></script>
<script src="js/app.js"></script>
<script src="js/init-app.js"></script>
<script src="js/init-dev.js"></script>
<script>
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
playAudio("http://labs.qnimate.com/sound.mp3");
}
// Audio player
//
var my_media = null;
var mediaTimer = null;
// Play audio
//
function playAudio(src) {
if (my_media == null) {
// Create Media object from src
my_media = new Media(src, onSuccess, onError);
} // else play current audio
// Play audio. playAudioWhenScreenIsLocked make sure the audio is playing even if screen is locked.
my_media.play({ playAudioWhenScreenIsLocked : true });
// Update my_media position every second
if (mediaTimer == null) {
mediaTimer = setInterval(function() {
// get my_media position
my_media.getCurrentPosition(
// success callback
function(position) {
if (position > -1) {
setAudioPosition((position) + " sec");
}
},
// error callback
function(e) {
console.log("Error getting pos=" + e);
setAudioPosition("Error: " + e);
}
);
}, 1000);
}
}
// Pause audio
//
function pauseAudio() {
if (my_media) {
my_media.pause();
}
}
// Stop audio
//
function stopAudio() {
if (my_media) {
my_media.stop();
}
clearInterval(mediaTimer);
mediaTimer = null;
}
// onSuccess Callback
//
function onSuccess() {
console.log("playAudio():Audio Success");
}
// onError Callback
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
// Set audio position
//
function setAudioPosition(position) {
document.getElementById('audio_position').innerHTML = position;
}
</script>
</body>
</html>
In Android the above code continues playing music even if user presses home button and takes the app to background state. But in iOS the sound stops when user presses the home button. So if you are building a cordova hybrid app then you need to use Background Audio plugin for iOS. But when you are building a legacy app you can set background audio permission for playing audio in background.
When screen is locked in iOS, the default music player is displayed. It can several controls next/previous buttons and also displays several information like song image, artist, album etc. You can control the music player when screen is locked using RemoteControls plugin.