Как записать и экспортировать аудио (WAV и MP3), используя Recorder.js в HTML5

WebRTC продвигается как на дрожжах. Используя только браузер, вы можете записывать, хотя и не во всех, Аудио с микрофона посетителя. Очевидно, что этот процесс требует одобрения пользователя, а это означает, что эта функция может быть действительно полезна для таких систем, как онлайн-оценки языка и т. Д.

В этой статье мы покажем вам, как записать звук, полученный микрофоном, используя Библиотека Recorder.js в браузере.

Как работает процесс записи?

Для записи аудио в браузере вам, очевидно, понадобится доступ к микрофону с помощью API getUserMedia и AudioContext API, поэтому убедитесь, что ваш браузер поддерживает эти API. С Recorder.js процесс записи довольно прост. Все, что вам нужно сделать, это запросить микрофон, как только пользователь разрешит доступ к микрофону, при успешном обратном вызове инициализации будет получен объект потока. Этот поток должен быть обработан с createMediaStreamSource метод из экземпляра AudioContext API. Предыдущие переменные должны храниться глобально или, по крайней мере, быть доступными в области видимости для остальных функций.

Класс Recorder.js ожидает в качестве первого аргумента обработанный поток в качестве первого аргумента, а именно ввода. С помощью этого экземпляра Recorder.js вы можете запустить метод записи, который начинает запись полученного аудио, и он будет работать бесконечно, пока не будет запущен метод stop из того же экземпляра устройства записи. В то же время вам нужно будет также остановить API getUserMedia, остановив первый (или все) экземпляры звуковой дорожки из ранее созданного аудиопотока.

Как последний шаг, экспортируйте Audio Blob из аудио устройства записи, используя метод exportWAV экземпляра устройства записи. Метод exportWAV может экспортировать аудио в формате wav и mp3, если второй параметр указан с правильным mimetype. Не забудьте использовать чистый метод записи, чтобы позже начать с нового. С помощью созданного BLOB-объекта вы сможете загрузить его в виде аудиофайла на сервер, в том же браузере или просто воспроизвести в том же документе.

Как записать аудио с помощью Recorder.js

Чтобы сделать объяснение настолько простым, насколько это возможно, мы просто напишем документ HTML, который реализует весь ранее описанный процесс. Он состоит из 2 кнопок, а именно «Пуск» и «Воспроизведение», которые запускают процесс записи с помощью Recorder.js. Когда пользователь останавливает запись, он добавляет аудиодорожку в список UL с загружаемым аудиофайлом со знаком «2017-07-14T10:43:28.456Z.wav«:

Заметка

Вы ничего не будете, кроме recorder.js скрипт, который можно скачать с официальный репозиторий на Github здесь.


Live input record and playback
ul {
list-style: none;
}
#recordingslist audio {
display: block;
margin-bottom: 10px;
}
Recorder.js export example

Make sure you are using a recent version of Google Chrome.

Also before you enable microphone input either plug in headphones or turn the volume down if you want to avoid ear splitting feedback!

Start recording Stop recording

Stored Recordings

    // 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); };
    Ссылка на основную публикацию
    Adblock
    detector