PhoneGap function 'Media' to play sound doesn't work - android

I have very simple code like this:
<script type="text/javascript" charset="utf-8">
function playAudio() {
// i try to specificate path to audio file different ways:
var src ="/android_asset/www/track.mp3";
//src = "http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3";
var media = new Media(src, // success callback
function() {
console.log("playAudio():Audio Success");
},
// error callback
function(err) {
console.log("playAudio():Audio Error: "+err);
});
alert('sm'); // alert doesn't work -> so prev func 'new Media' doesn't work too
media.play();
}
</script>
And call of this func is such:
<body onload="playAudio()">
I don't understand - why doesn't it work? Audio file is 'assets/www/track.mp3'

The problem is here
var src ="/android_asset/www/track.mp3";
JS don't know /android_asset/
Only JAVA know about this path only so either use java - JS injection or put this file inside www folder.

I don't understand yet why, but when I try do work with this code:
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
function playAudio(url) {
// Play the audio file at url
// http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3
var my_media = new Media(url,
// success callback
function () {
console.log("playAudio():Audio Success");
alert("ok");
},
// error callback
function (err) {
console.log("playAudio():Audio Error: " + err);
alert("oops");
}
);
// Play audio
my_media.play();
}
</script>
And called it in:
Play Audio
Or when I call it this way:
Play Audio
Only on simulator it work! But in web-browser it doesn't work still yet

Related

Phonegap app wont play audio

I'm making a app with several audio files, but it won't play on the phone. It won't work even without /android_asset/www/.
Here's my code:
<script>
var at_du_bruger_det = new Audio('/android_asset/www/sound/at_du_bruger_det.wav');
</script>
<div class="swipebox portfolio-wide-item" onclick="at_du_bruger_det.play();">
<h3>At du bruger det</h3>
<p>Tryk for at afspille</p>
<div class="overlay"></div>
<img class="responsive-image" src="images/at_du_bruger_det.jpg" alt="img">
</div>
I've added the org.apache.cordova.media plugin to the config file.
If you look at the Cordova Media plugin documentation, you can see that a Media object is required:
// 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();
}

working samples for using cordova media plugin to play sound in intel xdk

Can anybody please recommend a working example for using cordova media plugin in intel xdk environment to play sound on android phones? I tried this example (http://qnimate.com/create-a-music-player-app-using-intel-xdk/) without luck. The code for that sample is attached. I tried html5 audio tag and Soundjs library but they don't play sound on android native browser. Some online posts suggest the cordova media plugin would be a fix for android browser. However, I googled a lot and still cannot find a working example. Your help will be much appreciated.
<!DOCTYPE html>
<html>
<!--
* Please see the included README.md file for license terms and conditions.
-->
<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="js/fastclick.js"></script>
<link rel="stylesheet" href="css/app.css">
</head>
<body>
Play Audio
Pause Playing Audio
Stop Playing Audio
<p id="audio_position"></p>
<script src="intelxdk.js"></script>
<script src="cordova.js"></script>
<script src="xhr.js"></script>
<script src="js/cordova-init.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() {
//http://labs.qnimate.com/sound.mp3
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>

Error calling method on NPObject in FileReader in cordova app (Intel xdk android build)

I was trying to follow this instructions to be able to read files.
As a result I do have access to the file system BUT reading file produce an error:
Uncaught Error: Error calling method on NPObject
Fun part is that if I try to call readAsText(file) function for the second time The file reader finally reads a file but still produce the same error.
How to avoid this error and how to make fileReader work in the first call?
!DOCTYPE html>
<html>
<head>
<title>FileReader Example</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("readme.txt", null, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.file(gotFile, fail);
}
function gotFile(file){
readAsText(file);
readAsText(file);
}
function readAsText(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as text");
console.log(evt.target.result);
};
reader.readAsText(file);
}
function fail(evt) {
console.log(evt.target.error.code);
}
</script>
</head>
<body>
<h1>Example</h1>
<p>Read File</p>
</body>
</html>
This error occurs when you try, using method called from javascript interface, to interact with UI.
Check this here
For some reason following code works from the first time but still produces same error.
function gotFile(file){
readAsText(file);
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(){}, fail);
}
Could anyone explain this behavior?

Playing audio via phonegap and cordova for Android

I've been messing around with programming a test app for android and I've come across a issue playing a audio file. My problem lies with as soon as the page loads the audio file plays when it's not meant to and doesn't play via a button click
I'm using the example for cordova to get the audio to play but I can't work out why the audio plays straight away
Thanks
Script
script type="text/javascript" charset="utf-8" src="cordova-2.2.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
playAudio("/android_asset/www/audio/audio.mp3");
}
// Audio player
//
var my_media = null;
var mediaTimer = null;
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);
}
}
</script>
HTML button click
<a class="button" onclick="playaudio('/android_asset/www/audio/audio.mp3')";>Play that audio!</a>
Because onDeviceReady() is listener callback for addEventListener.
So whenever this listener instantiate your onDeviceReady() method will be called automatically.
And from that method you are calling playAudio() method, that's why your audio start playing automatically.
Remove this playAudio() method call from the onDeviceReady() callback function.
EDIT:
change this
<a class="button" onclick="playaudio('/android_asset/www/audio/audio.mp3')";>Play that audio!</a>
with,
<a class="button" onclick="playAudio('/android_asset/www/audio/audio.mp3');">Play that audio!</a>

Playing local sound in phonegap

I have a .wav file in my www folder. I am using jQuery with the following code. The alerts go off but the sound does not play. Am I doing something wrong?
<script type="text/javascript" charset="utf-8" src="phonegap-0.9.2.js"></script>
<script type="text/javascript" charset="utf-8" src="jquery.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
window.alert("READY!");
document.addEventListener("deviceready", onDeviceReady, true);
function onDeviceReady(){
window.alert("OK#!");
var snd = new Media("test.wav");
snd.play();
}
});
</script>
The sound just does not play.
You can use window.location.pathname to get the path of your application in any PhoneGap app. That way you don't have to hardcode it for Android. It will look something like this on iPhone:
/var/mobile/Applications/{GUID}/{appname}.app/www/index.html
And this on Android:
/android_asset/www/index.html
Strip off the /index.html, prepend file://, and append your file test.wav.
Demo: http://jsfiddle.net/ThinkingStiff/r7eay/
Code:
function getPhoneGapPath() {
var path = window.location.pathname;
path = path.substr( path, path.length - 10 );
return 'file://' + path;
};
var snd = new Media( getPhoneGapPath() + 'test.wav' );
Try giving an absolute local path. E.g.
new Media("/android_asset/www/test.wav");
That should work on Android. Hopefully they'll fix this in PhoneGap, as it's something of a bug in the cross-device support.
I have another version of getPhonegapPath, it detect's when you'r using Android:
function getPhoneGapPath() {
var path = window.location.pathname;
path = path.substr( path, path.length - 10 );
var devicePlatform = device.platform;
if(devicePlatform=="Android"){
path = 'file://'+path;
}
return path;
};

Categories

Resources