效果图:
核心代码:
VlcMutPlayer.h
#ifndef VLCMUTPLAYER_H
#define VLCMUTPLAYER_H
#include"vlc/vlc.h"
#include <QObject>
#include<QImage>
class VlcMutPlayer : public QObject
{
Q_OBJECT
public:
explicit VlcMutPlayer(QObject *parent = 0);
void play(QString filename);
~VlcMutPlayer();
signals:
void showImage(QImage img);
public slots:
private:
libvlc_instance_t *vlcInstance;
libvlc_media_player_t *mediaPlayer;
libvlc_media_t *media;
};
#endif // VLCMUTPLAYER_H
实现 VlcMutPlayer.cpp:
#include "VlcMutPlayer.h"
#include<QFile>
#include<QMutex>
#include<QDebug>
// 定义输出视频的分辨率
#define VIDEO_WIDTH 800
#define VIDEO_HEIGHT 600
QMutex g_mutex;
bool g_isInit = false;
char in_buffer[VIDEO_WIDTH*VIDEO_HEIGHT*4];
char out_buffer[VIDEO_WIDTH*VIDEO_HEIGHT*4];
VlcMutPlayer* _objInstance = NULL;
static void *lock(void *data, void **p_pixels)
{
Q_UNUSED(data)
g_mutex.lock();
*p_pixels = out_buffer; /*tell VLC to put decoded data to this buffer*/
return 0; /* picture identifier, not needed here */
}
static void unlock(void *data, void *id, void *const *p_pixels)
{
Q_UNUSED(data)
Q_UNUSED(id)
Q_UNUSED(p_pixels)
QImage image((unsigned char*)out_buffer,VIDEO_WIDTH,VIDEO_HEIGHT,QImage::Format_RGB32);
emit _objInstance->showImage(image);
g_mutex.unlock();
}
static void display(void *data, void *id)
{
/* do not display the video */
(void) data;
Q_UNUSED(id)
}
VlcMutPlayer::VlcMutPlayer(QObject *parent) : QObject(parent)
{
_objInstance = this;
// 创建并初始化 libvlc 实例
vlcInstance = libvlc_new(0, NULL);
}
void VlcMutPlayer::play(QString filename)
{
if (!QFile::exists(filename)) {
qDebug()<<"file is not exist:"<<filename;
return ;
}
media = libvlc_media_new_path(vlcInstance, filename.toStdString().data());
mediaPlayer = libvlc_media_player_new_from_media(media);
libvlc_media_release(media);
libvlc_video_set_callbacks(mediaPlayer, lock, unlock, display, 0);
libvlc_video_set_format(mediaPlayer, "RV32", VIDEO_WIDTH, VIDEO_HEIGHT, VIDEO_WIDTH *4);
libvlc_media_player_play(mediaPlayer);
}
VlcMutPlayer::~VlcMutPlayer()
{
if (mediaPlayer)
{
libvlc_media_player_stop(mediaPlayer); /*stop playing*/
libvlc_media_player_release(mediaPlayer); /*Free the media_player*/
mediaPlayer = NULL;
}
}
完成工程代码:https://download.csdn.net/download/xzpblog/10612631
扩展阅读:Qt封装VLC接口播放视频