gpt4 book ai didi

reactjs - 如何在用 reactjs 构建的 PWA 应用程序中切换相机?

转载 作者:行者123 更新时间:2023-12-04 11:33:20 25 4
gpt4 key购买 nike

我有一个记录或上传视频的代码。该应用程序是使用 create-react-app 构建的,并且是一个 PWA。
我已经使用了 facesMode 约束,但它仍然无法在手机(Samung fold 2)上切换相机,即使在摩托罗拉手机中也没有相同的影响。
这是代码:

import React, { useState, useEffect, useRef } from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';

import config from '../../config';


const MediaRecorderCapture = props => {
const [mediaRecorder, setMediaRecorder] = useState({});
const [isRecording, setIsRecording] = useState(false);
const [showRear, setShowRear] = useState(false);
const recorderRef = useRef();
const playerRef = useRef();

/**
* Initialize the MediaRecorder on component mount
*/
useEffect(() => {
console.log("reinitializing..")
initializeMediaRecorder();
}, [showRear])

/**
* Upon MedaRecorder being set, monitor the following events
*/
useEffect(() => {
let chunks = [];

mediaRecorder.ondataavailable = e => chunks.push(e.data)

mediaRecorder.onstop = e => {
let blob = new Blob(chunks, { type: 'video/mp4' });
chunks = [];

let url = (window.URL || window.webkitURL).createObjectURL(blob);
handleVideoRecorder(blob);
// uploadVideo(blob);
// setPlaybackPreview(url);
// createDownloadLink(url);
}

mediaRecorder.onerror = e => {
console.log('Error recording stream');
console.log(e.error);
}

console.log('MediaRecorder ready');
}, [mediaRecorder]);



// const createDownloadLink = url => {
// const link = <a href={url} download="Recording.mp4">Download</a>;
// const linkContainer = document.getElementById('download-link');
// ReactDOM.render(link, linkContainer);
// }

/**
* Helper function to console out change in state of the MediaRecorder
*/
useEffect(() => {
console.log(`MediaRecorder state: ${mediaRecorder.state}`)
}, [mediaRecorder.state])

/**
* Start recording the stream
*/
const start = async () => {
if (mediaRecorder.state === 'recording') return;
mediaRecorder.start();
setIsRecording(true);
}

/**
* Stop recording the stream
*/
const stop = async () => {
if (mediaRecorder.state === 'inactive') return;
mediaRecorder.stop();
setIsRecording(false);
await initializeMediaRecorder();
}

/**
* Set the playback player's source to the url of the newly recorderd stream
* @param {string} url
*/
const setPlaybackPreview = url => {
if (!playerRef.current) return;
console.log(`Playback URL: ${url}`);
playerRef.current.src = url;
}

/**
* Get a media device stream (webcam)
*/
const getStream = () => {
return new Promise(async (resolve, reject) => {
try {
const stream = await navigator.mediaDevices.getUserMedia({
audio: true,
video: {
facingMode: showRear ? 'environment' : 'user'
}
});
console.log('Stream fetched and rear camera? ', showRear);
resolve(stream);
}
catch (err) {
console.log('Error in fetching stream')
reject(err);
}
})
}

/**
* Set the live stream retrieved from the media device
* to the designated player to preview
* @param {object} stream
*/
const setRecordingStreamPreview = stream => {
if (!recorderRef.current) return;
recorderRef.current.srcObject = stream;
console.log("recordref ", recorderRef.current.srcObject)

}

/**
* Create MediaRecorder object from a given stream
* @param {object} stream
*/
const createMediaRecorder = stream => {
return new Promise((resolve, reject) => {
try {
const mediaRecorder = new MediaRecorder(stream);
console.log('New MediaRecorder created');
resolve(mediaRecorder);
}
catch (err) {
console.log('Error in creating new MediaRecorder');
reject(err);
}
})
}

/**
* Initialize MediaRecorder
*/
const initializeMediaRecorder = async () => {
return new Promise(async (resolve, reject) => {
try {
const stream = await getStream();
console.log(stream);
setRecordingStreamPreview(stream);
const mediaRecorder = await createMediaRecorder(stream);
setMediaRecorder(mediaRecorder);
resolve(mediaRecorder);
}
catch (err) {
console.log('Error in initializing MediaRecorder of fetching media devices stream')
reject(err);
}
})
}

const handleFileChange = evt => {
props.handleFileChange(evt);
}

const handleVideoRecorder = blob => {
props.handleVideoRecorder(blob);
}

const handleRearCamera = _ => {
setShowRear(!showRear);
}

return (
<>
<video
className="container is-widescreen"
ref={recorderRef}
autoPlay
playsInline
muted
/>
<div className="level is-mobile">
<div className="level-item has-text-centered">
<div className="player-uttons">
<button className="button is-rounded is-danger" onClick={isRecording ? stop : start}>
<span className="icon">
{isRecording ?
<i className="fa fa-stop"></i>
:
<i className="fa fa-video-camera"></i>
}
</span>
</button>
<button className="button is-rounded is-warning ml-2" onClick={handleRearCamera}>
<span className="icon">
<i className="fa fa-refresh"></i>
{/* {isRecording ?
<i className="fa fa-stop"></i>
:
<i className="fa fa-video-camera"></i>
} */}
</span>
</button>
</div>
</div>
</div>
<div className="level is-mobile">
<div className="level-item has-text-centered">
<div className="file is-primary">
<label className="file-label">
<input onChange={handleFileChange} className="file-input" type="file" name="video" accept="video/mp4,video/x-m4v,video/*" />
<span className="file-cta">
<span className="file-icon">
<i className="fa fa-cloud-upload"></i>
</span>
<span className="file-label">
Upload Video
</span>
</span>
</label>
</div>
</div>
</div>
</>
)
}

export default MediaRecorderCapture;
一旦设置了标志,我正在初始化媒体。
知道为什么这不起作用吗?
伙计们,我真的被这件事困住了。
谢谢

最佳答案

编辑:要在页面加载时枚举摄像机列表,您需要立即请求权限:


window.onload = function(){
navigator.getUserMedia({audio:true,video:true}, function(stream) {
stream.getTracks().forEach(x=>x.stop());
getCamAndMics();
}, err=>console.log(err));
<rest of app>
}

我已经构建了一个应用程序来枚举可用的相机,然后让用户选择要记录的相机:
function getCamAndMics(){
// List cameras and microphones. in the menu

navigator.mediaDevices.enumerateDevices()
.then(function(devices) {
devices.forEach(function(device) {
console.log(device.kind + ": " + device.label +" id = " + device.deviceId);
var audioSelect = document.getElementById("audioPicker-select");
var cameraSelect = document.getElementById("cameraPicker-select");
if(device.kind=="audioinput"){
//add a select to the audio dropdown list
var option = document.createElement("option");
option.value = device.deviceId;
option.text = device.label;
audioSelect.appendChild(option);
}else if(device.kind =="videoinput"){
//add a select to the camera dropdown list
var option = document.createElement("option");
option.value = device.deviceId;
option.text = device.label;
cameraSelect.appendChild(option);

}
});
})
.catch(function(err) {
console.log(err.name + ": " + err.message);
});


}
即使在录制过程中 - 如果用户更改值,摄像机也会切换。这不仅适用于移动设备(前置和后置摄像头),而且适用于可能连接了一些媒体设备的台式机。
我将配置中的cameraId发送到getUserMedia:
  var videoOptions = {
deviceId: cameraId,
width: { min: 100, ideal: cameraW, max: 1920 },
height: { min: 100, ideal: cameraH, max: 1080 },
frameRate: {ideal: cameraFR}
};

cameraMediaOptions = {
audio: false,
video: videoOptions
};
cameraStream = await navigator.mediaDevices.getUserMedia(cameraMediaOptions);
代码在 Github: https://github.com/dougsillars/recordavideo/blob/main/public/index.js
演示现场 https://record.a.video .
通过此设置,我可以直播或录制并上传视频以按需共享。 (后端为 https://api.video 用于点播和直播)

关于reactjs - 如何在用 reactjs 构建的 PWA 应用程序中切换相机?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68047599/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com