如何在浏览器中录制语音?

时间:2017-02-06 18:36:56

标签: javascript html5 browser asp.net-core webrtc

我在javascript中使用webrtc:

function start() {
    var constraints = {
        audio: true,
        video: true
    };

    navigator.mediaDevices.getUserMedia(constraints)
        .then(function (mediaStream) {
            console.log(window.URL.createObjectURL(mediaStream));

            var video = document.querySelector('#my-video');
            video.src = window.URL.createObjectURL(mediaStream);

            /*video.srcObject = mediaStream;
            video.onloadedmetadata = function (e) {
                video.play();
            };*/
        })
        .catch(function (err) {
            console.log(err.name + ": " + err.message);
        });
}

HTML:

<video id="my-video" autoplay="true" muted="true"></video>
<br />
<input id="start" type="button" value="Start" onclick="start()" />

请告诉我,您需要做些什么来录制声音并将其发送到服务器(Asp .NET Core)?

1 个答案:

答案 0 :(得分:0)

对于需要记录的库RecorderJS。

HTML:

<h4>Recording audio</h4>
<input type="button" onclick="startRecording(this);" value="Record" />
<input type="button" onclick="stopRecording(this);" value="Stop" />

<h4>Record:</h4>
<div class="newRecord"></div>

JS:

window.onload = function () {
    init();
};

var audio_context;
var recorder;

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!');
        console.log(err.name + ": " + err.message);
    }

    queryToUseMicrophone();
};

function queryToUseMicrophone() {
    navigator.mediaDevices.getUserMedia({ audio: true })
        .then(function (mediaStream) {
            var input = audio_context.createMediaStreamSource(mediaStream);
            recorder = new Recorder(input);
        }).catch(function (err) {
            console.log(err.name + ": " + err.message);
        });
}

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;

    createDownloadLink();

    recorder.clear();
}

function createDownloadLink() {
    recorder && recorder.exportWAV(function (blob) {
        var url = URL.createObjectURL(blob);
        var audio = document.createElement('audio');
        var a = document.createElement('a');

        audio.controls = true;
        audio.src = url;
        a.href = url;
        a.download = new Date().toISOString() + '.wav';
        a.innerHTML = a.download;
        document.querySelector(".newRecord").appendChild(audio);
        document.querySelector(".newRecord").appendChild(a);
    });
}