一 需求场景
主机A获取TT无人机实时视频流推送给web端在网页播放。
二 TT无人机外形
三 环境配置
参考 RoboMaster Developer Guide的编程环境安装在主机A上配置Python环境。
四 主机A与无人机组网
1 想要主机A获取TT无人机实时视频流,要将主机A、无人机接入网络,参考“ 教育无人机系列连接方式”里面的组网模式。
2 如何判断主机A和TT无人机是否组网成功?
登录路由器管理地址看是否有新的设备(TT无人机)接入或者在主机A利用Python代码来测试,代码测试参考RoboMaster-SDK的examples目录,比如执行examples/04_camera/01_video_with_display.py里面代码看到了无人机十秒图传,说明主机A和TT无人机组网成功。
五 主机A推流
1 用node.js搭建流媒体服务,这里选择flv视频流给web端使用,rtmp对象是主机A推流的一些配置,http对象是web拉流的配置。
const NodeMediaServer = require('node-media-server');
const config = {
rtmp: {
port: 1935, // RTMP 端口
chunk_size: 60000, // RTMP 分块大小
gop_cache: true, // 是否开启 GOP 缓存
ping: 30, // ping 间隔时间(秒)
ping_timeout: 60 // ping 超时时间(秒)
},
// HTTP-FLV 配置
http: {
port: 3001, // HTTP 端口
allow_origin: '*' // 跨域设置
}
};
const nms = new NodeMediaServer(config);
nms.run();
2 在主机A上执行Python脚本获取实时视频帧,获取到的图像帧推送到流媒体服务上,地址 'rtmp://localhost:1935/live/uav’是推流地址,端口号和上面1保持一致。
from robomaster import robot
import subprocess
import itertools
flvUav= 'rtmp://localhost:1935/live/uav'
fps = 30 # 帧率
width = 960 # 宽度
height = 720 # 高度
# 启动 ffmpeg 进程
ffmpeg_cmd = [
'ffmpeg',
'-y', # 覆盖输出文件而不提示
'-f', 'rawvideo', # 输入文件格式为原始视频
'-vcodec', 'rawvideo',
'-pix_fmt', 'bgr24', # 像素格式为BGR 24位
'-s', f'{width}x{height}',
'-r', str(fps),
'-i', '-', # 从标准输入读取帧
'-c:v', 'libx264', # 使用libx264编码器
'-preset', 'ultrafast', # 编码器预设为ultrafast
'-f', 'flv', # 输出格式为FLV
flvUav
]
# 使用 subprocess.Popen 创建 ffmpeg 进程,并将 stdin 管道化
ffmpeg_process = subprocess.Popen(ffmpeg_cmd, stdin=subprocess.PIPE)
if __name__ == '__main__':
tl_drone = robot.Drone()
tl_drone.initialize(conn_type='sta')
tl_camera = tl_drone.camera
tl_camera.start_video_stream(display=False)
tl_camera.set_fps("high")
tl_camera.set_resolution("high")
tl_camera.set_bitrate(3)
for i in itertools.count():
try:
img = tl_camera.read_video_frame(timeout=3, strategy='newest')
# 将帧写入 ffmpeg 进程
ffmpeg_process.stdin.write(img)
except Exception as e:
print('uavPush error')
tl_camera.stop_video_stream()
ffmpeg_process.stdin.close()
ffmpeg_process.wait()
tl_drone.close()
break # 使用 break 退出循环
六 web端播放
web端拉流地址是‘http://localhost:3001/live/uav.flv’,用flv.js来播放
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.bootcss.com/flv.js/1.4.0/flv.min.js"></script>
</head>
<body>
<video id="videoElement" width="100%" height='100%' controls autoplay muted></video>
</body>
</html>
<script>
let flvUrl='http://localhost:3001/live/uav.flv'
window.onload=()=>{
let flvPlayer=null
let videoElement = document.getElementById('videoElement');
if (flvjs.isSupported()) {
flvPlayer= flvjs.createPlayer({
type: 'flv',
url:flvUrl
});
flvPlayer.attachMediaElement(videoElement);
flvPlayer.load();
flvPlayer.play();
}else{
alert('当前浏览器不支持flvjs')
}
}
</script>
第五、六步完整demo代码可参考线上代码。