Just a quickie - a user on Stackoverflow asked how to both capture video and display it in the app. This is fairly easy with the Media Capture API so I thought I'd whip up a quick demo.
First, I created an HTML page with a button and an empty div to hold the video later on:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" type="text/css" href="css/app.css" />
</head>
<body>
<button id="takeVideo">Take Video</button>
<div id="videoArea"></div>
<script src="cordova.js"></script>
<script src="js/app.js"></script>
</body>
</html>
And then I wrote up the following JavaScript:
document.addEventListener("deviceready", init, false);
function init() {
document.querySelector("#takeVideo").addEventListener("touchend", function() {
console.log("Take video");
navigator.device.capture.captureVideo(captureSuccess, captureError, {limit: 1});
}, false);
}
function captureError(e) {
console.log("capture error: "+JSON.stringify(e));
}
function captureSuccess(s) {
console.log("Success");
console.dir(s[0]);
var v = "<video controls='controls'>";
v += "<source src='" + s[0].fullPath + "' type='video/mp4'>";
v += "</video>";
document.querySelector("#videoArea").innerHTML = v;
}
So I begin by simply listening for a touch event to the button I create. I then use the Media Capture API to start the video process. In the success handler I just take the result's fullPath property and put it in HTML. I was kinda surprised the path worked as I had thought I'd need to use a URL form, but it worked just fine.
Here it is running on my iPad.

If for some reason you want to try this yourself, I uploaded it to my Cordova demo repo: https://github.com/cfjedimaster/Cordova-Examples/tree/master/videotest1.
Archived Comments
Hi Raymond,
Love reading your blog and it has taught me a lot about Cordova and Ionic, which I'm using. Just wondering if this would work on an Android device? I can see that the returned mediaFile has the full path in the format of file:/ and a localURL of cdvFile:/// which I was previously trying to use with videogular but without any luck. If I can simply do it with the video tag in HTML5 then I'll skip videogular altogether.
Thanks
Phil
What is videogular?
Hi Raymond,
Sorry for the delayed response. The day job got in the way. Videogular is angular powered video player (http://www.videogular.com/). I have used it successfully to play videos which I have stored on AWS. However it doesn't seem to work on local video files.
Thanks
Ah, thanks.
Hi,
Is there any way to record video with no audio?
Thanks!
I don't believe so. If the mobile platform itself supports it, you could do your own plugin of course.
hello! for some reason when i record on an android, the video will save back to the gallery, but when recording on iPhone it will not. any help would be very much appreciated!
Sorry - not sure about that one. In theory, you could use the File plugin to copy the media file.
Is it possible to choose to record in mp4 for android/iOS? not .MOV for example that iOS devices chooses
With the plugin - I don't believe so. There may be other plugins.
Too bad bad It give me a .3gp format that can't be read :(
Is there a solution for that ? Can't find one..
With Cordova 5.3.3 (with Crosswalk plugin) on Android 4.1.2
There is an options in media plugin :
"mode: The selected video capture mode. The value must match one of the elements in capture.supportedVideoModes".
But that property is empty array.. and It's the same for supportedAudioModes, supportedImageModes.
EDIT : Chrome can read .3gp ! I did a mistake in my HTML tag... I hope every devices return readable video type
Unfortunately I'm not aware of any. I do know there are good services out there that let you send video via REST and they do all kinds of cool conversions. These are paid services, but they work damn well.
Pls I want to upload the recorded video to php server but don't know how. Kindly assist me in that regards.
Pls I want to upload the recorded video to php server but don't know how. Kindly assist me in that regards.
Use the File-Transfer plugin. It allows for uploads.
See my other reply.
Thanks for your reply, but I really do not know why File-Transfer plugin had not working for me.
You mean why it isn't working? I don't know why either as I can't see your code. :) I'd post this to StackOverflow. Ensure you have as much data possible about the issue.
Ok! Thanks for your timely reply.
No no no - please do not post big code blocks here! That's not really appropriate for comments. As I said, this is more appropriate for StackOverflow. You are welcome to post the link to your SO post here - if I have time I'll try to help out.
I'm so so sorry! Thanks for your assistance. I'll comply with that subsequently. Let me delete those codes.
bj
sir how to change path .3pg to .mp4 by default.plz sir give me proper code
Eh?
sir plz give me code
I linked to the code.
Hi Raymond. I tweaked a bit your code using ng-cordova capture plugin wrapper within an ionic application. However on both iOS and Android the plugin launches the device's default camera application instead of only showing in the div as you mention. I can't actually see why it would behave differently, especially when the original cordova plugin also mentions that it launches the default device application. Any suggestion/comment on this?
It's been a while since I wrote this, but I think it is *supposed* to show the default video recorder. The video div is used when *done* to display the video you recorded.
I see. Too bad. I haven't managed to even show the video in the div once recorded even though the innerHTML seems to be provided properly.
Any idea how to use the default player inside a canvas instead of fullscreen?
Do you see any errors in the console?
Also, "default player" for a web view *is* the video tag.
This is really helpful, thanks!
Very helpful! Can you give an example for capture and display of audio? thank you very much in advance!
Hi, thx for the tutorial, i use in Android App and looks good, the problem is that the same code in Windows Phone App dont work, dont show the video when i record, can you help me? I think that the problem is that dont save the video.
I'd check the docs for the Media plugin and see what they say about Windows Phone. Outside of that, I can't help you - I don't have a device to test with. I'd also use IE's remote debug feature to see if you can flesh out any errors.
Display of audio? You can use the audio tag with controls I suppose.
I tried with this callback function, but give me back error.
// capture audio callback
var captureSuccess1 = function(mediaFiles) {
var a = "<audio controls="controls">";
a += "<source src="" + mediaFiles[0].fullPath + "" type="audio/mpeg">";
a += "</audio>";
document.querySelector("#audioArea").innerHTML = a;
};
// Error:
MediaPlayer: Attempt to call getDuration without a valid mediaplayer
Where is getDuration defined? That isn't being used in my code.
I don't know. I also don't use getDuration, this is, what the Android Studio give me back.
I assume you changed the code to record audio, not video, right?
Yes
It may be that the output is not appropriate for the audio tag in the web view. Check the MDN documentation for <audio> and see. Also look at the fullPath extension as it should tell you the format.
In fact, I bet that's it.
Remember though that you can play audio with the Media plugin. You don't need the <audio> tag. You have to build your own controls, but that's not too hard.
Hi Raymond , Thanks for this post . But still am not able to show the video. here is how I am using it.
$scope.openVideoGallery = function(){
navigator.camera.getPicture(onSuccess, onFail, { quality: 30,
destinationType : Camera.DestinationType.FILE_URI,
sourceType : Camera.PictureSourceType.PHOTOLIBRARY,
mediaType: Camera.MediaType.VIDEO
});
function onSuccess(s) {
supersonic.logger.log(s);
// var v = "<video width="240" height="200" controls="controls">";
// v += "<source src="" + s + "" type="video/mp4">";
// v += "</video>";
$scope.vid=s;
}
function onFail(message) {
alert('Failed because: ' + message);
}
};
<video controls="" width="240" height="200">
<source ng-src="{{vid | trustUrl}}" type="video/mp4"/>
</video>
Can you please let me know if something is missed ..? I also added the filter to trust the URL.The file uri is coming like below
"content://com.android.providers.media.documents/document/video%3A24556"
Most likely the issue is that the video recorded by the camera is not valid for the video tag in the web view. A simple way to test this would be for you to record a video on your phone, put it on a local web server, and try to play it via a video tag.
now i know that the video is saved, because i can transfer to server, but html5 video tag cannot play the video (windows phone issue) but my boss want to preplay the video before send to server....
If the webview can't use the video type generated by the device, then you really don't have much of a choice here. You either convert it locally or upload it to a service that can provide a compatible version. Or consider a plugin.
i am trying save the video in externalstorage but fail anyways, i hate WP, in android its easy.
Hi Raymond,
Did this sample work for an android device?, not working on my Lollipop OS device
I just tested on iOS. If it fails to work on Android, I'd check what I suggested on the other comments, that maybe the <video> tag doesn't like how Android records video. Also look in the console for any errors.
Thanks for your comment Raymond, I had to remove the file:// or file: part from the local video file path to get it working as mentioned in the Docs,
Can I control the captured video resolution
Nope. In the future, you can check the plugins docs (https://www.npmjs.com/packa... to see for yourself.
Hi, could you let me know how you managed to do that. Thanks.
just used resultingURL.replace("file:", ""); use string.replace method, good luck
Thanks again :)
You can use iDealshare VideoGo to convert MOV to Windows Media Player more supported WMV, AVI, ASF for playing MOV on all versions of Windows Media Player.
Great article may need to update to include the new privay policy for camera and microphone. I am seeing issues if i start in horizontal it's cut off I have to keep rotating the device for it to put the video recorder in correcty any suggestions?
"update to include the new privay policy for camera and microphone"
Sorry - what? I don't believe anything has changed here. Can you explain what you mean?
As for your issue with the video recorder - hmm - not sure. You can lock orientation of course, and you can force orientation too. That might be a strategy.
yea in your project.plist you now need to add in .
<key>NSMicrophoneUsageDescription</key>
<string>So we can record your wonderful voice</string>
and
<key>NSCameraUsageDescription</key>
<string>So you can VlogOn</string>
otherwise the app will just deliberatly crash out part of the new ios X
maybe pushing my luck here.. do i need to use the file plugins to save the video to the photo album?
Thanks - I wonder if the plugin will start doing this automatically once ios10 is released.
Nope.
I know you must be sick of newbs asking vapid questions but here goes-
I have implemented your code from github into a new Cordova project. I have added the media capture plugin (labeled only capture) via the Cordova UI and it is listed in plugin UI. The only code addition I made is the script include for weinre debug in index.html.
On testing when the button click produced no result in Android and iOS I added (into app.js) first an additional console.log() call and then alert() calls to init() and to the touchend event function.
After pushing these to test server I got the alerts (but no console output in debugger) for init() and for button releases but still no UI changes when clicking the button. No camera interface or any error output.
I'm running XDK 3522 on Windows 7 and using an iPhone 6 with version 9.3.5 and a Blu running Android 5.0 and kernel 3.10.54.
In my first project I am able to open camera interface and display selected/shot image. Also succeeded in displaying geopositioning data for device.
Weinre debug shows me no output and perhaps I am using unsuccessfully. I am utterly new to this toolset.
Any advice on debugging most appreciated. Thank you for sharing this (and putting up with all the questions).
Hi Raymond, thanks for the tutorial. Everything works properly, but I can't find captured video in the camera roll. Is there any way to save captured video to camera roll(ios) or gallery(android)?
Hi, it would be great if you shared how you can save the video to the photo album?
"The only code addition I made is the script include for weinre debug in index.html."
You should be aware that weinre is a very old project and is *NOT* recommended for debugging Cordova apps. You should use remote debug w/ Chrome or Safari.
"I'm running XDK 3522"
Unfortunately, I do not use XDK so I can't help you with that. The best I can suggest is the vanilla Cordova CLI and using Chrome Remote Debug for your Android testing.
You have access to the path, so you could use the File plugin and a copy command to move it over. I'm not sure if you will have access to the camera roll/gallery though.
Hey Paul you edit it in the cordova.m file you can also increase the filming resolution and compression
OK, thank you.
And thanks again for sharing this! I'm just trying my hand at Cordova for the first time and examples like this really help me get my head around discrete pieces of the process.
thank you, Patrick
thanks
sorry wrong file it should be CDVCamera.m I tried to add it here but it threw a hissy fit.
Raymond, the tutorial saved the day for me. Thanks a lot. It worked perfectly well for me, however, after displaying the captured video, I was not able to upload video to external server. I did not observe any error report. Please, how can I successfully upload video after the display of the captured video?
You would use the FileTransfer plugin.
Hi Raymond, is there anyway to create a File or a Blob from the MediaFile captured by the plugin? I've been struggling with making a file or blob to upload to a backend service.
I haven't done a lot with Blobs in JavaScript. I know you want to start by looking at ArrayBuffers. You *can* read in binary data using XHR (or the FIleSystem reader for Cordova). I'd say it's possible, but I haven't done much with it.
Wait. Hold on. If you just want to upload it, use the FileTransfer plugin. You've got the local path. That would be trivial.
HI Raymond, How about recording using front camera only?
Check the plugin options - you may be able to select only one camera.
Hi Raymond,
Thanks for great article
I want to keep recording video all the time, but only keeping last 2 minutes (on file), how can I do that?
As far as I know, you can't with the plugin as is. If the native SDK supports it, you could write your own plugin. Another option would be a 3rd party service that would trim the video for you. These exist, but you would have to upload the video first, and a long one would be a problem.
I still need to click again after system camera page pop up. Is it possible that I can capture directly without manually click? The reason is that I need my program running automatically.
You can fire off the call to start the camera when the app loads - right?
how can i get base64 or blob after success of video ? After Success 's' is a [Object object](Object Array) and i need a [Object file] (Object File Array) to get base64 by using Filereader object . Please help me to get [Object file]. I am using worklight so any other way then let me know
You could read the file - remember you have the full path. The base64 string is going to be kinda huge though.
how should i upload it(Video) to server ? . I can't just save the video path if client delete the video then i won't be able to get the video so either base64 or blob or any other formate you know? please help
Look at the FileTransfer plugin.
I finally got it working on Android but the video doesn't show up after recording. Someone mentioned in a comment about file:// but I'm not sure how to implement the fix mentioned there. Could you please clarify? Thanks.
I got it to play. Must change to this:
v += "<source src="" + s[0].fullPath.replace("file://", "") + "" type="video/mp4">";
Hello do you know if is possible to add text to video recording into ionic 1, thanks.
You mean text into the video itself? For that you would need to manipulate the binary of the video itself - and while it would (maybe) be possible in JS, I'd look at a third party service to do that instead.
Hello Raymond thanks to response, I mean, I want to put a div canvas on the video while it is being recorded, do not put text inside the same video
So.... did you try just putting a div on it? Using absolute positioning?
Yes
Ok. And.....? You need to provide more detail. What you tried, how it worked, or didn't work, etc.
I have worked with the Cordoba camera plugin but I dont have idea how to put div in absolute position and still visible while recording the video
My CSS is pretty basic - I know it's something like
foo {
position:absolute;
top:something;
left:something;
}
Try the Mozilla Developer Network for more information on CSS in general.
Thanks for advice, but when initializing camera I need to keep div
And? What about your work is not keeping the div? Are you saying you made a div, and then used a canvas, and it got rid of the div? Or covered it up?
The problem is when active the camera, I need to keep the text while recording video like subtitles but in a div or canvas
Ah, so since it is using the system video recorder, it takes over the entire screen. You could look at something like WebRTC, but that's not supported in iOS10.
There a major problem with the navigator.device.capture.captureVideo, it doesnt allow to set width and height. As such video size gets to 100 MB for 20 sec. On the other hand using the normal camera the size is 6MB for 20sec.
I'd suggest filing a bug report on the plugin.
Thanks, that helped a lot. I was missing the source tag and tried to add the source with an src attribute to the video.
i am getting black scratched image screen after capture video not playing video why?
Sorry, no idea.