PhoneGap Developer
PhoneGap is an HTML5 app platform that allows you to author native applications with web technologies and get access to APIs and app stores. PhoneGap leverages web technologies developers already know best… HTML and JavaScript.
What does this mean? We can create native like functions for your application using PhoneGap that normally will not work with html5 by itself. Thus, you get the best of both worlds. You get an application that is cross platform and that works just as a native app will work.
Wrap it with PhoneGap
Using the free open source framework or PhoneGap build you can get access to native APIs.
Deploy to multiple platforms!
PhoneGap uses standards-based web technologies to bridge web applications and mobile devices.
With PhoneGap you can,
Take advantage of HTML5 and CSS3
Use JavaScript to write your code
Access Native Features
Deploy your app to Multiple Platforms
Take advantage of PhoneGap Build
Add PhoneGap Plugins to your project
Use Tools from the community
Get help from the growing Community
See Supported Features »
Supported Platforms
Open Source and Free
PhoneGap is an open source implementation of open standards. That means developers and companies can use PhoneGap for mobile applications that are free, commercial, open source, or any combination of these.
Why PhoneGap?
Mobile development is a mess. Building applications for each device–iPhone, Android, Windows Mobile and more–requires different frameworks and languages. One day, the big players in mobile may decide to work together and unify third-party app development processes. Until then, PhoneGap will use standards-based web technologies to bridge web applications and mobile devices. Plus, because PhoneGap apps are standards compliant, they’re future-proofed to work with browsers as they evolve.
PhoneGap is an open source implementation of open standards. That means developers and companies can use PhoneGap for mobile applications that are free, commercial, open source, or any combination of these.
Since winning the Web 2.0 Expo LaunchPad competition in April 2009, PhoneGap has been widely recognized as a game-changer for mobile app development. The code has been downloaded more than 600,000 times and thousands of apps built using PhoneGap are available in mobile app stores and directories. Check out some of them here.
Who’s behind PhoneGap?
Nitobi was the original creator and is one of the primary contributors to the PhoneGap framework, but there is a vast global community that also contributes to the project, including many from IBM, RIM and Microsoft. We have an engaging and active community that is open, transparent and collaborative.
In October 2011, Adobe acquired Nitobi enabling the team to focus solely on the PhoneGap project and continue its work on efficient expressive design and development across devices. Adobe will continue to host the PhoneGap online community as well as the PhoneGap Build service, which is now in open beta.
Apache Software Foundation
The PhoneGap code was contributed to the Apache Software Foundation (ASF) under the name Apache Callback in October 2011. It is currently under incubation until it can become a full Apache project. Through the ASF, future PhoneGap development will ensure open stewardship of the project. It will always remain free and open source under the Apache License, Version 2.0.
camera.getPicture
Takes a photo using the camera or retrieves a photo from the device’s album. The image is returned as a base64 encoded String or as the URI of an image file.
navigator.camera.getPicture( cameraSuccess, cameraError, [ cameraOptions ] );
Description
Function camera.getPicture opens the device’s default camera application so that the user can take a picture (if Camera.sourceType = Camera.PictureSourceType.CAMERA, which is the default). Once the photo is taken, the camera application closes and your application is restored.
If Camera.sourceType = Camera.PictureSourceType.PHOTOLIBRARY or Camera.PictureSourceType.SAVEDPHOTOALBUM, then a photo chooser dialog is shown, from which a photo from the album can be selected.
The return value will be sent to the cameraSuccess function, in one of the following formats, depending on the cameraOptions you specify:
A String containing the Base64 encoded photo image (default).
A String representing the image file location on local storage.
You can do whatever you want with the encoded image or URI, for example:
Render the image in an tag (see example below)
Save the data locally (LocalStorage, Lawnchair, etc)
Post the data to a remote server
Note: The image quality of pictures taken using the camera on newer devices is quite good. Encoding such images using Base64 has caused memory issues on some of these devices (iPhone 4, BlackBerry Torch 9800). Therefore, using FILE_URI as the ‘Camera.destinationType’ is highly recommended.
Supported Platforms
Android
Blackberry WebWorks (OS 5.0 and higher)
iPhone
Windows Phone 7 ( Mango )
Quick Example
Take photo and retrieve Base64-encoded image:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50 });
function onSuccess(imageData) {
var image = document.getElementById(‘myImage’);
image.src = “data:image/jpeg;base64,” + imageData;
}
function onFail(message) {
alert(‘Failed because: ‘ + message);
}
Take photo and retrieve image file location:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI });
function onSuccess(imageURI) {
var image = document.getElementById(‘myImage’);
image.src = imageURI;
}
function onFail(message) {
alert(‘Failed because: ‘ + message);
}
Full Example
< !DOCTYPE html>
var pictureSource; // picture source var destinationType; // sets the format of returned value
// Wait for PhoneGap to connect with the device // document.addEventListener("deviceready",onDeviceReady,false);
// PhoneGap is ready to be used! // function onDeviceReady() { pictureSource=navigator.camera.PictureSourceType; destinationType=navigator.camera.DestinationType; }
// Called when a photo is successfully retrieved // function onPhotoDataSuccess(imageData) { // Uncomment to view the base64 encoded image data // console.log(imageData);
// Get image handle // var smallImage = document.getElementById('smallImage');
// Unhide image elements // smallImage.style.display = 'block';
// Show the captured photo // The inline CSS rules are used to resize the image // smallImage.src = "data:image/jpeg;base64," + imageData; }
// Called when a photo is successfully retrieved // function onPhotoURISuccess(imageURI) { // Uncomment to view the image file URI // console.log(imageURI);
// Get image handle // var largeImage = document.getElementById('largeImage');
// Unhide image elements // largeImage.style.display = 'block';
// Show the captured photo // The inline CSS rules are used to resize the image // largeImage.src = imageURI; }
// A button will call this function // function capturePhoto() { // Take picture using device camera and retrieve image as base64-encoded string navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50 }); }
// A button will call this function // function capturePhotoEdit() { // Take picture using device camera, allow edit, and retrieve image as base64-encoded string navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true }); }
// A button will call this function // function getPhoto(source) { // Retrieve image file location from specified source navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50, destinationType: destinationType.FILE_URI, sourceType: source }); }
// Called if something bad happens. // function onFail(message) { alert('Failed because: ' + message); }
cameraSuccess
onSuccess callback function that provides the image data.
function(imageData) {
// Do something with the image
}
Parameters
imageData: Base64 encoding of the image data, OR the image file URI, depending on cameraOptions used. (String)
Example
// Show image
//
function cameraCallback(imageData) {
var image = document.getElementById(‘myImage’);
image.src = “data:image/jpeg;base64,” + imageData;
}
cameraError
onError callback function that provides an error message.
function(message) {
// Show a helpful message
}
Parameters
message: The message is provided by the device’s native code. (String)
cameraOptions
Optional parameters to customize the camera settings.
{ quality : 75,
destinationType : Camera.DestinationType.DATA_URL,
sourceType : Camera.PictureSourceType.CAMERA,
allowEdit : true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 100,
targetHeight: 100 };
Options
quality: Quality of saved image. Range is [0, 100]. (Number)
destinationType: Choose the format of the return value. Defined in navigator.camera.DestinationType (Number)
Camera.DestinationType = {
DATA_URL : 0, // Return image as base64 encoded string
FILE_URI : 1 // Return image file URI
};
sourceType: Set the source of the picture. Defined in nagivator.camera.PictureSourceType (Number)
Camera.PictureSourceType = {
PHOTOLIBRARY : 0,
CAMERA : 1,
SAVEDPHOTOALBUM : 2
};
allowEdit: Allow simple editing of image before selection. (Boolean)
EncodingType: Choose the encoding of the returned image file. Defined in navigator.camera.EncodingType (Number)
Camera.EncodingType = {
JPEG : 0, // Return JPEG encoded image
PNG : 1 // Return PNG encoded image
};
targetWidth: Width in pixels to scale image. Must be used with targetHeight. Aspect ratio is maintained. (Number)
targetHeight: Height in pixels to scale image. Must be used with targetWidth. Aspect ratio is maintained. (Number)
MediaType: Set the type of media to select from. Only works when PictureSourceType is PHOTOLIBRARY or SAVEDPHOTOALBUM. Defined in nagivator.camera.MediaType (Number)
Camera.MediaType = {
PICTURE: 0, // allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType
VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI
ALLMEDIA : 2 // allow selection from all media types
};
Android Quirks
Ignores the allowEdit parameter.
Camera.PictureSourceType.PHOTOLIBRARY and Camera.PictureSourceType.SAVEDPHOTOALBUM both display the same photo album.
Camera.EncodingType is not supported.
BlackBerry Quirks
Ignores the quality parameter.
Ignores the sourceType parameter.
Ignores the allowEdit parameter.
Application must have key injection permissions to close native Camera application after photo is taken.
Using Large image sizes may result in inability to encode image on later model devices with high resolution cameras (e.g. Torch 9800).
Camera.MediaType is not supported.
Palm Quirks
Ignores the quality parameter.
Ignores the sourceType parameter.
Ignores the allowEdit parameter.
Camera.MediaType is not supported.
iPhone Quirks
Set quality below 50 to avoid memory error on some devices.
When destinationType.FILE_URI is used, photos are saved in the application’s temporary directory.
The contents of the application’s temporary directory is deleted when the application ends. Developers may also delete the contents of this directory using the navigator.fileMgr APIs if storage space is a concern.
Windows Phone 7 Quirks
Ignores the allowEdit parameter.
Accelerometer
Captures device motion in the x, y, and z direction.
Methods
accelerometer.getCurrentAcceleration
accelerometer.watchAcceleration
accelerometer.clearWatch
Arguments
accelerometerSuccess
accelerometerError
accelerometerOptions
Objects (Read-Only)
Acceleration
accelerometer.getCurrentAcceleration
Get the current acceleration along the x, y, and z axis.
navigator.accelerometer.getCurrentAcceleration(accelerometerSuccess, accelerometerError);
Description
The accelerometer is a motion sensor that detects the change (delta) in movement relative to the current device orientation. The accelerometer can detect 3D movement along the x, y, and z axis.
The acceleration is returned using the accelerometerSuccess callback function.
Supported Platforms
Android
BlackBerry WebWorks (OS 5.0 and higher)
iPhone
Quick Example
function onSuccess(acceleration) {
alert(‘Acceleration X: ‘ + acceleration.x + ‘\n’ +
‘Acceleration Y: ‘ + acceleration.y + ‘\n’ +
‘Acceleration Z: ‘ + acceleration.z + ‘\n’ +
‘Timestamp: ‘ + acceleration.timestamp + ‘\n’);
};
function onError() {
alert(‘onError!’);
};
navigator.accelerometer.getCurrentAcceleration(onSuccess, onError);
Full Example
< !DOCTYPE html>
// Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready // function onDeviceReady() { navigator.accelerometer.getCurrentAcceleration(onSuccess, onError); }
// onSuccess: Get a snapshot of the current acceleration // function onSuccess(acceleration) { alert('Acceleration X: ' + acceleration.x + '\n' + 'Acceleration Y: ' + acceleration.y + '\n' + 'Acceleration Z: ' + acceleration.z + '\n' + 'Timestamp: ' + acceleration.timestamp + '\n'); }
// onError: Failed to get the acceleration // function onError() { alert('onError!'); }
Example
getCurrentAcceleration
iPhone Quirks
iPhone doesn’t have the concept of getting the current acceleration at any given point.
You must watch the acceleration and capture the data at given time intervals.
Thus, the getCurrentAcceleration function will give you the last value reported from a phoneGap watchAccelerometer call.
accelerometer.watchAcceleration
At a regular interval, get the acceleration along the x, y, and z axis.
var watchID = navigator.accelerometer.watchAcceleration(accelerometerSuccess,
accelerometerError,
[accelerometerOptions]);
Description
The accelerometer is a motion sensor that detects the change (delta) in movement relative to the current position. The accelerometer can detect 3D movement along the x, y, and z axis.
The accelerometer.watchAcceleration gets the device’s current acceleration at a regular interval. Each time the Acceleration is retrieved, the accelerometerSuccess callback function is executed. Specify the interval in milliseconds via the frequency parameter in the acceleratorOptions object.
The returned watch ID references references the accelerometer watch interval. The watch ID can be used with accelerometer.clearWatch to stop watching the accelerometer.
Supported Platforms
Android
BlackBerry WebWorks (OS 5.0 and higher)
iPhone
Quick Example
function onSuccess(acceleration) {
alert(‘Acceleration X: ‘ + acceleration.x + ‘\n’ +
‘Acceleration Y: ‘ + acceleration.y + ‘\n’ +
‘Acceleration Z: ‘ + acceleration.z + ‘\n’ +
‘Timestamp: ‘ + acceleration.timestamp + ‘\n’);
};
function onError() {
alert(‘onError!’);
};
var options = { frequency: 3000 }; // Update every 3 seconds
var watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);
Full Example
< !DOCTYPE html>
// The watch id references the current `watchAcceleration` var watchID = null;
// Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready // function onDeviceReady() { startWatch(); }
// Start watching the acceleration // function startWatch() {
// Update acceleration every 3 seconds var options = { frequency: 3000 };
watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options); }
// Stop watching the acceleration // function stopWatch() { if (watchID) { navigator.accelerometer.clearWatch(watchID); watchID = null; } }
// onSuccess: Get a snapshot of the current acceleration
//
function onSuccess(acceleration) {
var element = document.getElementById('accelerometer');
element.innerHTML = 'Acceleration X: ' + acceleration.x + '
' +
'Acceleration Y: ' + acceleration.y + '
' +
'Acceleration Z: ' + acceleration.z + '
' +
'Timestamp: ' + acceleration.timestamp + '
';
}
// onError: Failed to get the acceleration // function onError() { alert('onError!'); }
iPhone Quirks
At the interval requested, PhoneGap will call the success callback function and pass the accelerometer results.
However, in requests to the device PhoneGap restricts the interval to minimum of every 40ms and a maximum of every 1000ms.
For example, if you request an interval of 3 seconds (3000ms), PhoneGap will request an interval of 1 second from the device but invoke the success callback at the requested interval of 3 seconds.
accelerometer.clearWatch
Stop watching the Acceleration referenced by the watch ID parameter.
navigator.accelerometer.clearWatch(watchID);
watchID: The ID returned by accelerometer.watchAcceleration.
Supported Platforms
Android
BlackBerry WebWorks (OS 5.0 and higher)
iPhone
Quick Example
var watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);
// … later on …
navigator.accelerometer.clearWatch(watchID);
Full Example
< !DOCTYPE html>
// The watch id references the current `watchAcceleration` var watchID = null;
// Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready // function onDeviceReady() { startWatch(); }
// Start watching the acceleration // function startWatch() {
// Update acceleration every 3 seconds var options = { frequency: 3000 };
watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options); }
// Stop watching the acceleration // function stopWatch() { if (watchID) { navigator.accelerometer.clearWatch(watchID); watchID = null; } }
// onSuccess: Get a snapshot of the current acceleration
//
function onSuccess(acceleration) {
var element = document.getElementById('accelerometer');
element.innerHTML = 'Acceleration X: ' + acceleration.x + '
' +
'Acceleration Y: ' + acceleration.y + '
' +
'Acceleration Z: ' + acceleration.z + '
' +
'Timestamp: ' + acceleration.timestamp + '
';
}
// onError: Failed to get the acceleration // function onError() { alert('onError!'); }
Acceleration
Contains Accelerometer data captured at a specific point in time.
Properties
x: Amount of motion on the x-axis. Range [0, 1] (Number)
y: Amount of motion on the y-axis. Range [0, 1] (Number)
z: Amount of motion on the z-axis. Range [0, 1] (Number)
timestamp: Creation timestamp in milliseconds. (DOMTimeStamp)
Description
This object is created and populated by PhoneGap, and returned by an Accelerometer method.
Supported Platforms
Android
BlackBerry WebWorks (OS 5.0 and higher)
iPhone
Windows Phone 7 ( Mango )
Quick Example
function onSuccess(acceleration) {
alert(‘Acceleration X: ‘ + acceleration.x + ‘\n’ +
‘Acceleration Y: ‘ + acceleration.y + ‘\n’ +
‘Acceleration Z: ‘ + acceleration.z + ‘\n’ +
‘Timestamp: ‘ + acceleration.timestamp + ‘\n’);
};
function onError() {
alert(‘onError!’);
};
navigator.accelerometer.getCurrentAcceleration(onSuccess, onError);
Full Example
< !DOCTYPE html>
// Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready // function onDeviceReady() { navigator.accelerometer.getCurrentAcceleration(onSuccess, onError); }
// onSuccess: Get a snapshot of the current acceleration // function onSuccess() { alert('Acceleration X: ' + acceleration.x + '\n' + 'Acceleration Y: ' + acceleration.y + '\n' + 'Acceleration Z: ' + acceleration.z + '\n' + 'Timestamp: ' + acceleration.timestamp + '\n'); }
// onError: Failed to get the acceleration // function onError() { alert('onError!'); }
Example
getCurrentAcceleration
accelerometerSuccess
onSuccess callback function that provides the Acceleration information.
function(acceleration) {
// Do something
}
Parameters
acceleration: The acceleration at a single moment in time. (Acceleration)
Example
function onSuccess(acceleration) {
alert(‘Acceleration X: ‘ + acceleration.x + ‘\n’ +
‘Acceleration Y: ‘ + acceleration.y + ‘\n’ +
‘Acceleration Z: ‘ + acceleration.z + ‘\n’ +
‘Timestamp: ‘ + acceleration.timestamp + ‘\n’);
};
accelerometerError
onError callback function for acceleration functions.
function() {
// Handle the error
}
accelerometerOptions
An optional parameter to customize the retrieval of the accelerometer.
Options
frequency: How often to retrieve the Acceleration in milliseconds. (Number) (Default: 10000)
Compass
Obtains the direction that the device is pointing.
Methods
compass.getCurrentHeading
compass.watchHeading
compass.clearWatch
compass.watchHeadingFilter
compass.clearWatchFilter
Arguments
compassSuccess
compassError
compassOptions
compassHeading
compass.getCurrentHeading
Get the current compass heading.
navigator.compass.getCurrentHeading(compassSuccess, compassError, compassOptions);
Description
The compass is a sensor that detects the direction or heading that the device is pointed. It measures the heading in degrees from 0 to 359.99.
The compass heading information is returned via a CompassHeading object using the compassSuccess callback function.
Supported Platforms
Android
iPhone
Windows Phone 7 ( Mango ) if available in hardware
Quick Example
function onSuccess(heading) {
alert(‘Heading: ‘ + heading.magneticHeading);
};
function onError(error) {
alert(‘CompassError: ‘ error.code);
};
navigator.compass.getCurrentHeading(onSuccess, onError);
Full Example
< !DOCTYPE html>
// Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready // function onDeviceReady() { navigator.compass.getCurrentHeading(onSuccess, onError); }
// onSuccess: Get the current heading // function onSuccess(heading) { alert('Heading: ' + heading.magneticHeading); }
// onError: Failed to get the heading // function onError(compassError) { alert('Compass Error: ' + compassError.code); }
Example
getCurrentHeading
compass.watchHeading
At a regular interval, get the compass heading in degrees.
var watchID = navigator.compass.watchHeading(compassSuccess, compassError, [compassOptions]);
Description
The compass is a sensor that detects the direction or heading that the device is pointed. It measures the heading in degrees from 0 to 359.99.
The compass.watchHeading gets the device’s current heading at a regular interval. Each time the heading is retrieved, the headingSuccess callback function is executed. Specify the interval in milliseconds via the frequency parameter in the compassOptions object.
The returned watch ID references references the compass watch interval. The watch ID can be used with compass.clearWatch to stop watching the compass.
Supported Platforms
Android
iPhone
Windows Phone 7 ( Mango ) if available in hardware
Quick Example
function onSuccess(heading) {
var element = document.getElementById(‘heading’);
element.innerHTML = ‘Heading: ‘ + heading.magneticHeading;
};
function onError(compassError) {
alert(‘Compass error: ‘ + compassError.code);
};
var options = { frequency: 3000 }; // Update every 3 seconds
var watchID = navigator.compass.watchHeading(onSuccess, onError, options);
Full Example
< !DOCTYPE html>
// The watch id references the current `watchHeading` var watchID = null;
// Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready // function onDeviceReady() { startWatch(); }
// Start watching the compass // function startWatch() {
// Update compass every 3 seconds var options = { frequency: 3000 };
watchID = navigator.compass.watchHeading(onSuccess, onError, options); }
// Stop watching the compass // function stopWatch() { if (watchID) { navigator.compass.clearWatch(watchID); watchID = null; } }
// onSuccess: Get the current heading // function onSuccess(heading) { var element = document.getElementById('heading'); element.innerHTML = 'Heading: ' + heading.magneticHeading; }
// onError: Failed to get the heading // function onError(compassError) { alert('Compass error: ' + compassError.code); }
compass.clearWatch
Stop watching the compass referenced by the watch ID parameter.
navigator.compass.clearWatch(watchID);
watchID: The ID returned by compass.watchHeading.
Supported Platforms
Android
iPhone
Windows Phone 7 ( Mango ) if available in hardware
Quick Example
var watchID = navigator.compass.watchHeading(onSuccess, onError, options);
// … later on …
navigator.compass.clearWatch(watchID);
Full Example
< !DOCTYPE html>
// The watch id references the current `watchHeading` var watchID = null;
// Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready // function onDeviceReady() { startWatch(); }
// Start watching the compass // function startWatch() {
// Update compass every 3 seconds var options = { frequency: 3000 };
watchID = navigator.compass.watchHeading(onSuccess, onError, options); }
// Stop watching the compass // function stopWatch() { if (watchID) { navigator.compass.clearWatch(watchID); watchID = null; } }
// onSuccess: Get the current heading // function onSuccess(heading) { var element = document.getElementById('heading'); element.innerHTML = 'Heading: ' + heading.magneticHeading; }
// onError: Failed to get the heading // function onError(compassError) { alert('Compass error: ' + compassError.code); }
compass.watchHeadingFilter
Get the compass heading in degrees when it changes by at least a certain number of degrees.
var watchID = navigator.compass.watchHeadingFilter(compassSuccess, compassError, compassOptions);
Description
The compass is a sensor that detects the direction or heading that the device is pointed. It measures the heading in degrees from 0 to 359.99.
The compass.watchHeadingFilter gets the device’s current heading when it changes by a specified number of degrees. Each time the heading changes by the specified number of degrees or more, the headingSuccess callback function is called. Specify the degrees of change via the filter parameter in the compassOptions object.
The returned watch ID references references the compass watch interval. The watch ID can be used with compass.clearWatchFilter to stop watching the compass via a degree filter. Only one watchHeadingFilter can be in effect at one time. If a watchHeadingFilter is in effect, calling getCurrentHeading or watchHeading will use the existing filter value for specifying heading changes. On iOS this method is more efficient than compass.watchFilter() based on the iOS mechanism for monitoring compass heading changes.
Supported Platforms
iPhone
Quick Example
function onSuccess(heading) {
var element = document.getElementById(‘heading’);
element.innerHTML = ‘Heading: ‘ + heading.magneticHeading;
};
function onError(compassError) {
alert(‘Compass error: ‘ + compassError.code);
};
var options = { filter: 10 }; // Get notified on compass heading changes or 10 degrees or more
var watchID = navigator.compass.watchHeadingFilter(onSuccess, onError, options);
Full Example
< !DOCTYPE html>
// The watch id references the current `watchHeading` var watchID = null;
// Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready // function onDeviceReady() { startWatch(); }
// Start watching the compass // function startWatch() {
// Get notified on compass heading changes or 10 degrees or more var options = { filter: 10 };
watchID = navigator.compass.watchHeadingFilter(onSuccess, onError, options); }
// Stop watching the compass // function stopWatch() { if (watchID) { navigator.compass.clearWatchFilter(watchID); watchID = null; } }
// onSuccess: Get the current heading // function onSuccess(heading) { var element = document.getElementById('heading'); element.innerHTML = 'Heading: ' + heading.magneticHeading; }
// onError: Failed to get the heading // function onError(compassError) { alert('Compass error: ' + compassError.code); }
compass.clearWatchFilter
Stop watching the compass referenced by the watch ID parameter.
navigator.compass.clearWatchFilter(watchID);
watchID: The ID returned by compass.watchHeadingFilter.
Supported Platforms
iPhone
Quick Example
var watchID = navigator.compass.watchHeadingFilter(onSuccess, onError, options);
// … later on …
navigator.compass.clearWatchFilter(watchID);
Full Example
< !DOCTYPE html>
// The watch id references the current `watchHeading` var watchID = null;
// Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready // function onDeviceReady() { startWatch(); }
// Start watching the compass // function startWatch() {
// Get notified on compass heading changes or 10 degrees or more var options = { filter: 10 };
watchID = navigator.compass.watchHeadingFilter(onSuccess, onError, options); }
// Stop watching the compass // function stopWatch() { if (watchID) { navigator.compass.clearWatchFilter(watchID); watchID = null; } }
// onSuccess: Get the current heading // function onSuccess(heading) { var element = document.getElementById('heading'); element.innerHTML = 'Heading: ' + heading.magneticHeading; }
// onError: Failed to get the heading // function onError(compassError) { alert('Compass error: ' + compassError.code); }
compassSuccess
onSuccess callback function that provides the compass heading information via a compassHeading object.
function(heading) {
// Do something
}
Parameters
heading: The heading information. (compassHeading)
Example
function onSuccess(heading) {
alert(‘Heading: ‘ + heading.magneticHeading);
};
compassError
onError callback function for compass functions.
Example
function(CompassError) { // Handle the error }
compassOptions
An optional parameter to customize the retrieval of the compass.
Options
frequency: How often to retrieve the compass heading in milliseconds. (Number) (Default: 100)
filter: The change in degrees required to initiate a watchHeadingFilter success callback. (Number)
Android Quirks
filter is not supported.
Windows Phone 7 Quirks
filter is not supported.
compassHeading
A CompassHeading object is returned to the compassSuccess callback function when an error occurs.
Properties
magneticHeading: The heading in degrees from 0 – 359.99 at a single moment in time. (Number)
trueHeading: The heading relative to the geographic North Pole in degrees 0 – 359.99 at a single moment in time. A negative value indicates that the true heading could not be determined. (Number)
headingAccuracy: The deviation in degrees between the reported heading and the true heading. (Number)
timestamp: The time at which this heading was determined. (milliseconds)
Description
The CompassHeading object is returned to the user through the compassSuccess callback function.
Android Quirks
trueHeading is not supported. It will report the same value as magneticHeading
headingAccuracy will always be 0 as there is no difference between the magneticHeading and trueHeading on Android.
iOS Quirks
trueHeading is only returned when location services are running via navigator.geolocation.watchLocation()
For iOS > 4 devices, if the device is rotated and the app supports that orientation, the heading values will be reported back with respect to the current orientation.
Windows Phone 7 Quirks
returns trueHeading only, note that this code is largely untested because of a lack of devices that support compass.
CompassError
A CompassError object is returned to the compassError callback function when an error occurs.
Properties
code: One of the predefined error codes listed below.
Constants
CompassError.COMPASS_INTERNAL_ERR
CompassError.COMPASS_NOT_SUPPORTED
Description
The CompassError object is returned to the user through the compassError callback function when an error occurs.
Geolocation
The geolocation object provides access to the device’s GPS sensor.
Geolocation provides location information for the device, such as latitude and longitude. Common sources of location information include Global Positioning System (GPS) and location inferred from network signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, and GSM/CDMA cell IDs. No guarantee is given that the API returns the device’s actual location.
This API is based on the W3C Geo location API Specification. Some devices already provide an implementation of this spec. For those devices, the built-in support is used instead of replacing it with PhoneGap’s implementation. For devices that don’t have geolocation support, PhoneGap’s implementation should be compatible with the W3C specification.
Methods
geolocation.getCurrentPosition
geolocation.watchPosition
geolocation.clearWatch
Arguments
geolocationSuccess
geolocationError
geolocationOptions
Objects (Read-Only)
Position
PositionError
Coordinates
geolocation.getCurrentPosition
Returns the device’s current position as a Position object.
navigator.geolocation.getCurrentPosition(geolocationSuccess,
[geolocationError],
[geolocationOptions]);
Parameters
geolocationSuccess: The callback that is called with the current position.
geolocationError: (Optional) The callback that is called if there was an error.
geolocationOptions: (Optional) The geolocation options.
Description
Function geolocation.getCurrentPositon is an asynchronous function. It returns the device’s current position to the geolocationSuccess callback with a Position object as the parameter. If there is an error, the geolocationError callback is invoked with a PositionError object.
Supported Platforms
Android
BlackBerry (OS 4.6)
BlackBerry WebWorks (OS 5.0 and higher)
iPhone
Windows Phone 7 ( Mango )
Quick Example
// onSuccess Callback
// This method accepts a `Position` object, which contains
// the current GPS coordinates
//
var onSuccess = function(position) {
alert(‘Latitude: ‘ + position.coords.latitude + ‘\n’ +
‘Longitude: ‘ + position.coords.longitude + ‘\n’ +
‘Altitude: ‘ + position.coords.altitude + ‘\n’ +
‘Accuracy: ‘ + position.coords.accuracy + ‘\n’ +
‘Altitude Accuracy: ‘ + position.coords.altitudeAccuracy + ‘\n’ +
‘Heading: ‘ + position.coords.heading + ‘\n’ +
‘Speed: ‘ + position.coords.speed + ‘\n’ +
‘Timestamp: ‘ + new Date(position.timestamp) + ‘\n’);
};
// onError Callback receives a PositionError object
//
function onError(error) {
alert(‘code: ‘ + error.code + ‘\n’ +
‘message: ‘ + error.message + ‘\n’);
}
navigator.geolocation.getCurrentPosition(onSuccess, onError);
Full Example
< !DOCTYPE html>
// Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready // function onDeviceReady() { navigator.geolocation.getCurrentPosition(onSuccess, onError); }
// onSuccess Geolocation
//
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '
' +
'Longitude: ' + position.coords.longitude + '
' +
'Altitude: ' + position.coords.altitude + '
' +
'Accuracy: ' + position.coords.accuracy + '
' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '
' +
'Heading: ' + position.coords.heading + '
' +
'Speed: ' + position.coords.speed + '
' +
'Timestamp: ' + new Date(position.timestamp) + '
';
}
// onError Callback receives a PositionError object // function onError(error) { alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n'); }
Finding geolocation…
geolocation.watchPosition
Watches for changes to the device’s current position.
var watchId = navigator.geolocation.watchPosition(geolocationSuccess,
[geolocationError],
[geolocationOptions]);
Parameters
geolocationSuccess: The callback that is called with the current position.
geolocationError: (Optional) The callback that is called if there was an error.
geolocationOptions: (Optional) The geolocation options.
Returns
String: returns a watch id that references the watch position interval. The watch id can be used with geolocation.clearWatch to stop watching for changes in position.
Description
Function geolocation.watchPosition is an asynchronous function. It returns the device’s current position when a change in position has been detected. When the device has retrieved a new location, the geolocationSuccess callback is invoked with a Position object as the parameter. If there is an error, the geolocationError callback is invoked with a PositionError object.
Supported Platforms
Android
BlackBerry (OS 4.6)
BlackBerry WebWorks (OS 5.0 and higher)
iPhone
Windows Phone 7 ( Mango )
Quick Example
// onSuccess Callback
// This method accepts a `Position` object, which contains
// the current GPS coordinates
//
function onSuccess(position) {
var element = document.getElementById(‘geolocation’);
element.innerHTML = ‘Latitude: ‘ + position.coords.latitude + ‘
‘ +
‘Longitude: ‘ + position.coords.longitude + ‘
‘ +
‘
‘ + element.innerHTML;
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert(‘code: ‘ + error.code + ‘\n’ +
‘message: ‘ + error.message + ‘\n’);
}
// Options: retrieve the location every 3 seconds
//
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { frequency: 3000 });
Full Example
< !DOCTYPE html>
// Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false);
var watchID = null;
// PhoneGap is ready // function onDeviceReady() { // Update every 3 seconds var options = { frequency: 3000 }; watchID = navigator.geolocation.watchPosition(onSuccess, onError, options); }
// onSuccess Geolocation
//
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '
' +
'Longitude: ' + position.coords.longitude + '
' +
'
' + element.innerHTML; }
// onError Callback receives a PositionError object // function onError(error) { alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n'); }
Watching geolocation…
geolocation.clearWatch
Stop watching for changes to the device’s location referenced by the watchID parameter.
navigator.geolocation.clearWatch(watchID);
Parameters
watchID: The id of the watchPosition interval to clear. (String)
Description
Function geolocation.clearWatch stops watching changes to the device’s location by clearing the geolocation.watchPosition referenced by watchID.
Supported Platforms
Android
BlackBerry (OS 4.6)
BlackBerry WebWorks (OS 5.0 and higher)
iPhone
Windows Phone 7 ( Mango )
Quick Example
// Options: retrieve the location every 3 seconds
//
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { frequency: 3000 });
// …later on…
navigator.geolocation.clearWatch(watchID);
Full Example
< !DOCTYPE html>
// Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false);
var watchID = null;
// PhoneGap is ready // function onDeviceReady() { // Update every 3 seconds var options = { frequency: 3000 }; watchID = navigator.geolocation.watchPosition(onSuccess, onError, options); }
// onSuccess Geolocation
//
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '
' +
'Longitude: ' + position.coords.longitude + '
' +
'
' + element.innerHTML; }
// clear the watch that was started earlier // function clearWatch() { if (watchID != null) { navigator.geolocation.clearWatch(watchID); watchID = null; } }
// onError Callback receives a PositionError object // function onError(error) { alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n'); }
Watching geolocation…
Coordinates
A set of properties that describe the geographic coordinates of a position.
Properties
latitude: Latitude in decimal degrees. (Number)
longitude: Longitude in decimal degrees. (Number)
altitude: Height of the position in meters above the ellipsoid. (Number)
accuracy: Accuracy level of the latitude and longitude coordinates in meters. (Number)
altitudeAccuracy: Accuracy level of the altitude coordinate in meters. (Number)
heading: Direction of travel, specified in degrees counting clockwise relative to the true north. (Number)
speed: Current ground speed of the device, specified in meters per second. (Number)
Description
The Coordinates object is created and populated by PhoneGap, and attached to the Position object. The Position object is then returned to the user through a callback function.
Supported Platforms
Android
BlackBerry (OS 4.6)
BlackBerry WebWorks (OS 5.0 and higher)
iPhone
Windows Phone 7 ( Mango )
Quick Example
// onSuccess Callback
//
var onSuccess = function(position) {
alert(‘Latitude: ‘ + position.coords.latitude + ‘\n’ +
‘Longitude: ‘ + position.coords.longitude + ‘\n’ +
‘Altitude: ‘ + position.coords.altitude + ‘\n’ +
‘Accuracy: ‘ + position.coords.accuracy + ‘\n’ +
‘Altitude Accuracy: ‘ + position.coords.altitudeAccuracy + ‘\n’ +
‘Heading: ‘ + position.coords.heading + ‘\n’ +
‘Speed: ‘ + position.coords.speed + ‘\n’ +
‘Timestamp: ‘ + new Date(position.timestamp) + ‘\n’);
};
// onError Callback
//
var onError = function() {
alert(‘onError!’);
};
navigator.geolocation.getCurrentPosition(onSuccess, onError);
Full Example
< !DOCTYPE html>
// Set an event to wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is loaded and Ready // function onDeviceReady() { navigator.geolocation.getCurrentPosition(onSuccess, onError); }
// Display `Position` properties from the geolocation // function onSuccess(position) { var div = document.getElementById('myDiv');
div.innerHTML = 'Latitude: ' + position.coords.latitude + '
' +
'Longitude: ' + position.coords.longitude + '
' +
'Altitude: ' + position.coords.altitude + '
' +
'Accuracy: ' + position.coords.accuracy + '
' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '
' +
'Heading: ' + position.coords.heading + '
' +
'Speed: ' + position.coords.speed + '
';
}
// Show an alert if there is a problem getting the geolocation // function onError() { alert('onError!'); }
Android Quirks
altitudeAccuracy: This property is not support by Android devices, it will always return null.
Position
Contains Position coordinates that are created by the geolocation API.
Properties
coords: A set of geographic coordinates. (Coordinates)
timestamp: Creation timestamp for coords in milliseconds. (DOMTimeStamp)
Description
The Position object is created and populated by PhoneGap, and returned to the user through a callback function.
Supported Platforms
Android
BlackBerry (OS 4.6)
BlackBerry WebWorks (OS 5.0 and higher)
iPhone
Windows Phone 7 ( Mango )
Quick Example
// onSuccess Callback
//
var onSuccess = function(position) {
alert(‘Latitude: ‘ + position.coords.latitude + ‘\n’ +
‘Longitude: ‘ + position.coords.longitude + ‘\n’ +
‘Altitude: ‘ + position.coords.altitude + ‘\n’ +
‘Accuracy: ‘ + position.coords.accuracy + ‘\n’ +
‘Altitude Accuracy: ‘ + position.coords.altitudeAccuracy + ‘\n’ +
‘Heading: ‘ + position.coords.heading + ‘\n’ +
‘Speed: ‘ + position.coords.speed + ‘\n’ +
‘Timestamp: ‘ + new Date(position.timestamp) + ‘\n’);
};
// onError Callback receives a PositionError object
//
function onError(error) {
alert(‘code: ‘ + error.code + ‘\n’ +
‘message: ‘ + error.message + ‘\n’);
}
navigator.geolocation.getCurrentPosition(onSuccess, onError);
Full Example
< !DOCTYPE html>
// Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready // function onDeviceReady() { navigator.geolocation.getCurrentPosition(onSuccess, onError); }
// onSuccess Geolocation
//
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '
' +
'Longitude: ' + position.coords.longitude + '
' +
'Altitude: ' + position.coords.altitude + '
' +
'Accuracy: ' + position.coords.accuracy + '
' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '
' +
'Heading: ' + position.coords.heading + '
' +
'Speed: ' + position.coords.speed + '
' +
'Timestamp: ' + new Date(position.timestamp) + '
';
}
// onError Callback receives a PositionError object // function onError(error) { alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n'); }
Finding geolocation…
iPhone Quirks
timestamp: Uses seconds instead of milliseconds.
A workaround is to manually convert the timestamp to milliseconds (x 1000):
var onSuccess = function(position) {
alert(‘Latitude: ‘ + position.coords.latitude + ‘\n’ +
‘Longitude: ‘ + position.coords.longitude + ‘\n’ +
‘Timestamp: ‘ + new Date(position.timestamp * 1000) + ‘\n’);
};
PositionError
A PositionError object is returned to the geolocationError callback when an error occurs.
Properties
code: One of the predefined error codes listed below.
message: Error message describing the details of the error encountered.
Constants
PositionError.PERMISSION_DENIED
PositionError.POSITION_UNAVAILABLE
PositionError.TIMEOUT
Description
The PositionError object is returned to the user through the geolocationError callback function when an error occurs with geolocation.
geolocationSuccess
The user’s callback function that is called when a geolocation position is available.
function(position) {
// Do something
}
Parameters
position: The geolocation position returned by the device. (Position)
Example
function geolocationSuccess(position) {
alert(‘Latitude: ‘ + position.coords.latitude + ‘\n’ +
‘Longitude: ‘ + position.coords.longitude + ‘\n’ +
‘Altitude: ‘ + position.coords.altitude + ‘\n’ +
‘Accuracy: ‘ + position.coords.accuracy + ‘\n’ +
‘Altitude Accuracy: ‘ + position.coords.altitudeAccuracy + ‘\n’ +
‘Heading: ‘ + position.coords.heading + ‘\n’ +
‘Speed: ‘ + position.coords.speed + ‘\n’ +
‘Timestamp: ‘ + new Date(position.timestamp) + ‘\n’);
}
geolocationError
The user’s callback function that is called when there is an error for geolocation functions.
function(error) {
// Handle the error
}
Parameters
error: The error returned by the device. (PositionError)
geolocationOptions
Optional parameters to customize the retrieval of the geolocation.
{ maximumAge: 3000, timeout: 5000, enableHighAccuracy: true };
Options
frequency: How often to retrieve the position in milliseconds. This option is not part of the W3C spec and will be removed in the future. maximumAge should be used instead. (Number) (Default: 10000)
enableHighAccuracy: Provides a hint that the application would like to receive the best possible results. (Boolean)
timeout: The maximum length of time (msec) that is allowed to pass from the call to geolocation.getCurrentPosition or geolocation.watchPosition until the corresponding geolocationSuccess callback is invoked. (Number)
maximumAge: Accept a cached position whose age is no greater than the specified time in milliseconds. (Number)
Android Quirks
The Android 2.x simulators will not return a geolocation result unless the enableHighAccuracy option is set to true.
Media
The Media object provides the ability to record and play back audio files on a device.
var media = new Media(src, mediaSuccess, [mediaError], [mediaStatus]);
Note: The current implementation does not adhere to a W3C specification for media capture, and is provided for convenience only. A future implementation will adhere to the latest W3C specification and may deprecate the current APIs.
Parameters
src: A URI containing the audio content. (DOMString)
mediaSuccess: (Optional) The callback that is invoked after a Media object has completed the current play/record or stop action. (Function)
mediaError: (Optional) The callback that is invoked if there was an error. (Function)
mediaStatus: (Optional) The callback that is invoked to indicate status changes. (Function)
Methods
media.getCurrentPosition: Returns the current position within an audio file.
media.getDuration: Returns the duration of an audio file.
media.play: Start or resume playing audio file.
media.pause: Pause playing audio file.
media.release: Releases the underlying OS’es audio resources.
media.seekTo: Moves the position within the audio file.
media.startRecord: Start recording audio file.
media.stopRecord: Stop recording audio file.
media.stop: Stop playing audio file.
Additional ReadOnly Parameters
_position: The position within the audio playback in seconds. Not automatically updated during play, call getCurrentPosition to update.
_duration: The duration of the media in seconds.
Supported Platforms
Android
iOS
Windows Phone 7 ( Mango )
media.getCurrentPosition
Returns the current position within an audio file.
media.getCurrentPosition(mediaSuccess, [mediaError]);
Parameters
mediaSuccess: The callback that is called with the current position in seconds.
mediaError: (Optional) The callback that is called if there was an error.
Description
Function media.getCurrentPosition is an asynchronous function that returns the current position of the underlying audio file of a Media object. Also updates the _position parameter within the Media object.
Supported Platforms
Android
iOS
Windows Phone 7 ( Mango )
Quick Example
// Audio player
//
var my_media = new Media(src, onSuccess, onError);
// Update media position every second
var mediaTimer = setInterval(function() {
// get media position
my_media.getCurrentPosition(
// success callback
function(position) {
if (position > -1) {
console.log((position) + ” sec”);
}
},
// error callback
function(e) {
console.log(“Error getting pos=” + e);
}
);
}, 1000);
Full Example
< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
// Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready // function onDeviceReady() { playAudio("http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3"); }
// Audio player // var my_media = null; var mediaTimer = null;
// Play audio // function playAudio(src) { // Create Media object from src my_media = new Media(src, onSuccess, onError);
// Play audio my_media.play();
// 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; }
Play Audio
Pause Playing Audio
Stop Playing Audio
media.getDuration
Returns the duration of an audio file.
media.getDuration();
Description
Function media.getDuration is a synchronous function that returns the duration of the audio file in seconds, if known. If the duration is unknown, a value of -1 is returned.
Supported Platforms
Android
iOS
Windows Phone 7 ( Mango )
Quick Example
// Audio player
//
var my_media = new Media(src, onSuccess, onError);
// Get duration
var counter = 0;
var timerDur = setInterval(function() {
counter = counter + 100;
if (counter > 2000) {
clearInterval(timerDur);
}
var dur = my_media.getDuration();
if (dur > 0) {
clearInterval(timerDur);
document.getElementById(‘audio_duration’).innerHTML = (dur) + ” sec”;
}
}, 100);
Full Example
< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
// Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready // function onDeviceReady() { playAudio("http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3"); }
// Audio player // var my_media = null; var mediaTimer = null;
// Play audio // function playAudio(src) { // Create Media object from src my_media = new Media(src, onSuccess, onError);
// Play audio my_media.play();
// 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; }
Play Audio
Pause Playing Audio
Stop Playing Audio
media.pause
Pauses playing an audio file.
media.pause();
Description
Function media.pause is a synchronous function that pauses playing an audio file.
Supported Platforms
Android
iOS
Windows Phone 7 ( Mango )
Quick Example
// Play audio
//
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();
// Pause after 10 seconds
setTimeout(function() {
media.pause();
}, 10000);
}
Full Example
< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
// Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready // function onDeviceReady() { playAudio("http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3"); }
// Audio player // var my_media = null; var mediaTimer = null;
// Play audio // function playAudio(src) { // Create Media object from src my_media = new Media(src, onSuccess, onError);
// Play audio my_media.play();
// 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; }
Play Audio
Pause Playing Audio
Stop Playing Audio
media.play
Starts or resumes playing an audio file.
media.play();
Description
Function media.play is a synchronous function that starts or resumes playing an audio file.
Supported Platforms
Android
iOS
Windows Phone 7 ( Mango )
Quick Example
// Play audio
//
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();
}
Full Example
< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
// Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready // function onDeviceReady() { playAudio("http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.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 my_media.play();
// 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; }
Play Audio
Pause Playing Audio
Stop Playing Audio
media.release
Releases the underlying operating systems audio resources.
media.release();
Description
Function media.release is a synchronous function that releases the underlying operating systems audio resources. This function is particularly important for Android as there are a finite amount of OpenCore instances for media playback. Developers should call the ‘release’ function when they no longer need the Media resource.
Supported Platforms
Android
iOS
Windows Phone 7 ( Mango )
Quick Example
// Audio player
//
var my_media = new Media(src, onSuccess, onError);
my_media.play();
my_media.stop();
my_media.release();
Full Example
< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
// Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready // function onDeviceReady() { playAudio("http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3"); }
// Audio player // var my_media = null; var mediaTimer = null;
// Play audio // function playAudio(src) { // Create Media object from src my_media = new Media(src, onSuccess, onError);
// Play audio my_media.play();
// 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; }
Play Audio
Pause Playing Audio
Stop Playing Audio
media.seekTo
Sets the current position within an audio file.
media.seekTo(milliseconds);
Parameters
milliseconds: The position to set the playback position within the audio in milliseconds. .
Description
Function media.seekTo is an asynchronous function that updates the current position of the underlying audio file of a Media object. Also updates the _position parameter within the Media object.
Supported Platforms
Android
iOS
Windows Phone 7 ( Mango )
Quick Example
// Audio player
//
var my_media = new Media(src, onSuccess, onError);
my_media.play();
// SeekTo to 10 seconds after 5 seconds
setTimeout(function() {
my_media.seekTo(10000);
}, 5000);
Full Example
< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
// Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready // function onDeviceReady() { playAudio("http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3"); }
// Audio player // var my_media = null; var mediaTimer = null;
// Play audio // function playAudio(src) { // Create Media object from src my_media = new Media(src, onSuccess, onError);
// Play audio my_media.play(); // Update media position every second mediaTimer = setInterval(function() { // get 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); } ); }, 1000); // SeekTo to 10 seconds after 5 seconds setTimeout(function() { my_media.seekTo(10000); }, 5000); }
// 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; }
Play Audio
Stop Playing Audio
media.startRecord
Starts recording an audio file.
media.startRecord();
Description
Function media.startRecord is a synchronous function that starts recording an audio file.
Supported Platforms
Android
iOS
Windows Phone 7 ( Mango )
Quick Example
// Record audio
//
function recordAudio() {
var src = “myrecording.mp3″;
var mediaRec = new Media(src,
// success callback
function() {
console.log(“recordAudio():Audio Success”);
},
// error callback
function(err) {
console.log(“recordAudio():Audio Error: “+ err.code);
});
// Record audio
mediaRec.startRecord();
}
Full Example
< !DOCTYPE html>
// Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false);
// Record audio // function recordAudio() { var src = "myrecording.mp3"; var mediaRec = new Media(src, onSuccess, onError);
// Record audio mediaRec.startRecord();
// Stop recording after 10 sec var recTime = 0; var recInterval = setInterval(function() { recTime = recTime + 1; setAudioPosition(recTime + " sec"); if (recTime >= 10) { clearInterval(recInterval); mediaRec.stopRecord(); } }, 1000); }
// PhoneGap is ready // function onDeviceReady() { recordAudio(); }
// onSuccess Callback // function onSuccess() { console.log("recordAudio():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; }
Recording audio…
iOS Quirks
The file to record to must already exist and should be of type .wav. The File API’s can be used to create the file.
media.stop
Stops playing an audio file.
media.stop();
Description
Function media.stop is a synchronous function that stops playing an audio file.
Supported Platforms
Android
iOS
Windows Phone 7 ( Mango )
Quick Example
// Play audio
//
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();
// Pause after 10 seconds
setTimeout(function() {
my_media.stop();
}, 10000);
}
Full Example
< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
// Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready // function onDeviceReady() { playAudio("http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3"); }
// Audio player // var my_media = null; var mediaTimer = null;
// Play audio // function playAudio(src) { // Create Media object from src my_media = new Media(src, onSuccess, onError);
// Play audio my_media.play();
// 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; }
Play Audio
Pause Playing Audio
Stop Playing Audio
media.stopRecord
Stops recording an audio file.
media.stopRecord();
Description
Function media.stopRecord is a synchronous function that stops recording an audio file.
Supported Platforms
Android
iOS
Windows Phone 7 ( Mango )
Quick Example
// Record audio
//
function recordAudio() {
var src = “myrecording.mp3″;
var mediaRec = new Media(src,
// success callback
function() {
console.log(“recordAudio():Audio Success”);
},
// error callback
function(err) {
console.log(“recordAudio():Audio Error: “+ err.code);
});
// Record audio
mediaRec.startRecord();
// Stop recording after 10 seconds
setTimeout(function() {
mediaRec.stopRecord();
}, 10000);
}
Full Example
< !DOCTYPE html>
// Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false);
// Record audio // function recordAudio() { var src = "myrecording.mp3"; var mediaRec = new Media(src, onSuccess, onError);
// Record audio mediaRec.startRecord();
// Stop recording after 10 sec var recTime = 0; var recInterval = setInterval(function() { recTime = recTime + 1; setAudioPosition(recTime + " sec"); if (recTime >= 10) { clearInterval(recInterval); mediaRec.stopRecord(); } }, 1000); }
// PhoneGap is ready // function onDeviceReady() { recordAudio(); }
// onSuccess Callback // function onSuccess() { console.log("recordAudio():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; }
Recording audio…
MediaError
A MediaError object is returned to the mediaError callback function when an error occurs.
Properties
code: One of the predefined error codes listed below.
message: Error message describing the details of the error.
Constants
MediaError.MEDIA_ERR_ABORTED
MediaError.MEDIA_ERR_NETWORK
MediaError.MEDIA_ERR_DECODE
MediaError.MEDIA_ERR_NONE_SUPPORTED
Description
The MediaError object is returned to the user through the mediaError callback function when an error occurs.
mediaError
A user specified callback function that is invoked when there is an error in media functions.
function(error) {
// Handle the error
}
Parameters
error: The error returned by the device. (MediaError)







