Reputation: 377
I'm currently working on a project that in one part, we should record a video from users front camera or webcam, and then send the recorded video to backend for user verifying. This is how I record the video:
const startRecording = () => {
setShouldShowPreRecordingTimer(false);
if (videoRef.current) {
const stream = videoRef.current.srcObject as MediaStream;
const recorder = new MediaRecorder(stream, {
mimeType: returnVideoMimeType(),
videoBitsPerSecond: 250000,
});
recorder.ondataavailable = handleDataAvailable;
recorder.start();
setMediaRecorder(recorder);
}
};
const startRecording = () => {
setShouldShowPreRecordingTimer(false);
if (videoRef.current) {
const stream = videoRef.current.srcObject as MediaStream;
const recorder = new MediaRecorder(stream, {
mimeType: returnVideoMimeType(),
videoBitsPerSecond: 250000,
});
recorder.ondataavailable = handleDataAvailable;
recorder.start();
setMediaRecorder(recorder);
setIsRecording(true);
setRecordingTimer(RECORDING_TIME);
}
};
const stopRecording = () => {
if (mediaRecorder) mediaRecorder.stop();
};
const handleDataAvailable = (event: BlobEvent) => {
if (event.data.size > 0) {
setRecordedChunks((prev) => [...prev, event.data]);
}
};
and to ensure that the mime type is supported by the browser, I wrote this function:
export const returnVideoMimeType = () => {
const mimeTypes = [
'video/mp4;codecs=avc1.42E01E,mp4a.40.2',
'video/webm;codecs=vp9,opus',
'video/webm;codecs=vp8,opus',
'video/webm',
'',
];
if (MediaRecorder.isTypeSupported) {
return (
mimeTypes.find((mimeType) => MediaRecorder.isTypeSupported(mimeType)) ||
''
);
}
return 'video/mp4;codecs=avc1.42E01E,mp4a.40.2';
};
and this is the formats that are supported for the backend endpoint:
png,jpeg,bmp,mpeg,webm,3gp,avi,ogg,mp4,mov,wmv,gif,doc,zip,rar,pdf,docx
Now when I try to test this in Chrome or firefox or edge, It's working correctly and uploading the video. But whenever I try to upload in on a mac or an Iphone I get the error that the format of the file is not supported, I've checked the mime type returned in safari and it's
'video/mp4;codecs=avc1.42E01E,mp4a.40.2'
I've tried uploading it in chrome with the same mime type and it worked correctly. In Safari, the recording works correctly without an issue, the preview of recorded video works fine too, but for some reason it seems like it's changing the final mime type to something else. I also use this video constraints when starting the camera incase they have any issue:
const videoConstraints = {
video: {
width: { max: 960 }, // Reduce resolution to 640px width
height: { max: 1280 },
frameRate: { max: 30 }, // Lower frame rate reduces file size
facingMode: 'user',
},
audio: true,
};
Any ideas why upload in safari is not working correctly?
Upvotes: 0
Views: 25