javascripttypescriptweb-mediarecorder

JavaScript Recorded audio has unknown duration


okay so I successfully created a structure to record and download audio. But the problem is the final downloaded file has unknown duration. is there any way to work around that?? Here is my code (it's in Typescript)

let recorder: MediaRecorder,
dataArray: Blob[]

async function InitializeAudio(): Promise<void> {
    let audioIN = { audio: true }
    try {
        const mediastremObj = await navigator.mediaDevices.getUserMedia(audioIN)
        const mediaRecorder = new MediaRecorder(mediastremObj)
        recorder = mediaRecorder
        recorder.ondataavailable = (ev)=>{
            dataArray.push(ev.data)
        }
        recorder.onstop = (ev) => {
            const downloadTag = document.querySelector('#file-download') as HTMLAnchorElement
            const audioFile = new Blob(dataArray, {'type': 'audio/mp3;'})
            const url = window.URL.createObjectURL(audioFile)
            downloadTag.href = url
            downloadTag.download = `my-${Date.now()}-audio.mp3`
            downloadTag.click()
            window.URL.revokeObjectURL(url)
            dataArray = []
        }
    } catch (e) {
        throw new Error(e)
    }
}

Solution

  • okay so after weeks of searching and researching, i found out that the media recorder API can only record in mime types supported by the browser. in chrome browser the only supported mime type is audio/webm, and the generated Blob can't be converted to any other mimetype. i was able to find a lasting solution using wavesufer & lamejs libraries.

    link to them πŸ‘‡πŸ‘‡

    https://www.npmjs.com/package/wavesurfer.js?activeTab=readme

    https://www.npmjs.com/package/lamejs

    you might have an error using the lame js library, so here is a link to a refactored fork of the lame js projectπŸ‘‡πŸ‘‡

    https://www.npmjs.com/package/lamejstmp