c++ rtmp推流代码
时间: 2023-12-17 17:26:41 浏览: 124
ffmpeg rtmp推流源码
4星 · 用户满意度95%
以下是使用ffmpeg进行rtmp推流的C++代码示例:
```cpp
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <sys/wait.h>
using namespace std;
int main(int argc, char *argv[]) {
string rtmpUrl = "rtmp://example.com/live/stream"; // RTMP推流地址
string videoDevice = "/dev/video0"; // 视频设备
string audioDevice = "hw:0,0"; // 音频设备
// 构造ffmpeg命令
string cmd = "ffmpeg -f v4l2 -i " + videoDevice + " -f alsa -i " + audioDevice + " -vcodec libx264 -preset ultrafast -acodec aac -f flv " + rtmpUrl;
// 转换为C字符串
char *cmdStr = new char[cmd.length() + 1];
strcpy(cmdStr, cmd.c_str());
// 创建子进程
pid_t pid = fork();
if (pid == -1) {
cerr << "Failed to fork" << endl;
exit(1);
} else if (pid == 0) {
// 子进程执行ffmpeg命令
system(cmdStr);
exit(0);
} else {
// 父进程等待子进程结束
int status;
waitpid(pid, &status, 0);
}
delete[] cmdStr;
return 0;
}
```
该代码使用了ffmpeg库进行rtmp推流,需要在编译时链接ffmpeg库。具体的CMakeLists.txt文件如下:
```cmake
cmake_minimum_required(VERSION 3.5)
project(rtmp_push)
set(CMAKE_CXX_STANDARD 11)
find_package(Threads REQUIRED)
# ffmpeg库路径
set(FFMPEG_LIB_DIR /usr/local/lib)
# 头文件路径
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)
# 链接库路径
link_directories(${FFMPEG_LIB_DIR})
# 链接库
link_libraries(avformat avcodec avutil swscale swresample)
add_executable(rtmp_push main.cpp)
# 链接线程库
target_link_libraries(rtmp_push Threads::Threads)
```
阅读全文