Record Audio, Video, Image and GIF from Browser using videojs-record
This blog explain with HTML and JavaScript. Video.js plugin for recording audio/video/image files.
It can record audio, video and both, take picture from webcam and generate gif also.
Recording…..
- Audio
- Video
- Audio and Video
- image
- GIF
Audio/video/image
When recording either audio/video, video-only, animated GIF or a single image, include a video
element:
<video id="myVideo" class="video-js vjs-default-skin"></video>
Usage
Start by including the video.js stylesheet and library:
<link href="video-js.min.css" rel="stylesheet">
<script src="video.min.js"></script>
If you’re going to record audio and/or video you need to include RecordRTC as well:
<script src="RecordRTC.js"></script>
The videojs-record plugin automatically registers itself when the script is included on the page:
<script src="videojs.record.js"></script>
Add the extra stylesheet for the plugin that includes a custom font with additional icons:
<link href="videojs.record.css" rel="stylesheet">
Options
Configure the player using the video.js options, and enable the plugin by adding a record
configuration to plugins
. For example:
var player = videojs('myVideo', {
// video.js options
controls: true,
loop: false,
fluid: false,
width: 320,
height: 240,
plugins: {
// videojs-record plugin options
record: {
image: false,
audio: false,
video: true,
maxLength: 5,
debug: true
}
}
});
The available options for this plugin are:
https://www.npmjs.com/package/videojs-record#options
Methods
Methods for this plugin documented below are available using the record
method of the video.js player instance. For example:
player.record().destroy();
The available methods for this plugin are:
https://www.npmjs.com/package/videojs-record#methods
Events
Plugin events that are available on the video.js player instance. For example:
player.on('startRecord', function() {console.log('started recording!');});
The available event for this plugin are:
https://www.npmjs.com/package/videojs-record#events
Show the recorded data
Listen for the finishRecord
event and obtain the recorded data from theplayer.recordedData
object for further processing:
player.on('finishRecord', function() {console.log('finished recording: ', player.recordedData);});
Save data
Use the saveAs
method to show a 'Save as' browser dialog where the user can choose the storage location for the recorded data. It accepts a name
object that contains a mapping between the media type and the filename. For example:
player.on('finishRecord', function() {player.record().saveAs({'video': 'my-video-file-name.webm'});});
Show the streaming blob(audio/video):
Enable the event with the timeSlice
option. This json streaming video blob. So set the video to true.
record: {
audio:false,
video:true,
maxLength:5,
debug:true,
// fire the timestamp event every 2 seconds
timeSlice: 2000}player.on('timestamp', function() {if (player.recordedData && player.recordedData.length > 0) {var streamData = player.recordedData[player.recordedData.length - 1];console.log(streamData);});
To upload the blob(audio/video) to server(PHP):
upload-video.php
<?php
if(isset($_FILES["audiovideo"])){ // save audio and video
$fileName = "myaudiovideo.webm";
$uploadDirectory = './'. $fileName;
if (!move_uploaded_file($_FILES["audiovideo"]["tmp_name"], $uploadDirectory)) {
echo("Couldn't upload video !");
}
else{
echo("File Moved");
}
}
elseif(isset($_FILES["audio"])){ // save audio only
$fileName = "myaudio.webm";
$uploadDirectory = './'. $fileName;
if (!move_uploaded_file($_FILES["audio"]["tmp_name"], $uploadDirectory)) {
echo("Couldn't upload video !");
}
else{
echo("File Moved");
}
}
elseif(isset($_FILES["video"])){ // save video only
$fileName = "myvideo.webm";
$uploadDirectory = './'. $fileName;
if (!move_uploaded_file($_FILES["video"]["tmp_name"], $uploadDirectory)) {
echo("Couldn't upload video !");
}
else{
echo("File Moved");
}
}
elseif(isset($_FILES["stream"])){ // save streamming
$fileName = $_POST["name"];
$uploadDirectory = './'. $fileName;
if (!move_uploaded_file($_FILES["stream"]["tmp_name"], $uploadDirectory)) {
echo("Couldn't upload video !");
}
else{
echo("Success");
}
}
else{
echo "No file uploaded";
}
?>
To upload the blob(audio/video) to server(Python Flask):
from flask import Flask, request
from flask_cors import CORS
from werkzeug.utils import secure_filename
import osUPLOAD_FOLDER = '../upload_files'app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
CORS(app)@app.route('/audio',methods=['POST'])
def audio():
if request.method == 'POST':
file = request.files['audio']
filename = "myaudio.webm"
filename = secure_filename(filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return "success"@app.route('/video',methods=['POST'])
def video():
if request.method == 'POST':
file = request.files['video']
filename = "myvideo.webm"
filename = secure_filename(filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return "success"@app.route('/audiovideo',methods=['POST'])
def audiovideo():
if request.method == 'POST':
file = request.files['audiovideo']
filename = "myaudiovideo.webm"
filename = secure_filename(filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return "success"@app.route('/stream',methods=['POST'])
def stream():
if request.method == 'POST':
file = request.files['stream']
filename = request.form['name']
filename = secure_filename(filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return "success"if __name__ == "__main__":
app.run(host="0.0.0.0",debug=True)
SERVER URLS:
PHP URL: servers/upload-video.php
Python Flask URL:
Audio: http://0.0.0.0:5000/audio
Video: http://0.0.0.0:5000/video
Audio-Video: http://0.0.0.0:5000/audiovideo
Stream: http://0.0.0.0:5000/stream
Save Audio Only:
player.on('finishRecord', function() {
// the blob object contains the recorded data that
// can be downloaded by the user, stored on server etc.
console.log('finished recording: ', player.recordedData);var formData = new FormData();
formData.append('audio', player.recordedData);
// Execute the ajax request, in this case we have a very simple PHP script
// that accepts and save the uploaded "video" file
xhr('servers/upload-video.php', formData, function (fName) {
console.log("Video succesfully uploaded !",fName);
});// Helper function to send
function xhr(url, data, callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
callback(location.href + request.responseText);
}
};
request.open('POST', url);
request.send(data);
}});
Save Video Only:
player.on('finishRecord', function() {
// the blob object contains the recorded data that
// can be downloaded by the user, stored on server etc.
console.log('finished recording: ', player.recordedData);var formData = new FormData();
formData.append('video', player.recordedData);
// Execute the ajax request, in this case we have a very simple PHP script
// that accepts and save the uploaded "video" file
xhr('servers/upload-video.php', formData, function (fName) {
console.log("Video succesfully uploaded !",fName);
});// Helper function to send
function xhr(url, data, callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
callback(location.href + request.responseText);
}
};
request.open('POST', url);
request.send(data);
}
});
Save Audio-Video Only:
player.on('finishRecord', function() {
// the blob object contains the recorded data that
// can be downloaded by the user, stored on server etc.
console.log('finished recording: ', player.recordedData);var formData = new FormData();
formData.append('audiovideo', player.recordedData.video);
// Execute the ajax request, in this case we have a very simple PHP script
// that accepts and save the uploaded "video" file
xhr('servers/upload-video.php', formData, function (fName) {
console.log("Video succesfully uploaded !");
});// Helper function to send
function xhr(url, data, callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
callback(location.href + request.responseText);
}
};
request.open('POST', url);
request.send(data);
}
});
Save Streamming blob Only:
timestamp is event name for getting stream data
player.on('timestamp', function() {
// timestamps
// console.log('current timestamp: ', player.currentTimestamp);
// console.log('all timestamps: ', player.allTimestamps);
// stream data
data = player.recordedData;
console.log('array of blobs: ', player.recordedData);if (player.recordedData && player.recordedData.length > 0) {
var binaryData = player.recordedData[player.recordedData.length - 1];
segmentNumber++;
var formData = new FormData();
formData.append('name', binaryData['name']);
formData.append('stream', binaryData);xhr('servers/upload-video.php', formData, function (fName) {
console.log("Video succesfully uploaded !",fName);
});// Helper function to send
function xhr(url, data, callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
callback(location.href + request.responseText);
}
};
request.open('POST', url);
request.send(data);
}
}
});
Examples
The full source code available on GitHub and click here to show.