FFmpeg和SDL2播放mp4

简单的看了下FFmpeg和SDL2的相关内容,想用ffmpeg和SDL2制作一个mp4播放器。网上找了好多例子,大多数只能播放video,不能播放audio,后来还是从一个大神的github里找到一份代码(大神的代码地址),可以实现音视频同步,代码有两个地方需要稍微修改一下,具体的实现思路可以参考大神的博客。现在把代码贴出来,让初学者可以找到一个可以跑起来的代码,增加后续的学习信心。
SimplePlayer.c

#include 
#include 
#include 



#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 



#define SDL_AUDIO_BUFFER_SIZE 1024
#define MAX_AUDIO_FRAME_SIZE 192000 //channels(2) * data_size(2) * sample_rate(48000)

#define MAX_AUDIOQ_SIZE (5 * 16 * 1024)
#define MAX_VIDEOQ_SIZE (5 * 256 * 1024)

#define AV_SYNC_THRESHOLD 0.01
#define AV_NOSYNC_THRESHOLD 10.0

#define FF_REFRESH_EVENT (SDL_USEREVENT)
#define FF_QUIT_EVENT (SDL_USEREVENT + 1)

#define VIDEO_PICTURE_QUEUE_SIZE 1


typedef struct PacketQueue {
    AVPacketList *first_pkt, *last_pkt;
    int nb_packets;
    int size;
    SDL_mutex *mutex;
    SDL_cond *cond;
} PacketQueue;


typedef struct VideoPicture {
    AVFrame *frame;
    int width, height; /* source height & width */
    double pts;
} VideoPicture;

typedef struct VideoState {

    //multi-media file
    char filename[1024];
    AVFormatContext *pFormatCtx;
    int videoStream, audioStream;


    double audio_clock;
    double frame_timer;
    double frame_last_pts;
    double frame_last_delay;

    double video_clock; ///
    double video_current_pts; ///
    int64_t video_current_pts_time;  ///

cmake文件

cmake_minimum_required(VERSION 3.9)
project(SimplePlayer C)

set(CMAKE_C_STANDARD 99)

set(SOURCE_FILES SimplePlayer.cpp)

set(MY_LIBRARY_DIR /usr/local)
set(FFMPEG_DIR ${MY_LIBRARY_DIR}/ffmpeg) # FFmpeg的安装目录,可以通过命令"brew info ffmpeg"获取
set(SDL_DIR /usr/include/SDL)
find_package(Threads REQUIRED)


include_directories(${FFMPEG_DIR}/include/
        ${SDL_DIR}/include/) # 头文件搜索路径
link_directories(${FFMPEG_DIR}/lib/
        ${SDL_DIR}/lib/) # 动态链接库或静态链接库的搜索路径

include_directories(${INC_DIR_SDL})
link_directories(${LINK_DIR_SDL})
include_directories(${INC_DIR})
link_directories(${LINK_DIR})

add_executable(SimplePlayer SimplePlayer.c)
target_link_libraries(
        SimplePlayer
        avcodec
        SDL2
        SDL2main
        avcodec
        avdevice
        avfilter
        avformat
        avutil
        swresample
        pthread
        swscale)

最终实现效果

我使用的平台是ubuntu18.04,之前也开发过gstreamer的播放器,发现gstreamer更简单一点,但是ffmpeg提供的编解码功能更强大一些,也有在gstreamer中使用ffmpeg的例子,后续打通了会贴上代码。

你可能感兴趣的:(ffmpeg,ffmpeg)