vlc初始化创建两个实例m_pInstance、m_pMediaPlayer,libvlc_event_attach犹如QT中的connect绑定,这里绑定的是事件和回调函数,所有事件都在一个回调函数中处理。
int CVlcKits::initVLC()
{
// vlc初始化
m_pInstance = libvlc_new(0, nullptr);
if (m_pInstance)
{
m_pMediaPlayer = libvlc_media_player_new(m_pInstance);//媒体播放器对象
if (m_pMediaPlayer)
{
//事件管理器
m_pEvent_manager = libvlc_media_player_event_manager(m_pMediaPlayer);
//关联事件
libvlc_event_attach(m_pEvent_manager, libvlc_MediaPlayerPositionChanged, vlc_callback, this);
libvlc_event_attach(m_pEvent_manager, libvlc_MediaPlayerAudioVolume, vlc_callback, this);
}
else
{
libvlc_release(m_pInstance);
return -2; // libvlc_media_player_new failed
}
}
else
{
return -1; // libvlc_new failed
}
return 0;
}
以下为回调函数,回调函数在类外,用p_data指针(pThis)访问类内成员。
关联了两个事件。第一个libvlc_MediaPlayerPositionChanged是视频播放时进度变化事件,获取的时间以秒为单位,所以需要转换为时、分、秒再发送到UI设置进度条。
第二个是libvlc_MediaPlayerAudioVolume当前的声音大小变化事件,获取了当前声音大小后设置UI中的音量条。
void vlc_callback(const struct libvlc_event_t* p_event, void* p_data)
{
CVlcKits* pThis = static_cast<CVlcKits*>(p_data);
if (pThis)
{
switch (p_event->type)
{
case libvlc_MediaPlayerPositionChanged:
{
float pos = libvlc_media_player_get_position(pThis->media_player());
pThis->setTimeSliderPos(pos * 100);
qint64 curSecs = libvlc_media_player_get_time(pThis->media_player()) / 1000;
int curH = curSecs / 3600;
int curMinute = (curSecs - curH * 3600) / 60;
int curSec = curSecs - curH * 3600 - curMinute * 60;
char buf1[256] = { 0 };
sprintf(buf1, "%02d:%02d:%02d", curH, curMinute, curSec);
QString str1(buf1);
qint64 totalSecs = pThis->getDurations();
int _hour = totalSecs / 3600;
int _minute = (totalSecs - _hour * 3600) / 60;
int _sec = totalSecs - _hour * 3600 - _minute * 60;
char buf2[256] = { 0 };
sprintf(buf2, "%02d:%02d:%02d", _hour, _minute, _sec);
QString str2(buf2);
QString text = str1 + "/" + str2;
pThis->setTimeText(text);
}
break;
case libvlc_MediaPlayerAudioVolume:
{
int volume = libvlc_audio_get_volume(pThis->media_player()); //用pThis获取媒体播器对象
pThis->setVolumeSliderPos(volume);
}
break;
}
}
}
播放单个视频代码,固定流程,照抄就行。
/// 播放视频
/// </summary>
/// <param name="fileName">文件全路径名</param>
/// <param name="hwnd">视频显示的窗口句柄</param>
/// <returns>
/// 0 success
/// -1 libvlc_media_new_path failed
/// </returns>
int CVlcKits::play(QString fileName, void* hwnd)
{
//设置路径
m_pMedia = libvlc_media_new_path(m_pInstance, fileName.toStdString().c_str());
if (m_pMedia)
{
//解析media
libvlc_media_parse(m_pMedia);
//设置media
libvlc_media_player_set_media(m_pMediaPlayer, m_pMedia);
//设置播放的窗口句柄
libvlc_media_player_set_hwnd(m_pMediaPlayer, hwnd);
// 视频总时长,单位ms
m_totalSecs = libvlc_media_get_duration(m_pMedia) / 1000;
//释放media
libvlc_media_release(m_pMedia);
m_pMedia = nullptr;
//播放视频
libvlc_media_player_play(m_pMediaPlayer);
return 0;
}
else
{
if (m_pMediaPlayer)
{
libvlc_media_player_release(m_pMediaPlayer);
m_pMediaPlayer = nullptr;
}
// 最后释放
if (m_pInstance)
{
libvlc_release(m_pInstance);
m_pInstance = nullptr;
}
return -1; //libvlc_media_new_path failed
}
}