的index.php
在此文件中,我创建网络摄像头并创建按钮记录,保存,停止。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
<meta name="mobile-web-app-capable" content="yes">
<meta id="theme-color" name="theme-color" content="#fff">
<!--<base target="_blank">-->
<title>Access Webcam Device</title>
<link rel="stylesheet" href="today/main.css" />
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<?php
session_start();
$sessData = !empty($_SESSION['sessData'])?$_SESSION['sessData']:'';
if(!empty($sessData['status']['msg'])){
$statusMsg = $sessData['status']['msg'];
$statusMsgType = $sessData['status']['type'];
unset($_SESSION['sessData']['status']);
}
?>
<?php
if(!empty($sessData['userLoggedIn']) && !empty($sessData['userID'])){
include 'user.php';
$user = new User();
$conditions['where'] = array(
'id' => $sessData['userID'],
);
$conditions['return_type'] = 'single';
$userData = $user->getRows($conditions);
?>
<div class="tech">
<header>
<h1>Header</h1>
<div class="log"><span>Welcome <?php echo $userData['first_name']; ?>!</span> <a href="userAccount.php?logoutSubmit=1" class="logout">Logout</a></div>
</header>
<!--<div class="main">-->
<div class="regisFrm">
<!--<p><b>Name: </b><?php //echo $userData['first_name'].' '.$userData['last_name']; ?></p>
<p><b>Email: </b><?php //echo $userData['email']; ?></p>
<p><b>Phone: </b><?php //echo $userData['phone']; ?></p>-->
<div id="container">
<div style = "text-align:center;">
<h1>Webcam Recorder </h1>
<video controls autoplay></video><br>
<button id="rec" onclick="onBtnRecordClicked()">Record</button>
<button id="pauseRes" onclick="onPauseResumeClicked()" disabled>Pause</button>
<button id="stop" onclick="onBtnStopClicked()" disabled>Stop</button>
<button id="saveBtn" >Save</button>
</div>
<a id="downloadLink" download="mediarecorder.webm" name="mediarecorder.webm" href></a>
<p id="data"></p>
<script src="today/main.js"></script>
<script src="today/jQuery2.1.1.min.js"></script>
</div>
</div>
</div>
<?php }else{ ?>
<div class="tech">
<header>
<h1>Header</h1>
</header>
<div class="main">
<div class="panel-heading" style="background: #fff;color: #555;border: 0px;
border-bottom: 1px solid #ccc;">
<h3 class="panel-title" style="margin:10px 0; padding-left:10px;font-weight:bold; font-size: 18px;">
<i style="float:left;padding: 1px 6px 0 0;font-size: 16px;" class="fa fa-sign-in"></i>
Sign in</h3>
</div>
<?php echo !empty($statusMsg)?'<p class="'.$statusMsgType.'">'.$statusMsg.'</p>':''; ?>
<div class="regisFrm">
<form action="userAccount.php" method="post" style="padding:10px 10px;">
<input class="form-control" type="email" name="email" placeholder="EMAIL" required="">
<input class="form-control" type="password" name="password" placeholder="PASSWORD" required="">
<div class="send-button">
<input type="submit" name="loginSubmit" value="LOGIN">
</div>
</form>
<p style="padding-left:10px;">Don't have an account? <a href="registration.php">Register</a></p>
</div>
<?php } ?>
</div>
<footer>Copyright © </footer>
</div>
<script>
function drawOnCanvas(file) {
var reader = new FileReader();
reader.onload = function (e) {
var dataURL = e.target.result,
c = document.querySelector('canvas'), // see Example 4
ctx = c.getContext('2d'),
img = new Image();
img.onload = function() {
c.width = img.width;
c.height = img.height;
ctx.drawImage(img, 0, 0);
};
img.src = dataURL;
};
reader.readAsDataURL(file);
}
</script>
</body>
</html>
main.js 在上面的ajax我正在访问网络摄像头视频数据,并希望将数据存储在数据库中。
'use strict';
/* globals MediaRecorder */
// Spec is at http://dvcs.w3.org/hg/dap/raw-file/tip/media-stream-capture/RecordingProposal.html
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
if(getBrowser() == "Chrome"){
var constraints = {"audio": true, "video": { "mandatory": { "minWidth": 640, "maxWidth": 640, "minHeight": 480,"maxHeight": 480 }, "optional": [] } };//Chrome
}else if(getBrowser() == "Firefox"){
var constraints = {audio: true,video: { width: { min: 640, ideal: 640, max: 640 }, height: { min: 480, ideal: 480, max: 480 }}}; //Firefox
}
var recBtn = document.querySelector('button#rec');
var pauseResBtn = document.querySelector('button#pauseRes');
var stopBtn = document.querySelector('button#stop');
var videoElement = document.querySelector('video');
var dataElement = document.querySelector('#data');
var downloadLink = document.querySelector('a#downloadLink');
videoElement.controls = false;
function errorCallback(error){
console.log('navigator.getUserMedia error: ', error);
}
/*
var mediaSource = new MediaSource();
mediaSource.addEventListener('sourceopen', handleSourceOpen, false);
var sourceBuffer;
*/
var mediaRecorder;
var chunks = [];
var count = 0;
function startRecording(stream) {
log('Start recording...');
if (typeof MediaRecorder.isTypeSupported == 'function'){
/*
MediaRecorder.isTypeSupported is a function announced in https://developers.google.com/web/updates/2016/01/mediarecorder and later introduced in the MediaRecorder API spec http://www.w3.org/TR/mediastream-recording/
*/
if (MediaRecorder.isTypeSupported('video/webm;codecs=vp9')) {
var options = {mimeType: 'video/webm;codecs=vp9'};
} else if (MediaRecorder.isTypeSupported('video/webm;codecs=h264')) {
var options = {mimeType: 'video/webm;codecs=h264'};
} else if (MediaRecorder.isTypeSupported('video/webm;codecs=vp8')) {
var options = {mimeType: 'video/webm;codecs=vp8'};
}
log('Using '+options.mimeType);
mediaRecorder = new MediaRecorder(stream);
}else{
log('Using default codecs for browser');
mediaRecorder = new MediaRecorder(stream);
}
pauseResBtn.textContent = "Pause";
mediaRecorder.start(10);
var url = window.URL || window.webkitURL;
videoElement.src = url ? url.createObjectURL(stream) : stream;
videoElement.play();
mediaRecorder.ondataavailable = function(e) {
//log('Data available...');
//console.log(e.data);
//console.log(e.data.type);
//console.log(e);
chunks.push(e.data);
};
mediaRecorder.onerror = function(e){
log('Error: ' + e);
console.log('Error: ', e);
};
mediaRecorder.onstart = function(){
log('Started & state = ' + mediaRecorder.state);
};
mediaRecorder.onstop = function(){
log('Stopped & state = ' + mediaRecorder.state);
var blob = new Blob(chunks, {type: "video/webm"});
chunks = [];
var videoURL = window.URL.createObjectURL(blob);
downloadLink.href = videoURL;
videoElement.src = videoURL;
downloadLink.innerHTML = 'Download video file';
var rand = Math.floor((Math.random() * 10000000));
var name = "video_"+rand+".webm" ;
downloadLink.setAttribute( "download", name);
downloadLink.setAttribute( "name", name);
loadToServer(blob);
};
function loadToServer(blob){
var data = new FormData();
data.append('file', blob);
debugger;
$.ajax({
url : "recording.php",
type: 'POST',
data:data,
contentType: false,
processData: false,
success: function(data) {
alert("boa!");
},
error: function() {
alert("not so boa!");
}
});
}
mediaRecorder.onpause = function(){
log('Paused & state = ' + mediaRecorder.state);
}
mediaRecorder.onresume = function(){
log('Resumed & state = ' + mediaRecorder.state);
}
mediaRecorder.onwarning = function(e){
log('Warning: ' + e);
};
}
//function handleSourceOpen(event) {
// console.log('MediaSource opened');
// sourceBuffer = mediaSource.addSourceBuffer('video/webm; codecs="vp9"');
// console.log('Source buffer: ', sourceBuffer);
//}
function onBtnRecordClicked (){
if (typeof MediaRecorder === 'undefined' || !navigator.getUserMedia) {
alert('MediaRecorder not supported on your browser, use Firefox 30 or Chrome 49 instead.');
}else {
navigator.getUserMedia(constraints, startRecording, errorCallback);
recBtn.disabled = true;
pauseResBtn.disabled = false;
stopBtn.disabled = false;
}
}
function onBtnStopClicked(){
debugger;
mediaRecorder.stop();
videoElement.controls = true;
recBtn.disabled = false;
pauseResBtn.disabled = true;
stopBtn.disabled = true;
}
function onPauseResumeClicked(){
if(pauseResBtn.textContent === "Pause"){
console.log("pause");
pauseResBtn.textContent = "Resume";
mediaRecorder.pause();
stopBtn.disabled = true;
}else{
console.log("resume");
pauseResBtn.textContent = "Pause";
mediaRecorder.resume();
stopBtn.disabled = false;
}
recBtn.disabled = true;
pauseResBtn.disabled = false;
}
function log(message){
dataElement.innerHTML = dataElement.innerHTML+'<br>'+message ;
}
//browser ID
function getBrowser(){
var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browserName = navigator.appName;
var fullVersion = ''+parseFloat(navigator.appVersion);
var majorVersion = parseInt(navigator.appVersion,10);
var nameOffset,verOffset,ix;
// In Opera, the true version is after "Opera" or after "Version"
if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
browserName = "Opera";
fullVersion = nAgt.substring(verOffset+6);
if ((verOffset=nAgt.indexOf("Version"))!=-1)
fullVersion = nAgt.substring(verOffset+8);
}
// In MSIE, the true version is after "MSIE" in userAgent
else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
browserName = "Microsoft Internet Explorer";
fullVersion = nAgt.substring(verOffset+5);
}
// In Chrome, the true version is after "Chrome"
else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
browserName = "Chrome";
fullVersion = nAgt.substring(verOffset+7);
}
// In Safari, the true version is after "Safari" or after "Version"
else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
browserName = "Safari";
fullVersion = nAgt.substring(verOffset+7);
if ((verOffset=nAgt.indexOf("Version"))!=-1)
fullVersion = nAgt.substring(verOffset+8);
}
// In Firefox, the true version is after "Firefox"
else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
browserName = "Firefox";
fullVersion = nAgt.substring(verOffset+8);
}
// In most other browsers, "name/version" is at the end of userAgent
else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) <
(verOffset=nAgt.lastIndexOf('/')) )
{
browserName = nAgt.substring(nameOffset,verOffset);
fullVersion = nAgt.substring(verOffset+1);
if (browserName.toLowerCase()==browserName.toUpperCase()) {
browserName = navigator.appName;
}
}
// trim the fullVersion string at semicolon/space if present
if ((ix=fullVersion.indexOf(";"))!=-1)
fullVersion=fullVersion.substring(0,ix);
if ((ix=fullVersion.indexOf(" "))!=-1)
fullVersion=fullVersion.substring(0,ix);
majorVersion = parseInt(''+fullVersion,10);
if (isNaN(majorVersion)) {
fullVersion = ''+parseFloat(navigator.appVersion);
majorVersion = parseInt(navigator.appVersion,10);
}
return browserName;
}
recording.php
这是我的recording.php,它用于url中的ajax,这也是一个动作,我试图将数据存储在数据库中代表此页面。
<?php
if(isset($_POST['submit']))
{
$con = mysql_connect('localhost','root','') or die(mysql_error());
$db = mysql_select_db('registered_users',$con) or die(mysql_error());
$sql= "INSERT INTO recording (video_static.webm) VALUES ('".$_POST['file']."')";
//echo $sql;
mysql_query($sql);
header("location: index.php"); //link to redirect page
}
?>