I have tried but there is an error "TypeError: Cannot read properties of undefined (reading 'stop')" I am calling function on button click here is function as well :)
const getAudio= async ()=>{
let device = await navigator.mediaDevices.getUserMedia({audio: true});
let chunks = [];
let recorder;
device.then(stream => {
recorder = new MediaRecorder(stream);
recorder.ondataavailable = e => {
chunks.push(e.data);
if (recorder.state === 'inactive') {
this.blob = new Blob(chunks, {type: 'audio/webm'});
let testAudioRecord = URL.createObjectURL(this.blob);
console.log(testAudioRecord)
}
}
recorder.start(1000);
});
setTimeout(() => {
recorder.stop(); // Cannot read ('stop') =error
}, 2000)
}
I spot a bit of a mixup between using async with await, and the .then promise handling.
Since you are using an async function, lets refactor to try...catch with await to wait for the promoise to resolve.
const getAudio = async () => {
let chunks = [];
let recorder;
try {
//wait for the stream promise to resolve
let stream = await navigator.mediaDevices.getUserMedia({ audio: true });
recorder = new MediaRecorder(stream);
recorder.ondataavailable = (e) => {
chunks.push(e.data);
if (recorder.state === "inactive") {
this.blob = new Blob(chunks, { type: "audio/webm" });
let testAudioRecord = URL.createObjectURL(this.blob);
console.log(testAudioRecord);
}
};
recorder.start(1000);
setTimeout(() => {
recorder.stop();
}, 2000);
} catch (e) {
console.log("error getting stream", e);
}
};
There are better ways to construct the code, but this should get your function working.
Here is a codesandbox with your function and a playback option
Here is another audio codesandbox