본문 바로가기

잡단한것들/코딩연습장

웹브라우저에서 녹음을 해보자 MediaDevices.getUserMedia() Int16Array blob

int16Array blob객체 활용하기

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
</head>
<body>
    <button class="record">record</button>
    <button class="stop">stop</button>
    <script>
        const record = document.querySelector(".record");
        const stop = document.querySelector(".stop");
        if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
            console.log("getUserMedia supported.");
            navigator.mediaDevices.getUserMedia(
                // constraints - only audio needed for this app
                {
                    audio: true,
                }
            ).then(function (stream) {
                //Success CallBack
                const mediaRecorder = new MediaRecorder(stream);
                record.onclick = function () {
                    mediaRecorder.start(1000);
                    console.log(mediaRecorder.state);
                    console.log("recorder started");
                    record.style.background = "red";
                    record.style.color = "black";
                    let chunks = [];
                    mediaRecorder.ondataavailable = async function (e) {
                        // var text = await new Response(e.data).text();
                        // console.log(text);
                        // e.data.arrayBuffer().then((resutl) => {
                        //     console.log(resutl);
                        // });
                        console.log(e.data.type, 'tpye::');
                        const fr = new FileReader();
                        fr.onload = () => {
                            // It worked
                            const Data = new Int16Array(fr.result, 02);
                            console.log(Data);
                            // ...use the array here...
                        };
                        fr.onerror = () => {
                            // The read failed, handle/report it
                        };
                        fr.readAsArrayBuffer(e.data);
                        // const data = new Int16Array(fr.result);
                        // console.log(data);
                        chunks.push(e.data);
                        // console.log(chunks);
                    };
                };
                stop.onclick = function () {
                    if (mediaRecorder.state = 'recording') {
                        mediaRecorder.stop();
                        record.style.background = "";
                        record.style.color = "";
                        console.log('stopped recording')
                    }
                }
            }).catch(function (err) {
                //Error CallBack
                console.log(
                    "The following getUserMedia error occurred: " + err
                );
            });
        } else {
            console.log("getUserMedia not supported on your browser!");
        }
    </script>
</body>
</html>

참고한 자료

MediaDevices.getUserMedia()

https://developer.mozilla.org/ko/docs/Web/API/MediaDevices/getUserMedia

 

MediaDevices.getUserMedia() - Web API | MDN

MediaDevices 인터페이스의 getUserMedia() 메서드는 사용자에게 미디어 입력 장치 사용 권한을 요청하며, 사용자가 수락하면 요청한 미디어 종류의 트랙을 포함한 MediaStream (en-US)을 반환합니다.

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder/stop

 

MediaRecorder.stop() - Web APIs | MDN

The MediaRecorder.stop() method (part of the MediaRecorder API) is used to stop media capture.

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/API/FileReader/loadend_event

 

FileReader: loadend event - Web APIs | MDN

The loadend event is fired when a file read has completed, successfully or not.

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsArrayBuffer

 

FileReader.readAsArrayBuffer() - Web APIs | MDN

The FileReader interface's readAsArrayBuffer() method is used to start reading the contents of a specified Blob or File. When the read operation is finished, the readyState becomes DONE, and the loadend is triggered. At that time, the result attribute cont

developer.mozilla.org

https://developer.mozilla.org/ko/docs/Web/API/MediaDevices

 

MediaDevices - Web API | MDN

MediaDevices 인터페이스는 카메라, 마이크, 공유 화면 등 현재 연결된 미디어 입력 장치로의 접근 방법을 제공하는 인터페이스입니다. 다르게 말하자면, 미디어 데이터를 제공하는 모든 하드웨어

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/API/MediaStream_Recording_API

 

MediaStream Recording API - Web APIs | MDN

The MediaStream Recording API, sometimes referred to as the Media Recording API or the MediaRecorder API, is closely affiliated with the Media Capture and Streams API and the WebRTC API. The MediaStream Recording API makes it possible to capture the data g

developer.mozilla.org

 

int16Array관련

https://www.javascripture.com/DataView

 

DataView JavaScript API

Converts value to a 32 bit floating point number and stores it into this at the specified offset. If littleEndian is true, the value will be stored as little endian (least significant byte is at byteOffset and most significant at byteOffset + 3). Example:

www.javascripture.com

https://www.javascripture.com/Uint16Array

 

Uint16Array JavaScript API

Returns a new Uint16Array which is composed of the items this[start], this[start + 1], ..., this[end - 1]. Note that item[end] is not included. If start or end is negative, the value is added to this.length before performing the slice. If end is not specif

www.javascripture.com

 

https://stackoverflow.com/questions/37394541/how-to-convert-blob-to-int16array

 

How to convert Blob to Int16Array

I have a WAV file in Blob and in order to convert it to MP3 I need to convert it to Int16Array first (to follow the example from here: https://github.com/zhuker/lamejs). E.g. var mp3encoder = new

stackoverflow.com

https://jeongah-story.tistory.com/179

 

[Javascript] API 활용 - Blob

[모던자바스크립트] 19.2 blob : Blob을 활용하면 자바스크립트로 이미지, 음성,영상 등의 이진 데이터를 다룰 수 있습니다. 또한 Blob을 상속받는 file 객체로 로컬 파일을 다룰 수 있게 됩니다. : Blob

jeongah-story.tistory.com

 

추가로 좋은 예제 발견

https://codepen.io/robert_bakiev/pen/VpoLYo

 

Recorder

Simple audiorecorder...

codepen.io

 

다운로드 구현시

https://developer.mozilla.org/en-US/docs/Web/API/MediaStream_Recording_API

 

MediaStream Recording API - Web APIs | MDN

The MediaStream Recording API, sometimes referred to as the Media Recording API or the MediaRecorder API, is closely affiliated with the Media Capture and Streams API and the WebRTC API. The MediaStream Recording API makes it possible to capture the data g

developer.mozilla.org