通过php将使用Media Recorder录制的音频发送到服务器

时间:2017-03-22 16:23:21

标签: php audio mediarecorder mediarecorder-api

我最近开始研究Media Recorder API,到目前为止,我设法使用此API在浏览器中录制音频,在浏览器中播放该音频并将其下载到我的磁盘上。现在,我想将录制的音频发送到PHP服务器。我怎样才能做到这一点?

到目前为止,这是我的代码:

<!DOCTYPE html>

    <button id="record" disabled> record </button>
</p>
<p>
    <button id="stop" disabled> stop </button>

<p>
    <audio id="audio" controls></audio>
</p>
<p>
    <a id="downloadLink" href></a>
    <script type="text/javascript">
    var recordButton, stopButton, recorder;
    var chunks = [];
    var downloadLink = document.querySelector('a#downloadLink');
    window.onload = function() {

        recordButton = document.getElementById("record");
        stopButton = document.getElementById("stop");



        navigator.mediaDevices.getUserMedia({
                audio: true
            })
            .then(function(stream) {

                recordButton.disabled = false; 
                recordButton.addEventListener('click', startRecording);
                stopButton.addEventListener('click', stopRecording);
                recorder = new MediaRecorder(stream );
                recorder.addEventListener('dataavailable', onRecordingReady);
            });
    };

    function startRecording() {
        chunks = [];
        recordButton.disabled = true;
        stopButton.disabled = false;
        recorder.start();

    }

    function stopRecording() {
        recordButton.disabled = false;
        stopButton.disabled = true;
        recorder.stop();
    }


    function onRecordingReady(e) { 
        chunks.push(e.data)
        var audio = document.getElementById('audio');
        audio.src = window.URL.createObjectURL(e.data);
        var audioURL = audio.src;
        downloadLink.href = audioURL;
        downloadLink.innerHTML = audioURL;
        var rand = Math.floor((Math.random() * 10000000));
        var name = "audio_" + rand + ".wav";

        downloadLink.setAttribute("download", name);
        downloadLink.setAttribute("name", name);
        audio.play();

    }
    </script>

0 个答案:

没有答案