有没有人用MediaRecorder在pc上录制视频并上传到服务器。

新手上路,请多包涵

浏览器调用摄像头和录制视频我这里已经实现但是,如何用MediaRecorder

阅读 9.1k
1 个回答
新手上路,请多包涵

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml&...
<head runat="server">

<title></title>  
<meta charset="utf-8">

</head>

<body>  
<video width="640" height="480" id="myVideo"></video>
<input type="button" name="" value="开始" id="startBtn">
<input type="button" name="" value="停止" id="stopBtn">
<input type="button" name="" value="重新开始录像" id="ppBtn">
<script src="https://cdn.webrtc-experiment.com/MediaStreamRecorder.js"> </script>
<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
    //  判断浏览器
    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;        
    var constraints = { audio: true, video: { width: 1280, height: 720 } }; 

    var aa = '' ; //防止两次上传
    //  调用摄像头  成功后获取视频流:mediaStream
    navigator.mediaDevices.getUserMedia(constraints)
    .then(function(mediaStream) {
      var video = document.querySelector('video');
      //  赋值 video 并开始播放
      video.srcObject = mediaStream;
      video.onloadedmetadata = function(e) {
        video.play();
      };
        //  录像api的调用
        var mediaRecorder = new MediaStreamRecorder(mediaStream);
            mediaRecorder.mimeType = 'video/webm';

        //  停止录像以后的回调函数
        mediaRecorder.ondataavailable = function (blob) {
            // POST/PUT "Blob" using FormData/XHR2
            // var blobURL = URL.createObjectURL(blob);
            // console.log(blob);
            // document.write('<a href="' + blobURL + '">' + blobURL + '</a>');
            //  停止以后调用上传
            if(aa == ""){uploadToPHPServer(blob);aa = blob}
        };
        

        $("#startBtn").click(function(){
          //  开始录像
          mediaRecorder.start();
        })

        $("#stopBtn").click(function(){
          //  停止录像
          mediaRecorder.stop();
        })

        $("#ppBtn").click(function(){
          if(aa !== ""){aa = "";mediaRecorder.start();}
        })
        // 上传
        function uploadToPHPServer(blob) {
          var file = new File([blob], 'msr-' + (new Date).toISOString().replace(/:|\./g, '-') + '.webm', {
              type: 'video/webm'
          });

          // create FormData
          var formData = new FormData();
          formData.append('video-filename', file.name);
          formData.append('video-blob', file);
          console.log(formData);
          makeXMLHttpRequest('https:/你的地址/data/save.php', formData, function() {
              var downloadURL = 'https://你的地址' + file.name;
              console.log('File uploaded to this path:', downloadURL);
          });
      }

      function makeXMLHttpRequest(url, data, callback) {
          var request = new XMLHttpRequest();
          request.onreadystatechange = function() {
              if (request.readyState == 4 && request.status == 200) {
                  callback();
              }
          };
          request.open('POST', url);
          request.send(data);
      }

      //  上传结束
    })
    .catch(function(err) { console.log(err.name + ": " + err.message); });
</script>

</body>
</html>

php文件
<?php
// via: https://github.com/muaz-khan/...
header("Access-Control-Allow-Origin: *");
function selfInvoker()
{

if (!isset($_POST['audio-filename']) && !isset($_POST['video-filename'])) {
    echo 'PermissionDeniedError';
    return;
}

$fileName = '';
$tempName = '';

if (isset($_POST['audio-filename'])) {
    $fileName = $_POST['audio-filename'];
    $tempName = $_FILES['audio-blob']['tmp_name'];
} else {
    $fileName = $_POST['video-filename'];
    $tempName = $_FILES['video-blob']['tmp_name'];
}

if (empty($fileName) || empty($tempName)) {
    echo 'PermissionDeniedError';
    return;
}
$filePath = 'uploads/' . $fileName;

// make sure that one can upload only allowed audio/video files
$allowed = array(
    'webm',
    'wav',
    'mp4',
    'mp3',
    'ogg'
);
$extension = pathinfo($filePath, PATHINFO_EXTENSION);
if (!$extension || empty($extension) || !in_array($extension, $allowed)) {
    echo 'PermissionDeniedError';
    continue;
}

if (!move_uploaded_file($tempName, $filePath)) {
    echo ('Problem saving file.');
    return;
}

echo ($filePath);

}
selfInvoker();
?>

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏