Phonegap app wont play audio - android

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();
}

Related

Phonegap Build App - Play Audio

So, i have made an app with phonegap build, where the goal is to read a xml file that contains info about audio tracks, and includes the path for each audio track.
I proceed to input the data of xml file into html, and before it was working fine. After i imported my project into phonegap build, no more audio plays. The controls work, but the audio doesn't play.
Here is the code:
<script>
document.addEventListener('play', function(e){
var audios = document.getElementsByTagName('audio');
for(var i = 0, len = audios.length; i < len;i++){
if(audios[i] != e.target){
audios[i].pause();
}
}
}, true);
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","teste.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
document.write("<table><tr><th>Track</th><th>Description</th<th>URL</th></tr>");
var x=xmlDoc.getElementsByTagName("CD");
for (i=0;i<x.length;i++){
document.write("<tr><td>");
document.write(x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("DESCRIPTION")[0].childNodes[0].nodeValue);
document.write("</td><td>");
var audio = x[i].getElementsByTagName("URL")[0].childNodes[0].nodeValue;
document.write('<audio controls><source src="'+audio +'" type="audio/mpeg"></audio>');
document.write("</td></tr>");
}
document.write("</table>");
</script>
The XML file is simply structured like this:
<CD>
<TITLE>Track one</TITLE>
<DESCRIPTION>Bob Dylan</DESCRIPTION>
<URL>files/test.mp3</URL>
</CD>
I have read some similar questions and find that most mistakes are in the PATH of the audio file. What should i do for the audio to play?
Thanks
EDIT: I have updated my code:
var path = '/android_asset/www/';
var audio = x[i].getElementsByTagName("URL")[0].childNodes[0].nodeValue;
var audioPath = path+audio;
alert(audioPath);
document.write('PLAY<br/>');
document.write('PAUSE<br/>');
document.write('STOP');
document.write('<p id="audio_position"></p>');
The alert(audioPath) returns the correct path and it works when I use this function:
function onDeviceReady() {
playAudio('/android_asset/www/files/test1.mp3');
}
The audioPath is the same as the path above.
But the app doesn't play the sound when i press Play...
Any ideas?
playAudio function:
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);
}
}
FOUND my problem! It was the 'onclick'. I now import jQuery and built the following code:
$(".btPlay").on("click",function (e) {
// body...
console.log("Play");
playAudio(audioPath);
});
It now works!
Try to install the cordova Media plugin org.apache.cordova.media (http://docs.phonegap.com/en/edge/cordova_media_media.md.html)
And then, try this :
//src is your path to your file
var my_media = new Media(src, function(){
alert("Success");
}, function(){
alert("Fail");
});
my_media.play();
Try it with all the paths yuo already tried, but this plugin works for me with online files.
EDIT: You may need to add '/android_asset/www/' in front of your src

Cordova/Phonegap YouTube iframe_api error: XMLHttpRequest cannot load chrome-extension Cross origin requests are only supported for HTTP

I am trying to use the a YouTube iframe API with my cordova-android project. When I run the code in a browser on my computer it runs perfectly, but when i build my app and run it on my phone the page containing the iframe will not load, and i get the following error in my console:
XMLHttpRequest cannot load chrome-extension://boadgeojelhgndaghljhdicfkmllpafd/cast_sender.js. Cross origin requests are only supported for HTTP
Here is my code:
<div class='ui-body ui-body-a'>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
console.log('Loaded Video)
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
</div>
Thanks in advance!
I got it to work by using glitchbone's cordova plugin YoutubeVideoPlayer.

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

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

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 Videos from Chrome Filesystem Not Working on Android

I am trying to create an offline video player that would download video content from my site for later viewing offline via an HTML5 video element. The code below works fine in Chrome for the desktop, but not on mobile (Nexus S smartphone, Nexus 7 tablet, 4.1 since only that runs chrome, which is required for the filesystem api). I am using the filesystem API that is supported by chrome on both the desktop and mobile.
I have confirmed it is correctly storing the file on the mobile device and I can retrieve the file correctly, but for some reason after retrieving the video from the localsystem chrome does not want to play the video. This is true whether I am using the html5 video element or whether I am navigating directly to the filesystem URL. When I use the html5 video element it returns the error media_err_not_supported. I have confirmed that the device can play the video if I navigate directly to it on my server (without first storing it using the filesystem api), so the issue is not a codec or video format problem. I am also using the video/mp4 mime type in both cases.
Again, this works on desktop, but not mobile. Any ideas?
Here is the code we are using:
<!DOCTYPE html >
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"> </script>
<script type="text/javascript">
var _fs;
var filename = "test3.mp4";
var diskSpaceRequired = 10 * 1024 * 1024;
$(document).ready(function () {
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
function onInitFs(fs) {
_fs = fs;
getVideo(fs);
}
if (!!window.requestFileSystem) {
window.webkitStorageInfo.requestQuota(
window.webkitStorageInfo.PERSISTENT,
diskSpaceRequired, // amount of bytes you need
function () { },
function () {}
);
window.requestFileSystem(window.PERSISTENT, diskSpaceRequired, onInitFs, function () { alert('error'); });
} else {
alert('not supported');
}
$("#play").on('click', playVideo);
$("#ourVideo").on('error', function(e) { console.log('ERROR!!!', e, arguments);
console.log($("#ourVideo")[0].error);
});
});
function playVideo() {
_fs.root.getFile(filename, {}, function (fileEntry) {
$("#ourVideo").attr('src', fileEntry.toURL());
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function (e) {
$("#ourVideo").get(0).play();
};
reader.readAsText(file);
}, errorHandler);
}, errorHandler);
}
function getVideo(fs) {
fs.root.getFile(filename, { create: true }, function (fileEntry) {
fileEntry.createWriter(function (fileWriter) {
fetchResource(fileWriter);
}, errorHandler);
}, errorHandler);
}
function errorHandler(e) {
console.log('error', e);
}
function fetchResource(fileWriter) {
console.log('fetchresource');
var xhr = new XMLHttpRequest();
xhr.responseType = "arraybuffer";
xhr.open("GET", "http://mydomain.com/trailer.mp4", true);
xhr.onload = function(e) {
if (this.status == 200) {
var bb = new WebKitBlobBuilder();
bb.append(this.response);
var blob = bb.getBlob("video\/mp4");
fileWriter.write(blob);
} else {
console.log(this.status);
}
};
xhr.send();
}
</script>
<title>foo</title>
</head>
<body>
<input type="button" value="Play Video" id="play"/>
<video id="ourVideo" controls="">
<source id="vidSource" type="video/mp4"/>
</video>
</body>
</html>
The problem looks like your android chrome coudn't access the android file system correctly, For that you can use nanoHttpd server for access android local files in device or sdcard.
for NanoHttpd server use this one class in your application and pass the media file location as http://localhost:8081/sdcard/(your_media_location).mp4
or get nanoHttpd from https://gist.github.com/1893396
I think this is more accurate to access sdcard files than directly calling for them
try change html part to
</head>
<body>
<input type="button" value="Play Video" id="play"/>
<video id="ourVideo" controls="">
<source src="video1.mp4" type= "video/mp4">
<source src="video1.ogv" type= "video/ogg">
</video>
</body>
you can convert your mp4 to ogv using
http://video.online-convert.com/convert-to-ogg
and put ogv file in the same location in mp4
**for more information check out these
http://www.broken-links.com/2010/07/08/making-html5-video-work-on-android-phones/
HTML5 <video> element on Android does not play

Categories

Resources