Playing mp4 video in webview using html5 in android - html

I'm trying to play mp4 video in webView using HTML5 in android but unfortunately it's not working, So can anyone help me, how can i do it ?
Here is my code
HTML file with name new2.html
<video width="365" height="200" src="/sdcard/Download/video.mp4" controls autobuffer></video>
<!--<!DOCTYPE html>
<html>
<body>
<video width="320" height="240" controls autoplay>
  <source src="/sdcard/Download/video.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
</body>
</html>-->
Java file is:
public class WebActivity extends Activity {
WebView wv;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.web_activity);
wv = (WebView) findViewById(R.id.webview);
wv.loadUrl("file:///android_asset/new2.html");
wv.getSettings().setAllowFileAccess(true);
wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setPluginsEnabled(true);
// webview.loadUrl("file:///android_asset/new.html");
}
}
XML file is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>

You need to call your file through local host -- file://localhost/ -- otherwise your phone will not recognize that it is you asking for permissions. By using your browser without localhost you are pinging off a satellite and can not make it back on re-rentry.
You are getting the controls to display because they come from a public html folder, but your source ( the video ) does not.

From this blog it states there are two steps:
Create new class that extends ContentProvider and override essentially 1 method openFile. Method onCreate can be empty returning true and the rest can just throw UnsupportedOperationException.
Add a provider entry to AndroidManifest.xml.
This page shows how to do it as well - a summary from that page follows:
Step 1: Declare your Content Provider in AndroidManifest.xml:
<provider android:name="MyDataContentProvider"
android:authorities="com.techjini" />
^^^^^^^^^^^ change this
Step 2:
Create your ContentProvider and implement openFile.
All you have to do is get real path from uri, open it and return the descriptor
URI uri = URI.create("file:///data/data/com.techjini/files/myImage.jpeg");
^^^^^your path to your file
File file = new File(uri);
ParcelFileDescriptor parcel =
ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
return parcel;
You can find out where your image is stored using:
System.out.println(getFilesDir().getAbsolutePath());
You can now load the file:
myWebView.loadUrl("content://com.techjini/myImage.jpeg");
^^^^^^^^^^^change to same as in manifest
hope that helps.

What happens if you change "/sdcard/Download/video.mp4" to "file:///sdcard/Download/video.mp4"? I mean the html part:
<video width="365" height="200" src="file:///sdcard/Download/video.mp4" controls autobuffer></video>
I couldn't open the html page in a custom web app. However I noticed that without adding "file:///" the video wouldn't play in my android browser. (In my case by adding "file:///" it took some time before the video started loading.)

<video width="365" height="200" src="video.mp4" controls autobuffer></video>
and the video.mp4 should be in your assets folder, the same place where you are putting your new2.html

To play MP4 video in WebView, you need to first declare Content Provider in Manifest
<provider android:name = "MyDataContentProvider" android:authorities="com.myapp" />
Implement open file with open() method −
URI myURL = URI.create("file:///mypath/new.mp4");
File f = new File(myURL);
ParcelFileDescriptor p =
ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY);
return p;

Related

can't play video with local file in android

i have avi file in local file directory
file:///storage/emulated/0/ionic_download/2022-02-07/18/18-59-32.avi
but the problem is that I want to play video with above file path.
data[i].toURL() is above file path
html
<video controls autoplay width="{{top_box_width}}" height="{{top_box_height}}">
<source [src]="play_path" type="video/mp4">
</video>
.ts
let myURL = normalizeURL(data[i].toURL() ) + "#t=0.1";
console.log("222"+myURL);
this.play_path = this.sanitizer.bypassSecurityTrustResourceUrl(data[i].toURL());
console.log('Cccccontent path cahnged ', this.play_path);
this.dismiss_loading();
both myURL and play_path is not playing video…
how can I play video?
thank you
chorme://inspect result is
what is really weird for me is that with fileopener.open
it works. so file path is not wrong or not found
this.fileOpener.open("file:///storage/emulated/0/ionic_download/2022-02-07/18/18-59-32.avi", 'video/mp4')
.then(() => console.log('File is opened'))
.catch(e => {
console.log('Error opening file', e);
if(e.message == "File not found"){
alert("파일이 없습니다.");
this.localstorage_remove(file_name);
}
});
AFAIK you should not define savePath inside functions. Your html code cannot even find the variable savePath because its being defined and initialized much later after the whole HTML has been rendered.
Define your savePath variable as global then initialize it inside your function using this.savePath. Your code should work.

Playing video from directories that are not in webroot

I can play video files from a IIS web server to a client web app as long as they reside in the webroot directory on the server. I would like to play them from a shared directory not in the webroot, however. Is this possible??
Javascript function calling up video file, Videos is share name:
function loadAnotherVideo() {
var video = document.getElementById("video");
var source = document.getElementById("fileSelector");
var path = "//192.168.0.18/Videos/" + source.value;
alert(path);
video.src = path;
video.load();
video.play();
}
You should be able to do something like this, just make sure the App Pool has reading rights on the folder where the file is stored
File - video.aspx
private void Page_Load(object sender, System.EventArgs e)
{
//Set the appropriate ContentType.
Response.ContentType = "video/mp4";
//Get the physical path to the file.
string FilePath = "c:\path-to-video\video.mp4";
//Write the file directly to the HTTP content output stream.
Response.WriteFile(FilePath);
Response.End();
}
HTML
<video width="320" height="240" controls>
<source src="video.aspx" type="video/mp4">
Your browser does not support the video tag.
</video>
Based on a comment
Here is a post showing how to set/change a video source using javascript:
Changing source on html5 video tag

HTML5 Audio events with QWebView

Trying to get the hooks for the audio tag events in the HTML5 through QtWeKit. For that I created a sample application that just loads a html file through QwebView.
The html file contains a HTML5 audio tag.
<audio id="audio_with_local_controls" controls>
<source src="nokia-tune.mp3" type="audio/mp3" />
</audio>
In the script side, I'm trying to get the hooks for the audio tag play, pause and ended events.
/// AUDIO TAG EVENTS.
var aid = document.getElementById('audio_with_local_controls');
function onplay_(){
console.log('onplay');
alert('onplay');
}
function oncanplay_(){
console.log('oncanplay');
alert('oncanplay');
}
function onpause_(){
console.log('onpause');
alert('onpause');
}
console.log(aid);
aid.onplay = onplay_;
aid.oncanplay = oncanplay_;
aid.onpause = onpause_;
aid.onprogress = function onprogress_(){ alert('onprogress'); }
aid.onended = function onended_(){ alert('onended'); }
aid.onabort = function onabort_(){ alert('onabort'); }
The code sequence might not make sense as I was trying something up and down in the code.
Chrome was able to capture the hooks. But QWebView remains silent on this, nothing gets captured.
Is it that QWebView doesn't support this? or Am I writing something wrong?

How to embed video in iframe

Using HTML5 Video Support is pretty amazing but doesn't work in IE versions, So i didn't prefer it.
I am using MVC4 Razor View engine for development.
I came up with this issue-
While i embed video directly from youtube then it is working fine. But when i upload a video and then show it through #Model.FilePath then it is not even showing iframe there. The path is correct.
Controller-
[HttpPost]
public ActionResult Index(HttpPostedFileBase file, SystemUser user)
{
if (file != null && file.ContentLength > 0)
{
string path = Server.MapPath("~/Logo/");
file.SaveAs(path + file.FileName);
string filePath = "/Logo/" + Path.GetFileName(file.FileName);
string Extension = Path.GetExtension(file.FileName);
var scope = (from u in dv.SystemUsers
where u.UserId == this.LoggedInUser.UserId
select u).FirstOrDefault();
scope.FilePath = filePath;
scope.FileName = file.FileName;
dv.SystemUsers.GetModifiedMembers(scope);
dv.SubmitChanges();
return RedirectToAction("userprofile", "User");
}
return View();
}
View-
#model MvcApplication8.Models.SystemUser
<h2>
UserProfile</h2>
<iframe width="560" height="315" src="#Model.FilePath" frameborder="0" ></iframe>
FilePath-
/Logo/video-2012-12-08-21-31-56.mp4
While working with images instead of video using <img src="#Model.FilePath"> it was working excellent.
What went wrong with iframe embedding?
Are you looking for network (with example devTool F12 Chrome) if he found your url ? After saved your video, can you read it ?
you can try with
#Url.Content("~/Logo/video-2012-12-08-21-31-56.mp4")
OR
UPDATE
you do this :
#Url.Content(Model.Filepath)
This work fine for me !
or example (jsfiddle) here

Html Image src path with shared network is not working in firefox

In My webpage i am using a image tag, the src attribute is pointing to shared network location ie (/server/images/image1.png). The exact script is "<img src="file://///server/images/image1.png". It is working fine in IE. In firefox, when I do debug using firebug its showing image, but it's not displayed in page (user view). Even it's working fine when copy this location and place it in firefox address bar. What will be the problem while using img tag also what is the solution for this? Thanks in advance.
Putting this as an answer here so as to provide help for others like myself that was searching for how to display networked images and came accross this SO post in the top 3 search engine results. It also seems like a better answer than the java servlet issuing images in the response.
FireFox would not display networked images so I created an MVC helper that extends HtmlHelper.
public static class ImageHelper
{
/// <summary>Converts a photo to a base64 string.</summary>
/// <param name="html">The extended HtmlHelper.</param>
/// <param name="fileNameandPath">File path and name.</param>
/// <returns>Returns a base64 string.</returns>
public static MvcHtmlString PhotoBase64ImgSrc(this HtmlHelper html, string fileNameandPath)
{
var byteArray = File.ReadAllBytes(fileNameandPath);
var base64 = Convert.ToBase64String(byteArray);
return MvcHtmlString.Create(String.Format("data:image/gif;base64,{0}", base64));
}
}
use in the MVC View like so:
using
<img src="#Html.PhotoBase64ImgSrc(image)" height="60px" width="60px" alt="photo" />
here the 'image' in #Html.PhotoBase64ImgSrc(image) is a pure network UNC, e.g.
//Photos/ebaebbed-92df-4867-afe8-0474ef8644eb.jpg
Create a regular HTML img element like so:
<img id="image1" runat="server" ImageUrl=<%# Eval("Value") %>/>
And in code behind do this:
image1.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(bytes);
Where bytes is a byte[].
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["FileName"] != null)
{
// Read the file and convert it to Byte Array
string filePath = "C:\\Users\\Public\\Pictures\\Sample Pictures\\";
string filename = Request.QueryString["FileName"];
string contenttype = "image/" + Path.GetExtension(filename).Replace(".", "");
FileStream fs = new FileStream(filePath + filename, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
image1.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(bytes);
}
}
You are done. The image will be displayed.
The solution usually is: use a web server.
You may have to make it like so.
<img src="../server/images/image1.png" />
Once you add the "../" it is basically telling your browser to go back one directory to search for the location after the "../" .
Where is the file located and where is the location of your HTML document?
UPDATE:
I do all of my work on a Network Server as well... This should do the trick.
<img alt="" src="file:///SERVER:/FOLDER/IMAGES/image1.png" />
Thanks,
Aaron
I wrote a servlet which reads the file from LAN using Java File Stream and sets it in response and it does the trick. Thanks to all for valuable response.