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

Related

Websockets in WebViews failing to connect, returning code 1006

I have created a simple websocket in an HTML page that works great and connects fine in all of the web browsers. However, when I load it in a web view like in an Android App it fails to connect and returns the code 1006. It is trying to connect to a different URL/endpoint so I am thinking this might be a CORS issue. I am building for a minimum target of API 23.
<!DOCTYPE html>
<html>
<body>
<h1>Socket Connect</h1>
<div id="container"></div>
</body>
<script>
const div = document.getElementById('container');
try {
console.log('connect');
var ws = new WebSocket('wss://anotherserver.com:3000');
ws.binaryType = 'arraybuffer';
}
catch (err) {
}
ws.onerror = function (error) {
// error is always blank
console.log('error');
};
ws.onopen = function () {
div.textContent = 'Opened';
console.log('opened');
};
ws.onclose = function (error) {
// always = 1006
div.textContent = error.code;
console.log(error.code);
};
</script>
</html>
I have read a few other posts about setting some options in my code and I have done that. See here
myWebView.getSettings().setAppCacheEnabled(true);
myWebView.getSettings().setDatabaseEnabled(true);
myWebView.getSettings().setDomStorageEnabled(true);
myWebView.getSettings().setCacheMode(currentCacheMode); /* use cache if not expired */
myWebView.getSettings().setJavaScriptEnabled(true);
I have set cleartext in my manifest as well
It ended up being a CORS issue.

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

Playing Youtube html5 videos on Android Phones using iframe API

I am using the following code to play HTML5 videos
<!DOCTYPE html>
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script type="text/javascript" id="youtubeplayer">
</script>
<script>
document.getElementById('youtubeplayer').style.width=window.innerWidth;
document.getElementById('youtubeplayer').style.height=window.innerHeight;
// 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', {
//videoId: localStorage.getItem('videoid'),
videoId : "8UVNT4wvIGY",
width : Math.abs(window.innerWidth*0.99),
height : Math.abs(window.innerHeight*0.99),
allowFullScreen : true,
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 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>
</body>
</html>
Basically I am embedding it in a HTML5 page.
It works very well on Desktop, but on a Android device (Google Nexus 10), it just shows the title of the video and the video doesn't load.
Fitvids plugin worked super well for me and played nicely within the bootstrap framework I was using.
From their github page:
<script src="path/to/jquery.min.js"></script>
<script src="path/to/jquery.fitvids.js"></script>
<script>
$(document).ready(function(){
// Target your .container, .wrapper, .post, etc.
$("#thing-with-videos").fitVids();
});
</script>
Boom done!

Streaming of ShoutCast .MP3 File in jPlayer on Android/iPhone

I have a very specific problem with jPlayer. I need to run it in Android/iPhone, which is no problem thanks to "jPlayer Android Fix" on the documentation. However, I also need it to stream a ShoutCast .MP3 file, not a ShoutCast stream. All the documentation I read points to a generic URL/IP/Port, but not a file.
I have got it all working with a static MP3 using the following code:
<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
var id = "#jquery_jplayer_1";
var bubble = {
mp3:"http://www.jplayer.org/audio/mp3/Miaow-07-Bubble.mp3"
};
var options = {
swfPath: "/jplayer2-4-0",
supplied: "mp3",
wmode: "window",
smoothPlayBar: true,
keyEnabled: true
};
var myAndroidFix = new jPlayerAndroidFix(id, bubble, options);
$('#setMedia-Bubble').click(function() {
myAndroidFix.setMedia(bubble);
$('.jp-title ul li').text('Bubble');
});
$('#setMedia-Bubble-play').click(function() {
myAndroidFix.setMedia(bubble).play();
$('.jp-title ul li').text('Bubble');
});
$("#jplayer_inspector").jPlayerInspector({jPlayer:$("#jquery_jplayer_1")});
});
//]]>
</script>
... but the moment I change
mp3:"http://www.jplayer.org/audio/mp3/Miaow-07-Bubble.mp3"
to
mp3:"http://live.station.ca:8000/stream.mp3"
... I get nothing. I've even tried
mp3:"http://live.station.ca:8000/stream.mp3;stream/1"
Can anybody help? Thanks in advance!

PhoneGap Conversion - HTML to .apk

I am turning a HTML app into a .apk using https://build.phonegap.com and everything works great appart from my file selector.
<input name="file" type="file" id="file">
I want to be able to select images only (it doesnt matter if it can select more - but its the images I am looking for) from both camera and file system..
In the web version http://carbonyzed.co.uk/websites/assent/1/photos.html this works great from my phone, but when converted to .apk, this functionality is lost, and I can't seem to find anything on here, or online relating to this issue.
At least for me, the input file doesn't work in Phonegap.
You need use the Phonegap API to get picture and select the source where come from, like photolibrary, camera or savedphotoalbum.
See more info about camera.getPicture: http://docs.phonegap.com/en/2.1.0/cordova_camera_camera.md.html#camera.getPicture
and about Camera.PictureSourceType parameter of cameraOptions method: http://docs.phonegap.com/en/2.1.0/cordova_camera_camera.md.html#cameraOptions
Ended up using the Child Browser system like so
In the head
<script src="childbrowser.js"></script>
in the body
<button class="button-big" onClick="window.plugins.childBrowser.showWebPage('URL_TO_GO_HERE',
{ showAddress: false });" style="width: 100%;">UPLOAD PHOTOS</button>
which has a standard fileuploader like
<input name="file" type="file" id="file">
then it let me select from root storage, works in phonegap 2.2 onwards on both iOS and Android OS
To capture an image I used this in the head
<script type="text/javascript" charset="utf-8" src="json2.js"></script>
<script type="text/javascript" charset="utf-8">
// Called when capture operation is finished
//
function captureSuccess(mediaFiles) {
var i, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
uploadFile(mediaFiles[i]);
}
}
// Called if something bad happens.
//
function captureError(error) {
var msg = 'An error occurred during capture: ' + error.code;
navigator.notification.alert(msg, null, 'Uh oh!');
}
// A button will call this function
//
function captureImage() {
// Launch device camera application,
// allowing user to capture up to 2 images
navigator.device.capture.captureImage(captureSuccess, captureError, {limit: 2});
}
// Upload files to server
function uploadFile(mediaFile) {
var ft = new FileTransfer(),
path = mediaFile.fullPath,
name = mediaFile.name;
ft.upload(path,
"http://my.domain.com/upload.php",
function(result) {
console.log('Upload success: ' + result.responseCode);
console.log(result.bytesSent + ' bytes sent');
},
function(error) {
console.log('Error uploading file ' + path + ': ' + error.code);
},
{ fileName: name });
}
</script>
and this in the body
<input type="button" class="button-big" style="width: 100%;" onclick="captureImage();" value="TAKE PHOTO">
copy and past and it works a dream,
Check it out in this image
any questions, just email comment,
or email me... support#carbonyzed.co.uk

Categories

Resources