通过web audio api录音并上传到服务器

作者: 白云飞 分类: javascript,php 发布时间: 2017-07-13 14:55 阅读:

之前通过 webRTC 做过web端的录音测试,发现兼容性不是很好。还会出现录音遗漏的问题。今天,又需要在web端录音,于是找了一个很好的接口来丛这个。

html部分

<!DOCTYPE html>

<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>Live input record and playback</title>
  <style type='text/css'>
    ul { list-style: none; }
    #recordingslist audio { display: block; margin-bottom: 10px; }
  </style>
</head>
<body>

  <h1>Recorder.js simple WAV</h1>
  <button onclick="startRecording(this);">record</button>
  <button onclick="stopRecording(this);" disabled>stop</button>
  <div id="audio"></div>
  <script>
  function __log(e, data) {
    log.innerHTML += "\n" + e + " " + (data || '');
  }

  var audio_context;
  var recorder;

  function startUserMedia(stream) {
    var input = audio_context.createMediaStreamSource(stream);
    recorder = new Recorder(input);
  }

  function startRecording(button) {
    recorder && recorder.record();
    button.disabled = true;
    button.nextElementSibling.disabled = false;
  }

  function stopRecording(button) {
    recorder && recorder.stop();
    button.disabled = true;
    button.previousElementSibling.disabled = false;

    // create WAV download link using audio data blob
    //createDownloadLink();
	uploadToServer();
    
    recorder.clear();
  }
  
  function uploadToServer(){
	recorder && recorder.exportWAV(function(blob) {
		
		var fileType = 'wav';
		var fileName =  new Date().valueOf() + '.' + fileType;
		var url = './upload.php';
		
		// create FormData
		var formData = new FormData();
		formData.append('name', fileName);
		formData.append('file', blob);
		
		var request = new XMLHttpRequest();
		// upload success callback
		request.onreadystatechange = function() {
			if (request.readyState == 4 && request.status == 200) {
				console.log(request.response);
				var reObj = eval('(' + request.response + ')');
				
				var au = document.createElement('audio');
				au.controls = true;
				au.src = reObj.data;
				
				var audioDOM = document.getElementById('audio');
				audioDOM.appendChild(au);
				
			}
		};
		// upload start callback
		request.upload.onloadstart = function() {
			console.log('Upload started...');
		};
		// upload process callback
		request.upload.onprogress = function(event) {
			console.log('Upload Progress ' + Math.round(event.loaded / event.total * 100) + "%");
		};
		// upload error callback
		request.upload.onerror = function(error) {
			console.error('XMLHttpRequest failed', error);
		};
		// upload abort callback
		request.upload.onabort = function(error) {
			console.error('XMLHttpRequest aborted', error);
		};

		request.open('POST', url);
		request.send(formData);
	});
  }

  /*function createDownloadLink() {
    recorder && recorder.exportWAV(function(blob) {
      var url = URL.createObjectURL(blob);
	  console.log(url);
	  
      var li = document.createElement('li');
      var au = document.createElement('audio');
      var hf = document.createElement('a');
      
      au.controls = true;
      au.src = url;
      hf.href = url;
      hf.download = new Date().toISOString() + '.wav';
      hf.innerHTML = hf.download;
      li.appendChild(au);
      li.appendChild(hf);
      recordingslist.appendChild(li);
    });
  }*/

  window.onload = function init() {
    try {
      // webkit shim
      window.AudioContext = window.AudioContext || window.webkitAudioContext;
      navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia;
      window.URL = window.URL || window.webkitURL;
      
      audio_context = new AudioContext;
    } catch (e) {
      alert('No web audio support in this browser!');
    }
    
    navigator.getUserMedia({audio: true}, startUserMedia, function(e) {
      console.log('No live audio input: ' + e);
    });
  };
  </script>

  <script src="../dist/recorder.js"></script>
</body>
</html>

php部分

<?php

if ($_FILES["file"]["error"] > 0){
	echo json_encode(['code' => -1, 'data' => '', 'msg' => $_FILES["file"]["error"]]);
	exit;
}

$name = (string)$_POST['name'];

if(!move_uploaded_file($_FILES["file"]["tmp_name"], "./" . $name)){
	echo json_encode(['code' => -2, 'data' => '', 'msg' => '保存失败']);
	exit;
}

echo json_encode(['code' => 1, 'data' => 'http://localhost/test/Recorderjs/examples/' + $name . ".wav", 'msg' => '上传成功']);

 

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

发表评论

电子邮件地址不会被公开。