使用librtmp接收直播流和點播流並儲存
阿新 • • 發佈:2018-12-31
#include <stdlib.h> #include <string.h> #include <math.h> #include <stdio.h> #include <signal.h> #include <stdint.h> #include "librtmp/rtmp_sys.h" #include "librtmp/log.h" #pragma comment(lib,"ws2_32.lib") #pragma comment(lib,"librtmp.lib") int InitSockets() { WORD version;WSADATA wsaData; version = MAKEWORD(1, 1); return (WSAStartup(version, &wsaData) == 0); } void CleanupSockets() { WSACleanup(); } int main() { InitSockets(); RTMP rtmp={0}; RTMP_Init(&rtmp); rtmp.Link.timeout=25;//超時設定 //由於crtmpserver是每個一段時間(預設8s)傳送資料包,需大於傳送間隔才行 bool bLiveStream=true;//是否直播 if (bLiveStream) { RTMP_SetupURL(&rtmp,"rtmp://127.0.0.1:1935/live/testlive"); //設定直播標誌 rtmp.Link.lFlags|=RTMP_LF_LIVE; }else { RTMP_SetupURL(&rtmp,"rtmp://127.0.0.1:1935/vod/test.flv"); } RTMP_SetBufferMS(&rtmp, 3600*1000);//1hour if(!RTMP_Connect(&rtmp,NULL)) { printf("Connect Server Err\n"); WSACleanup(); return -1; } if(!RTMP_ConnectStream(&rtmp,0)) { printf("Connect stream Err\n"); RTMP_Close(&rtmp); WSACleanup(); return -1; } int buffsize=1024*1024*10; char*buff=(char*)malloc(buffsize); double duration=-1; int nRead; FILE*fp=fopen("aaa.flv","wb"); long countbuffsize=0; //它直接輸出的就是FLV檔案,包括FLV頭,可對流按照flv格式解析就可提前音訊,視訊資料 while(nRead=RTMP_Read(&rtmp,buff,buffsize)) { fwrite(buff,1,nRead,fp); if (!bLiveStream&&duration<0) { duration = RTMP_GetDuration(&rtmp); printf("duration:%f\n",duration); } countbuffsize+=nRead; printf("\rdownland...:%0.2fkB",countbuffsize*1.0/1024); } fclose(fp); free(buff); buff=NULL; RTMP_Close(&rtmp); WSACleanup(); return 0; }