React开发:Amazon KVS实时视频流获取后续步骤求助
在React中获取Amazon KVS实时视频流(Viewer角色)
你已经完成了获取信令通道端点的核心步骤,接下来可以通过Amazon KVS WebRTC SDK快速建立连接并获取实时视频流,以下是直接可落地的步骤和代码:
1. 安装依赖
先安装官方WebRTC SDK:
npm install amazon-kinesis-video-streams-webrtc-sdk-js
2. 整合到React组件
基于你已有的代码,将后续逻辑封装到React组件中,使用useEffect处理异步连接逻辑,用useRef引用视频元素:
import React, { useEffect, useRef } from 'react'; import AWS from 'aws-sdk'; import { SignalingClient, Role } from 'amazon-kinesis-video-streams-webrtc-sdk-js'; const KVSVideoViewer = ({ channelName, awsCredentials }) => { const videoRef = useRef(null); const signalingClientRef = useRef(null); const peerConnectionRef = useRef(null); useEffect(() => { const connectToKVS = async () => { const { accessKeyId, secretAccessKey, region, sessionToken } = awsCredentials; const kinesisVideoClient = new AWS.KinesisVideo({ accessKeyId, secretAccessKey, region, sessionToken }); // 你已完成的部分:获取通道信息和端点 const { ChannelInfo } = await kinesisVideoClient.describeSignalingChannel({ ChannelName: channelName }).promise(); const { ChannelARN } = ChannelInfo; const getSignalingChannelEndpointResponse = await kinesisVideoClient.getSignalingChannelEndpoint({ ChannelARN: ChannelARN, SingleMasterChannelEndpointConfiguration: { Protocols: ['WSS', 'HTTPS'], Role: Role.VIEWER, }, }).promise(); const endpointsByProtocol = getSignalingChannelEndpointResponse.ResourceEndpointList.reduce((endpoints, endpoint) => { endpoints[endpoint.Protocol] = endpoint.ResourceEndpoint; return endpoints; }, {}); // --------------- 新增逻辑:建立WebRTC连接 --------------- // 1. 初始化信令客户端 signalingClientRef.current = new SignalingClient({ channelARN: ChannelARN, endpoint: endpointsByProtocol.WSS, role: Role.VIEWER, region: region, credentials: { accessKeyId, secretAccessKey, sessionToken }, }); // 2. 配置ICE服务器(用于NAT穿透) const iceServers = [{ urls: `stun:stun.kinesisvideo.${region}.amazonaws.com:443` }]; peerConnectionRef.current = new RTCPeerConnection({ iceServers }); // 3. 监听远程流到达事件,挂载到video元素 peerConnectionRef.current.ontrack = (event) => { if (videoRef.current) { videoRef.current.srcObject = event.streams[0]; } }; // 4. 信令客户端事件监听 signalingClientRef.current.on('open', async () => { console.log('信令通道已打开'); // 发送SDP offer const offer = await peerConnectionRef.current.createOffer(); await peerConnectionRef.current.setLocalDescription(offer); signalingClientRef.current.sendSdpOffer(offer); }); signalingClientRef.current.on('sdpAnswer', async (answer) => { await peerConnectionRef.current.setRemoteDescription(answer); }); signalingClientRef.current.on('iceCandidate', (candidate) => { peerConnectionRef.current.addIceCandidate(candidate); }); signalingClientRef.current.on('close', () => { console.log('信令通道已关闭'); }); signalingClientRef.current.on('error', (error) => { console.error('信令客户端错误:', error); }); // 打开信令连接 signalingClientRef.current.open(); }; connectToKVS(); // 组件卸载时清理资源 return () => { if (peerConnectionRef.current) { peerConnectionRef.current.close(); } if (signalingClientRef.current) { signalingClientRef.current.close(); } }; }, [channelName, awsCredentials]); return ( <video ref={videoRef} autoPlay playsInline muted={false} // 根据需求设置是否静音 style={{ width: '100%', maxWidth: '800px' }} /> ); }; export default KVSVideoViewer;
关键说明
- 角色配置:你设置的是
Role.VIEWER,所以只需要订阅流,不需要发布自己的媒体流 - ICE服务器:使用KVS提供的STUN服务器,确保跨网络环境下能建立连接
- 资源清理:组件卸载时必须关闭PeerConnection和信令客户端,避免内存泄漏
- 视频元素属性:
autoPlay和playsInline是确保视频自动播放的关键(部分浏览器需要用户交互才能取消静音,可根据需求调整muted)
使用组件
在你的仪表盘页面中直接引入并传入参数即可:
<KVSVideoViewer channelName="你的通道名称" awsCredentials={{ accessKeyId: '你的AccessKey', secretAccessKey: '你的SecretKey', region: '你的区域(如us-east-1)', sessionToken: '你的临时会话Token(如果使用STS)' }} />
内容的提问来源于stack exchange,提问作者Jack Sparrow
相关产品推荐
相关产品推荐

