Wednesday, 13 June 2012

Play sound in iPhone | Phonegap

Ahh! After lot of search i found some clue for playing sound in iPhone through phonegap.
Path for  sound file --> import your sound file inside www folder.
Let say :
Path : www->src->alarm.wav
i)initiateAudio()-> This function describes to initiate the audio tag on source and set source attribute.
ii)playAudio()-> Use this function to play sound file.


if you want to check the fileformat 

if (audio.canPlayType('audio/mpeg')) 
source.type= 'audio/mpeg'; 
source.src='your_file_name.mp3'; 
else 
source.type= 'audio/wav'; 
source.src='your_file_name.wav'; 
}

EXAMPLE:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Play Sound in both OS</title>
<script type="text/javascript" src="js/cordova-1.8.0.js"></script>
<script type="text/javascript">
$(document).ready(function()  {
 initiateAudio();
});
var audio;
function initiateAudio() {
if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
//CODE_FOR_IPHONE_||_IPAD
    var source= document.createElement('source'); 
    audio= document.createElement('audio'); 
    source.type='audio/wav';
    source.src='src/alarm.wav'; 

    audio.setAttribute('src', source.src); 
   
}else{
      //CODE_FOR_ANDROID
      audio = new Media("/android_asset/www/src/alarm.wav");
}
}
function playAudio(){
audio.play();
}
</script>
</head>
<body>
//YOUR_CONTENT_HERE
</body>
</html>

No comments:

Post a Comment