本文概述
WebRTC跨越式发展。仅使用浏览器, 你就可以录制(但不是全部)访问者麦克风的音频。显然, 此过程需要用户的批准, 这意味着此功能对于在线语言评估等系统非常有用。
在本文中, 我们将向你展示如何使用浏览器中的Recorder.js库来记录麦克风所接收的音频。
记录过程如何进行?
要在浏览器中录制音频, 显然需要使用getUserMedia API和AudioContext API访问麦克风, 因此请确保你的浏览器支持这些API。使用Recorder.js, 记录过程非常简单。你需要做的就是请求麦克风, 一旦用户允许访问麦克风, 初始化成功回调中就会收到一个流对象。需要使用AudioContext API实例的createMediaStreamSource方法处理此流。先前的变量应该全局存储, 或者至少在其余功能的范围内可用。
Recorder.js类期望将处理后的流作为第一个参数(即输入)作为第一个参数。使用此Recorder.js实例, 你可以触发开始记录接收到的Audio的record方法, 它将无限期地运行, 直到触发来自同一记录器实例的stop方法为止。同时, 你还需要通过停止先前创建的音频流中的第一个(或所有)音轨实例来停止getUserMedia API
最后一步, 使用记录器实例的exportWAV方法从记录器音频中导出Audio Blob。当使用正确的mimetype指定第二个参数时, exportWAV方法可以以wav和mp3格式导出音频。不要忘记使用记录器的clear方法, 稍后再开始使用新方法。使用生成的Blob, 你可以将其作为音频文件上传到服务器, 使用相同的浏览器或仅在相同的文档中播放。
如何使用Recorder.js录制音频
为了使解释尽可能简单, 我们将只编写一个HTML文档来实现前面描述的所有过程。它由2个按钮组成, 即”开始”和”播放”, 它们触发Recorder.js的记录过程。当用户停止录制时, 它将音频轨道附加到带有可下载音频文件的UL列表中, 例如” 2017-07-14T10:43:28.456Z.wav”:
注意
除了可以从此处的Github官方存储库下载的recorder.js脚本, 你什么也没有。
<!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 export example</h1>
<p>Make sure you are using a recent version of Google Chrome.</p>
<p>Also before you enable microphone input either plug in headphones or turn the volume down if you want to avoid ear splitting
feedback!
</p>
<!-- Draw the action buttons -->
<button id="start-btn">Start recording</button>
<button id="stop-btn" disabled>Stop recording</button>
<!-- List item to store the recording files so they can be played in the browser -->
<h2>Stored Recordings</h2>
<ul id="recordingslist"></ul>
<script>
// Expose globally your audio_context, the recorder instance and audio_stream
var audio_context;
var recorder;
var audio_stream;
/**
* Patch the APIs for every browser that supports them and check
* if getUserMedia is supported on the browser.
*
*/
function Initialize() {
try {
// Monkeypatch for AudioContext, getUserMedia and URL
window.AudioContext = window.AudioContext || window.webkitAudioContext;
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia;
window.URL = window.URL || window.webkitURL;
// Store the instance of AudioContext globally
audio_context = new AudioContext;
console.log('Audio context is ready !');
console.log('navigator.getUserMedia ' + (navigator.getUserMedia ? 'available.' : 'not present!'));
} catch (e) {
alert('No web audio support in this browser!');
}
}
/**
* Starts the recording process by requesting the access to the microphone.
* Then, if granted proceed to initialize the library and store the stream.
*
* It only stops when the method stopRecording is triggered.
*/
function startRecording() {
// Access the Microphone using the navigator.getUserMedia method to obtain a stream
navigator.getUserMedia({ audio: true }, function (stream) {
// Expose the stream to be accessible globally
audio_stream = stream;
// Create the MediaStreamSource for the Recorder library
var input = audio_context.createMediaStreamSource(stream);
console.log('Media stream succesfully created');
// Initialize the Recorder Library
recorder = new Recorder(input);
console.log('Recorder initialised');
// Start recording !
recorder && recorder.record();
console.log('Recording...');
// Disable Record button and enable stop button !
document.getElementById("start-btn").disabled = true;
document.getElementById("stop-btn").disabled = false;
}, function (e) {
console.error('No live audio input: ' + e);
});
}
/**
* Stops the recording process. The method expects a callback as first
* argument (function) executed once the AudioBlob is generated and it
* receives the same Blob as first argument. The second argument is
* optional and specifies the format to export the blob either wav or mp3
*/
function stopRecording(callback, AudioFormat) {
// Stop the recorder instance
recorder && recorder.stop();
console.log('Stopped recording.');
// Stop the getUserMedia Audio Stream !
audio_stream.getAudioTracks()[0].stop();
// Disable Stop button and enable Record button !
document.getElementById("start-btn").disabled = false;
document.getElementById("stop-btn").disabled = true;
// Use the Recorder Library to export the recorder Audio as a .wav file
// The callback providen in the stop recording method receives the blob
if(typeof(callback) == "function"){
/**
* Export the AudioBLOB using the exportWAV method.
* Note that this method exports too with mp3 if
* you provide the second argument of the function
*/
recorder && recorder.exportWAV(function (blob) {
callback(blob);
// create WAV download link using audio data blob
// createDownloadLink();
// Clear the Recorder to start again !
recorder.clear();
}, (AudioFormat || "audio/wav"));
}
}
// Initialize everything once the window loads
window.onload = function(){
// Prepare and check if requirements are filled
Initialize();
// Handle on start recording button
document.getElementById("start-btn").addEventListener("click", function(){
startRecording();
}, false);
// Handle on stop recording button
document.getElementById("stop-btn").addEventListener("click", function(){
// Use wav format
var _AudioFormat = "audio/wav";
// You can use mp3 to using the correct mimetype
//var AudioFormat = "audio/mpeg";
stopRecording(function(AudioBLOB){
// Note:
// Use the AudioBLOB for whatever you need, to download
// directly in the browser, to upload to the server, you name it !
// In this case we are going to add an Audio item to the list so you
// can play every stored Audio
var url = URL.createObjectURL(AudioBLOB);
var li = document.createElement('li');
var au = document.createElement('audio');
var hf = document.createElement('a');
au.controls = true;
au.src = url;
hf.href = url;
// Important:
// Change the format of the file according to the mimetype
// e.g for audio/wav the extension is .wav
// for audio/mpeg (mp3) the extension is .mp3
hf.download = new Date().toISOString() + '.wav';
hf.innerHTML = hf.download;
li.appendChild(au);
li.appendChild(hf);
recordingslist.appendChild(li);
}, _AudioFormat);
}, false);
};
</script>
<!-- Include the recorder.js library from a local copy -->
<script src="recorder.js"></script>
</body>
</html>
如果你不知道如何在浏览器中将Blob下载为文件, 则可以阅读这篇文章, 其中介绍了如何轻松实现它。
编码愉快!