您的位置:首页 > 移动开发 > IOS开发

iOS开发技巧之:如何在iOS平台上对一个视频进行解码和显示

2017-03-23 13:32 961 查看


前言

1.写作原因:iOS自己的播放器支持的格式有限,目前只有avi,mkv,mov,m4v,mp4等,像flv,rmvb等格式是不支持的,必须借助ffmpeg等第三方才能实现。

2.写作目的:利用第三方ffmpeg完成对不支持格式的解码和显示,目前只针对视频帧。


理论说明:

1.对于一个不能播放的视频格式,我们的方法是先把他解码成视频帧,然后再以图片的显示一帧帧的显示在屏幕上。

2.解码:具体包括解复用,解码和存储流信息。


代码实现(只关注解码流程)

//注册所有的文件格式和编解码器
avcodec_register_all();
av_register_all();

//打开视频文件,将文件格式的上下文传递到AVFormatContext类型的结构体中

if (avformat_open_input(&pFormatContext, [moviePath cStringUsingEncoding:NSASCIIStringEncoding], NULL, NULL)) {
av_log(NULL, AV_LOG_ERROR, "Couldn't open file\n");
goto initError;
}
//查找文件中视频流的信息
if (avformat_find_stream_info(pFormatContext, NULL) < 0) {
av_log(NULL, AV_LOG_ERROR, "Couldn't find a video stream in the input");
goto initError;
}

//find the first video stream
if ((videoStream = av_find_best_stream(pFormatContext, AVMEDIA_TYPE_VIDEO, -1, -1, &pCodec, 0)) < 0) {
av_log(NULL, AV_LOG_ERROR, "Cannot find a video stream in the input file\n");
goto initError;
}

//
pCodecContext = pFormatContext->streams[videoStream]->codec;

//找到该视频流对应的解码器
pCodec = avcodec_find_decoder(pCodecContext->codec_id);

if (pCodec == NULL) {
av_log(NULL, AV_LOG_ERROR, "Unsupported codec!\n");
goto initError;
}
//打开解码器
if (avcodec_open2(pCodecContext, pCodec, NULL) < 0) {
av_log(NULL, AV_LOG_ERROR, "Cannot open video decoder\n");
goto initError;
}

pFrame = av_frame_alloc();

_outputWidth = pCodecContext->width;
self.outputHeight = pCodecContext->height;


后面就是将YUV数据转换为RGB,然后将RGB图像转换为UIImage,便可以在屏幕上显示出来了这里不再赘述,git代码上有所体现。

代码已经传到git上面

演示:



如果你觉得有用,就加个star吧
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: