简体   繁体   中英

Javascript: Microphone audio to download link?

I'm trying to record audio from the microphone and then add a download link for it.

This is my current code:

<!DOCTYPE html>
<html>
    <head>
        <title>Weird Problem</title>
        <script>
        function microphone() {
            if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                navigator.mediaDevices.getUserMedia({ audio: true, video: false }).then(function(stream) {
                    var recorder = new MediaRecorder(stream);
                    var chunks = [];
                    recorder.ondataavailable = function(e) {
                        chunks.push(e.data);
                    }
                    recorder.onstop = function() {
                        stream.getTracks()[0].stop();
                        var blob = new Blob(chunks, { type: "audio/ogg; codecs=opus" });
                        var url = window.URL.createObjectURL(blob);
                        document.getElementById("player").src = url;
                        document.getElementById("upload").href = url;
                        document.getElementById("upload").download = "test.ogg";
                    }
                    recorder.start();
                    setTimeout(function() {
                        recorder.stop();
                    }, 5000);
                }).catch(function(error) {
                    console.log(error);
                });
            }
        }
        </script>
    </head>
    <body>
        <input type="button" value="Record Microphone" onclick="microphone();">
        <br>
        <audio controls id="player"></audio>
        <br>
        <a id="upload">Download Microphone Recording</a>
    </body>
</html>

I'm on Chrome, and for me it plays the microphone audio correctly, but when I try to download it, the file won't play or even open.

I get various errors that the file contains data in an unknown format, so I think it's something to do with the audio headers.

Any help would be highly appreciated!

It turns out this issue is a bit more complicated than I expected.

I'm now adapting code from Recorder.js .

The online demo does exactly what I need .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM