David Hope
David Hope

Reputation: 1536

Changing HTML5 video src dynamically on Android?

I have the following code which loads a local video on an Android device and places it in a HTML5 Video src tag:

Javascript code:

var path = 'file:///data/data/com.myapp.app/files/';

var src = path+'Intro.mp4';
var video = $("#introVideo");

video.find("source").attr("src", src);

HTML code:

<video id="introVideo" width="100%" poster="poster.jpg"controls>
<source src="" type="video/mp4">
</video>

This doesn't work on Android device. However, if i don't use the javascript code above and just use the video path like the following, everything works fine:

This works:

<video id="introVideo" width="100%" poster="poster.jpg"controls>
<source src="file:///data/data/com.myapp.app/files/Intro.mp4" type="video/mp4">
</video>

When i alert(src); I get the exact URL which is:

file:///data/data/com.myapp.app/files/Intro.mp4

Which means the video exist locally and there is an issue with my Javascript code above. But i don't understand what the issue is!

Can someone please advice on this issue?

Thanks in advance.

EDIT:

This is how the code above is trigerred:

$(document).on('click','.backit', function(e){

    var path = 'file:///data/data/com.myapp.app/files/';

    var src = path+'Intro.mp4';
    var video = $("#introVideo");

    video.find("source").attr("src", src);

});

EDIT:

Further investigation, I found out that the Video's src tag is being set correctly when i use my javascript code above, However, the video doesn't play when i set its src tag dynamically which is very strange.

Upvotes: 1

Views: 491

Answers (1)

Offbeatmammal
Offbeatmammal

Reputation: 8228

Not knowing what framework you're using, I just did a quick test for a similar scenario using an existing bare-bones Android app that loads an HTML page, and this worked for me (note that at runtime my webview is accessing assets from the file:///android_asset/ path as my videos are local to the project):

HTML

<video id="vid" width="320" height="240"></video>

Initial JS:

var path = 'file:///android_asset/';
var vid = document.getElementById('vid');
var src = document.createElement('source');

src.setAttribute('src', path + 'video1.mp4');

vid.appendChild(src);
vid.play();

to change the source to a new video

src.setAttribute('src', path + 'video2.mp4'); 

vid.load();
vid.play();

Upvotes: 1

Related Questions