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;
};
Related
I was trying some cookbook samples of phonegap app(along with xui) to read write files to local storage(SD card), PhoneGap is so popular in its file io, but when I tried on the device it didn't do anything. I think somebody has encountered same things.
The code is shown below:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width;" />
<title>File Download</title>
<script type="text/javascript" src="xui.js"></script>
<script type="text/javascript" src="cordova-2.0.0.js"></script>
<script type="text/javascript" >
var downloadDirectory;
document.addEventListener("deviceready", onDeviceReady, true);
function onDeviceReady() {
window.requestFileSystem(
LocalFileSystem.PERSISTENT,
0,
onFileSystemSuccess,
null
);
x$('#download_btn').on( 'click', function(e) {
download();
});
}
function onFileSystemSuccess(fileSystem) {
fileSystem.root.getDirectory('my_downloads',{create:true},
function(dir) {
downloadDirectory = dir;
},fail);
}
function fail(error) {
x$('#message').html('We encountered a problem: ' + error.code);
}
function download() {
var fileURL = document.getElementById('file_url').value;
var localFileName = getFilename(fileURL);
x$('#message').html('Downloading ' + localFileName);
var fileTransfer = new FileTransfer();
fileTransfer.download(fileURL, downloadDirectory.fullPath + '/' + localFileName,
function(entry){
x$('#message').html('Download complete. File saved to: ' + entry.fullPath);
},
function(error){
alert("Download error source " + error.source);
}
);
}
// Obtain the filename
function getFilename(url) {
if (url) {
var m = url.toString().match(/.*\/(.+?)\./);
if (m && m.length > 1) {
return m[1] + '.' + url.split('.').pop();
}
}
return "";
}
</script>
</head>
<body>
<input type="text" id="file_url" value="http://blogs.adobe.com/adobeingovernment/files/2012/07/phonegap.jpg" />
<input type="button" id="download_btn" value="Download" />
<div id="message"></div>
</body>
</html>
I already reviewed android manifest file, it has all permission including write to external storage. Kindly advise.
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
I am trying to access a text file inside the www folder of one of my phonegap applications from the index.html. I don't think filereader works because it accesses the phone's file system and not the application's file system. Regardless, here's what I tried and it jumps to the error function when this line is called within gotFS:
fileSystem.root.getFile("version.txt", null, gotFileEntry, fail);
Here's my full index.html code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<script charset="utf-8" src = "jquery-1.10.1.min.js"></script>
<script charset="utf-8" src = "cordova-2.7.0.js"></script>
<script>
function test()
{
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
document.write("gotFSreached");
fileSystem.root.getFile("version.txt", null, gotFileEntry, fail); // this jumps to fail
}
function gotFileEntry(fileEntry) {
document.write("gotFileEntryreached");
fileEntry.file(gotFile, fail);
}
function gotFile(file){
document.write("gotFilereached");
readAsText(file);
}
function readAsText(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as text");
document.write(evt.target.result);
};
reader.readAsText(file);
}
function fail(evt) {
document.write("error");
}
</script>
<body>
<button type="button" onclick="test()">Print version.txt</button>
</body>
</html>
$.get("version.txt", function(data) {
// there u have version.txt data (in var data)
});
I am trying to create a database using phonegap's api:
In order to do this I have used the following html:
<!DOCTYPE HTML>
<html>
<head>
<title>Cordova</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.0.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() {
var db = window.openDatabase("test", "1.0", "Test DB", 1000000);
alert("database created");
}
</script>
</head>
<body>
<form name="input" action="html_form_action.asp" method="get">
<input type="submit" value="Create Db" />
</form>
</body>
</html>
The buttone doesnt do anyting. The idea is that when the app starts I'm supposed to get confirmation that a database has been created. However this is not happening. Please help...
**Hi check whether Deviceready fires or not then try this **
function onDeviceReady() {
alert("onDeviceReady");
try {
if (!window.openDatabase) {
alert('Browser does not Support this');
} else {
var shortName = 'DbName';
var version = '1.0';
var displayName = 'DBName';
var maxSize = 100000; // in bytes
openDatabase(shortName, version, displayName, maxSize);
alert('DB created');
}
} catch(e) {
if (e == 2) {
// Version mismatch..
console.log("Invalid database version.");
} else {
console.log("Unknown error "+ e +".");
}
return;
}
}
I think there is problem in your js location path . I run your code and i didn't get any error.
Please check your path of your cordova.js . I think you put that js in js folder of assets/www/js
I dont think 'alert()' works inside a webview as-is. Try console.log() instead to output a message (if you are using eclipse), or some other method - perhaps changing the content of a div - to show you the results.
Trying to load an image into onto an html5 canvas and then running the html5 on Android using Phonegap. Here is my HTML.
<!DOCTYPE HTML>
<html>
<body>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script type="text/javascript">
var c=document.getElementById("myCanvas");
var cxt=c.getContext("2d");
var img=new Image()
img.src="img_flwr.png"
cxt.drawImage(img,0,0);
</script>
<img src="img_flwr.png"/>
</body>
</html>
I have included the standard img tag to demonstrate the problem.
Under Firefox, this page correctly shows the image rendered on the canvas and in the standard img tag.
When I deploy to Android emulator using Phonegap, only the standard img displays the picture.
Both the html and the .png file are in the assets/www folder of my phonegap project.
How can I get the image to render correctly on the canvas?
EDIT.. Fixed (thanks Avinash).. its all about timing.. you need to wait until the img is loaded before drawing onto the canvas ..vis
var c=document.getElementById("myCanvas");
var cxt=c.getContext("2d");
var img=new Image()
img.src="img_flwr.png";
img.onload = function() {
cxt.drawImage(img,0,0);
};
It might be the delay in loading the image(it's just a Guess of mine, I'm not sure. If it helps I'll be Glad) ...
Try this code(which waits until the page is loaded completely)
<!DOCTYPE HTML>
<html>
<body>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script type="text/javascript">
window.onload = function() {
var c=document.getElementById('myCanvas');
var cxt=c.getContext('2d');
var img=new Image();
img.src='img_flwr.png';
cxt.drawImage(img,0,0);
};
</script>
<img src="img_flwr.png"/>
</body>
</html>
Or you can do after the Image is loaded as follows
var c=document.getElementById('myCanvas');
var cxt=c.getContext('2d');
var img=new Image();
img.onload = function() {
cxt.drawImage(img,0,0);
};
img.src='img_flwr.png';
Please let me know if the problem still persists ...
I haven't had a chance to try this but try to refer to your image as:
file://android_asset/www/img_flwr.png
I tried without the img tags for PhoneGap 1.1.0 Xcode 4.2 and the Image() class onload events fire but the images report zero widths and heights. If the img html tags are added they work. So I am thinking device ready is not a place to do this or this shows an incompatibility with how a js programmer might expect the events and sequencing to work. Having the images floating around off screen open issues with multiple resolutions.
Here is the stub code.
var tileLoaded = true;
var dirtLoaded = true;
function onBodyLoad()
{
document.addEventListener("deviceready", onDeviceReady, false);
}
/* When this function is called, PhoneGap has been initialized and is ready to roll */
/* If you are supporting your own protocol, the var invokeString will contain any arguments to the app launch.
see http://iosdevelopertips.com/cocoa/launching-your-own-application-via-a-custom-url-scheme.html
for more details -jm */
function onDeviceReady()
{
// do your thing!
//navigator.notification.alert("PhoneGap is working");
console.log("device on ready started");
canvas = document.getElementById('myCanvas');
c = canvas.getContext('2d');
canvas.addEventListener('mousedown', handleMouseDown, false);
window.addEventListener('keydown', handleKeyDown, false);
tileMap = [];
tile.src = "img/tile.png";
//tile.onLoad = tileImageLoaded();
dirt.src = "img/dirt.png";
//dirt.onLoad = dirtImageLoaded();
console.log("device on ready ended");
draw();
}
function tileImageLoaded()
{
console.log("tile loaded");
console.log("draw - tile.width:" + tile.width);
console.log("draw - tile.height:" + tile.height);
tileLoaded = true;
draw();
}
function dirtImageLoaded()
{
console.log("dirt loaded");
console.log("draw - dirt.width:" + dirt.width);
console.log("draw - dirt.height:" + dirt.height);
dirtLoaded = true;
draw();
}