Play local audio on iOS device with PhoneGap

Published: 10 years ago

Recently I had a problem getting audio files to play in iOS with PhoneGap (2.9.0) while it was working perfectly fine on android devices.

Here's the example code I was using:

// console audio after playing
function audio_win(response)  { console.log('Audio FAILED' + response); }
function audio_fail(response) { console.log('Audio WINNER' + response); }

// file path for ios 
// src = file:///var/mobile/Applications/271BF94B-8540-43FB-944E-39E5AC7A9A3F/[APP-PACKAGE-NAME]/www/sounds/filename.mp3
var src = location.origin;

// call the media function
var audio = new Media(src, audio_win, audio_fail );

// PRODUCES ERROR
audio.play()

Here's the updated fixed version:

// console audio after playing
function audio_win(response)  { console.log('Audio FAILED' + response); }
function audio_fail(response) { console.log('Audio WINNER' + response); }

// file path for ios 
// src = file:///var/mobile/Applications/271BF94B-8540-43FB-944E-39E5AC7A9A3F/[APP-PACKAGE-NAME]/www/sounds/filename.mp3
var src = location.origin;

// ADDED
// remove file:// if on ios
if( device.platform === 'iOS' ) {
    src = src.replace('file://', '');
}

// call the media function
var audio = new Media(src, audio_win, audio_fail );

// WORKS!
audio.play()

Don't forget the PhoneGap APIs

In order to use the global variable device you will have to add the following in your config.xml, also remember you need to add the media API.




comments powered by Disqus
:?>