fix(设备管理):新增设备视频流播放功能

This commit is contained in:
2025-05-17 17:36:32 +08:00
parent d4c39ac6b5
commit 783753bd60
8 changed files with 317 additions and 6 deletions
@@ -66,6 +66,7 @@
"react-helmet-async": "^1.2.0",
"react-intl": "6.4.4",
"react-json-tree": "^0.17.0",
"react-player": "^2.16.0",
"spark-md5": "^3.0.2",
"treeify-js": "^1.0.8",
"umi": "^3.5.0",
@@ -0,0 +1,20 @@
.playerContainer {
.controls {
margin-bottom: 16px;
padding: 8px;
background: #f5f5f5;
border-radius: 4px;
}
:global {
.ant-tabs-content {
background: #000;
border-radius: 4px;
overflow: hidden;
}
.ant-tabs-tab {
margin: 0 16px 0 0;
}
}
}
@@ -0,0 +1,237 @@
import React, { useState, useEffect, useRef } from 'react';
import { Modal, Tabs, Button, Space, Select, message, Badge } from 'antd';
import ReactPlayer from 'react-player';
import { VideoCameraOutlined, DownloadOutlined, PauseOutlined, PlayCircleOutlined } from '@ant-design/icons';
import styles from './VideoPlayer.less';
interface VideoPlayerProps {
visible: boolean;
onClose: () => void;
streamUrls: {
playFlvUrl: string;
playM3u8Url: string;
playRtmpUrl: string;
};
deviceSn: string;
}
const VideoPlayer: React.FC<VideoPlayerProps> = ({ visible, onClose, streamUrls, deviceSn }) => {
const [activeTab, setActiveTab] = useState('flv');
const [isPlaying, setIsPlaying] = useState(true);
const [isRecording, setIsRecording] = useState(false);
const [streamStatus, setStreamStatus] = useState<'online' | 'offline'>('offline');
const [quality, setQuality] = useState('high');
const playerRef = useRef<any>(null);
const mediaRecorderRef = useRef<MediaRecorder | null>(null);
const recordedChunksRef = useRef<Blob[]>([]);
// 检查流状态
const checkStreamStatus = async () => {
try {
const response = await fetch(streamUrls.playFlvUrl, { method: 'HEAD' });
setStreamStatus(response.ok ? 'online' : 'offline');
} catch (error) {
setStreamStatus('offline');
}
};
// 定期检查流状态
useEffect(() => {
if (visible) {
checkStreamStatus();
const interval = setInterval(checkStreamStatus, 30000); // 每30秒检查一次
return () => clearInterval(interval);
}
}, [visible, streamUrls]);
// 开始录制
const startRecording = () => {
if (playerRef.current) {
const stream = playerRef.current.getInternalPlayer().captureStream();
const mediaRecorder = new MediaRecorder(stream, {
mimeType: 'video/webm;codecs=vp9',
});
mediaRecorder.ondataavailable = (event) => {
if (event.data.size > 0) {
recordedChunksRef.current.push(event.data);
}
};
mediaRecorder.onstop = () => {
const blob = new Blob(recordedChunksRef.current, { type: 'video/webm' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `recording-${deviceSn}-${new Date().toISOString()}.webm`;
a.click();
URL.revokeObjectURL(url);
recordedChunksRef.current = [];
};
mediaRecorderRef.current = mediaRecorder;
mediaRecorder.start();
setIsRecording(true);
}
};
// 停止录制
const stopRecording = () => {
if (mediaRecorderRef.current && isRecording) {
mediaRecorderRef.current.stop();
setIsRecording(false);
}
};
// 处理播放器错误
const handleError = (error: any) => {
console.error('播放器错误:', error);
message.error('视频流播放出错,请检查网络连接或刷新重试');
};
// 处理播放器就绪
const handleReady = () => {
message.success('视频流已就绪');
};
// 获取当前播放的URL
const getCurrentUrl = () => {
switch (activeTab) {
case 'flv':
return streamUrls.playFlvUrl;
case 'hls':
return streamUrls.playM3u8Url;
case 'rtmp':
return streamUrls.playRtmpUrl;
default:
return streamUrls.playFlvUrl;
}
};
// 根据质量设置播放器配置
const getPlayerConfig = () => {
const baseConfig = {
controls: true,
width: '100%',
height: 450,
playing: isPlaying,
onError: handleError,
onReady: handleReady,
ref: playerRef,
};
switch (quality) {
case 'low':
return {
...baseConfig,
config: {
file: {
attributes: {
style: {
width: '100%',
height: '100%',
},
},
forceVideo: true,
forceHLS: true,
hlsOptions: {
maxBufferLength: 30,
maxMaxBufferLength: 60,
maxBufferSize: 0,
maxBufferHole: 0.5,
},
},
},
};
case 'high':
default:
return baseConfig;
}
};
return (
<Modal
title={
<Space>
<span>设备视频流</span>
<Badge
status={streamStatus === 'online' ? 'success' : 'error'}
text={streamStatus === 'online' ? '在线' : '离线'}
/>
</Space>
}
open={visible}
onCancel={onClose}
width={800}
footer={null}
>
<div className={styles.playerContainer}>
<div className={styles.controls}>
<Space>
<Button
type="primary"
icon={isPlaying ? <PauseOutlined /> : <PlayCircleOutlined />}
onClick={() => setIsPlaying(!isPlaying)}
>
{isPlaying ? '暂停' : '播放'}
</Button>
<Button
type={isRecording ? 'primary' : 'default'}
icon={<DownloadOutlined />}
onClick={isRecording ? stopRecording : startRecording}
>
{isRecording ? '停止录制' : '开始录制'}
</Button>
<Select
value={quality}
onChange={setQuality}
options={[
{ label: '高质量', value: 'high' },
{ label: '低质量', value: 'low' },
]}
/>
</Space>
</div>
<Tabs
activeKey={activeTab}
onChange={setActiveTab}
items={[
{
key: 'flv',
label: 'FLV',
children: (
<ReactPlayer
url={getCurrentUrl()}
{...getPlayerConfig()}
/>
),
},
{
key: 'hls',
label: 'HLS',
children: (
<ReactPlayer
url={getCurrentUrl()}
{...getPlayerConfig()}
/>
),
},
{
key: 'rtmp',
label: 'RTMP',
children: (
<ReactPlayer
url={getCurrentUrl()}
{...getPlayerConfig()}
/>
),
},
]}
/>
</div>
</Modal>
);
};
export default VideoPlayer;
@@ -3,8 +3,9 @@ import {
saveOrUpdateDevice,
deleteDevice,
updateDeviceBoundStatus,
getStreamUrls,
} from '@/services/device/api';
import { PlusOutlined, ExportOutlined, ImportOutlined, DownloadOutlined } from '@ant-design/icons';
import { PlusOutlined, ExportOutlined, ImportOutlined, DownloadOutlined, VideoCameraOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
ModalForm,
@@ -20,6 +21,7 @@ import { Button, message, Space, Switch, Upload } from 'antd';
import React, { useRef, useState } from 'react';
import moment from 'moment';
import UpdateForm from './components/UpdateForm';
import VideoPlayer from './components/VideoPlayer';
const DEVICE_TYPE = {
DOCK: 1,
@@ -38,6 +40,9 @@ const TableList: React.FC = () => {
const [createModalVisible, handleModalVisible] = useState<boolean>(false);
const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
const [currentRow, setCurrentRow] = useState<DEVICE.Device>();
const [videoModalVisible, setVideoModalVisible] = useState<boolean>(false);
const [streamUrls, setStreamUrls] = useState<any>(null);
const [loading, setLoading] = useState<boolean>(false);
// 统一的API请求处理函数
const handleRequest = async (
@@ -100,6 +105,24 @@ const TableList: React.FC = () => {
window.location.href = '/api-device/device/template';
};
// 处理视频流播放
const handlePlayVideo = async (deviceSn: string) => {
setLoading(true);
try {
const res = await getStreamUrls(deviceSn);
if (res.resp_code === 0) {
setStreamUrls(res.data);
setVideoModalVisible(true);
} else {
message.error(res.resp_msg || '获取视频流地址失败');
}
} catch (error) {
message.error('获取视频流地址失败');
} finally {
setLoading(false);
}
};
// 表格列定义
const columns: ProColumns<DEVICE.Device>[] = [
{
@@ -173,8 +196,14 @@ const TableList: React.FC = () => {
dataIndex: 'option',
valueType: 'option',
fixed: 'right',
width: 120,
width: 180,
render: (_, record) => [
<a
key="video"
onClick={() => handlePlayVideo(record.deviceSn)}
>
<VideoCameraOutlined /> 视频流
</a>,
<a
key="edit"
onClick={() => {
@@ -370,6 +399,19 @@ const TableList: React.FC = () => {
values={currentRow}
/>
)}
{/* 添加视频播放弹窗 */}
{streamUrls && (
<VideoPlayer
visible={videoModalVisible}
onClose={() => {
setVideoModalVisible(false);
setStreamUrls(null);
}}
streamUrls={streamUrls}
deviceSn={currentRow?.deviceSn || ''}
/>
)}
</PageContainer>
);
};
@@ -76,5 +76,17 @@ export async function updateDeviceBoundStatus(deviceSn: string, boundStatus: DEV
});
}
export async function getStreamUrls(deviceSn: string) {
return request<API.OptionalResult<{
pushUrl: string;
playFlvUrl: string;
playM3u8Url: string;
playRtmpUrl: string;
}>>('/api-device/stream-urls', {
method: 'GET',
params: { deviceId: deviceSn },
});
}