I have created a React component with a microphone button that:
OnMouseDown
=> User begins recording audioOnMouseUp
=> Audio recording endsIn other words, as long as the button is held down, the user can continue recording (similar to WhatsApp / other apps voice-message feature).
My issue is, on the first time the page appears on a user's desktop, the moment they click the button to record, Chrome pops up a dialog asking the user permission to access the microphone.
The problem with that is that, in order to click "ok" on the dialog, the user has to Mouse-up on the button which is causing an error due to the recording element not having been created yet.
Is there a way to make it such that OnMouseDown
=>
From the research I've done, it seems I need to do something along the lines of:
const onMouseDown = async () => {
await navigator.mediaDevices.getUserMedia({ audio: true });
// rest of code
};
But it seems that that actually starts a recorder (and there won't be any corresponding MouseUp
event to end it) and all I want to do with this portion of the code is:
In case someone gets caught up with the same issue, what I ended up having to do was create a global variable checking if microphone permissions were granted (I did this via Redux). Then, when the component first mounts, I run an action that:
export const checkMicrophonePermissions = () => async dispatch => {
let retval = false;
await navigator.mediaDevices.getUserMedia({ audio: true })
.then(stream => retval = true)
.catch(err => retval = false);
dispatch({
type: MICROPHONE_ACCESS,
payload: retval
});
}
Basically, it will run as the page loads the first time and pop-up a dialog asking the user to permit microphone access and sets the global variable relating to MICROPHONE_ACCESS
to true
/ false
based upon the user's reply.