淘先锋技术网

首页 1 2 3 4 5 6 7

## 一、前言

上一个作品是ffmpeg内核做的,由于ffmpeg太过于强大,很多初学者会看的云里雾里懵逼状态,也有很多用户只需要一个简单的播放视频流即可,根本不需要涉及到负责的解码转码等,于是vlc就上场了,他就是直接对ffmpeg做了深层次的封装,提供了友好的接口,具备这种境界的还有个mpv之类的,mpv相比于vlc还更牛逼在库文件就一个,貌似是封装成了静态库,不想vlc还要带一堆的动态库文件和插件文件,当然vlc的简单在于只需要几行代码就可以撸起来,让初学者看到效果很重要,很兴奋,可以更快速的进行下一步的编码中,体验编码的乐趣。

## 二、代码思路

第一步:引入vlc的头文件```c++# ifdef __cplusplusextern "C" {# endif#ifdef vlc3#include #include #include #include #include #include #include #include #include #include #include #include #else#include #include #include #include #include #include #include #include #include #include #include #endif# ifdef __cplusplus}# endif```第二步:设置句柄打开视频流```c++bool VlcThread::init(){    const char *tempArg = "";    const char *vlc_args[9] = {"-I", "dummy", "--no-osd", "--no-stats", "--ignore-config", "--no-video-on-top", "--no-video-title-show", "--no-snapshot-preview", tempArg};    vlcInst = libvlc_new(sizeof(vlc_args) / sizeof(vlc_args[0]), vlc_args);    if (vlcInst == NULL) {        return false;    }    vlcMedia = libvlc_media_new_location(vlcInst, url.toUtf8().constData());    vlcPlayer = libvlc_media_player_new_from_media(vlcMedia);    if (vlcPlayer == NULL) {        return false;    }    //设置播放句柄    VlcWidget *w = (VlcWidget *)this->parent();#if defined(Q_OS_WIN)    libvlc_media_player_set_hwnd(vlcPlayer, (void *)w->winId());#elif defined(Q_OS_LINUX)    libvlc_media_player_set_xwindow(vlcPlayer, w->winId());#elif defined(Q_OS_MAC)    libvlc_media_player_set_nsobject(vlcPlayer, (void *)w->winId());#endif    //设置硬件加速 none auto any d3d11va dxva2    setOption(QString(":avcodec-hw=%1").arg("none"));    //设置通信协议 tcp udp    setOption(QString(":rtsp-%1").arg("tcp"));    //设置缓存时间 默认500毫秒    setOption(QString(":network-caching=%1").arg(300));    libvlc_media_player_play(vlcPlayer);    //qDebug() << TIMEMS << "init vlc finsh";    return true;}```第三步:暂停及释放资源```c++void VlcThread::pause(){    if (vlcPlayer != NULL) {        libvlc_media_player_pause(vlcPlayer);    }}void VlcThread::next(){    if (vlcPlayer != NULL) {        libvlc_media_player_pause(vlcPlayer);    }}void VlcThread::free(){    if (vlcInst != NULL) {        libvlc_release(vlcInst);        vlcInst = NULL;    }    if (vlcMedia != NULL) {        libvlc_media_release(vlcMedia);        vlcMedia = NULL;    }    if (vlcPlayer != NULL) {        libvlc_media_player_release(vlcPlayer);        vlcPlayer = NULL;    }    //qDebug() << TIMEMS << "close vlc ok";}

## 三、效果图

479ff05a9a5be09e16908dd03835a351.png

## 四、开源主页

1. 国内站点:[https://gitee.com/feiyangqingyun/QWidgetDemo](https://gitee.com/feiyangqingyun/QWidgetDemo)

2. 国际站点:[https://github.com/feiyangqingyun/QWidgetDemo](https://github.com/feiyangqingyun/QWidgetDemo)