libVLC 添加字幕文件

news/2024/12/13 2:44:43/

在观看视频文件的时候,偶尔会遇到有的视频文件缺少音频、有的没有字幕的问题,libVLC提供了很好的接口来帮我们添加字幕文件。

以下是如何使用 libvlc 库在播放媒体时添加字幕的步骤:

1.初始化 VLC 实例。

vlc_base = libvlc_new(0, NULL);

2.创建一个媒体播放器,加载媒体文件。

    vlc_media = libvlc_media_new_path(vlc_base, filename.toUtf8().data());if (!vlc_media) {return;}// 创建libvlc实例和媒体播放器vlc_mediaPlayer = libvlc_media_player_new_from_media(vlc_media);if (!vlc_mediaPlayer) {return;}

3.播放媒体。

void showWidget::slotPlay()
{if (vlc_mediaPlayer)libvlc_media_player_play(vlc_mediaPlayer);
}

4.选择字幕文件加载。

使用libvlc_video_set_subtitle_file来加载字幕文件。

void showWidget::slotAddSubtitle()
{QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),"./",tr("videos (*.srt *.ssa *.ass *.txt)"));if (fileName.isEmpty())return;if (!vlc_mediaPlayer)return;const QString nativePath = QDir::toNativeSeparators(fileName);int res = libvlc_video_set_subtitle_file(vlc_mediaPlayer, nativePath.toUtf8().constData());if (res != 0) {qDebug("Could not add subtitle file.\n");}
}

以下是ui界面设计:

运行结果: 可以看见字幕文件已经被加载上。

代码示例:

#pragma once
#define LIBVLC_USE_PTHREAD_CANCEL 1
#include <QtWidgets/QWidget>
#include "ui_showWidget.h"
#include <QMenu>
#include <QActionGroup>
#include <vlc/vlc.h>#include <QDebug>
#include <QFileDialog>
#include <QThread>
#include <QMouseEvent>
#include <QKeyEvent>enum Rate
{Rate2X,Rate1_5X,Rate1_25X,Rate1_0X,Rate0_75X,Rate0_5X
};class showWidget : public QWidget
{Q_OBJECTpublic:showWidget(QWidget *parent = nullptr);~showWidget();protected:virtual void mouseDoubleClickEvent(QMouseEvent *event);virtual void keyPressEvent(QKeyEvent *event);virtual bool eventFilter(QObject *watched, QEvent *event);private slots:void slotOpenFile();void slotPlay();void slotPause();void slotStop();void slotValueChanged(int value);void slotCurrentIndexChanged(int index);void slotSnap();void slotAddSubtitle();private://事件处理回调static void vlcEvents(const libvlc_event_t *ev, void *param);private:Ui::showWidgetClass ui;private:libvlc_instance_t *vlc_base = nullptr;libvlc_media_t *vlc_media = nullptr;libvlc_media_player_t *vlc_mediaPlayer = nullptr;QList<float> m_lstRate;
};#include "showWidget.h"
#include <QTimer>
#include <QTime>
#include <QFileDialog>#pragma execution_character_set("utf-8")showWidget::showWidget(QWidget *parent): QWidget(parent)
{ui.setupUi(this);this->setWindowTitle("视频播放器");ui.cbxRate->setCurrentIndex(Rate1_0X);m_lstRate << 2.0 << 1.5 << 1.25 << 1.0 << 0.75 << 0.5;vlc_base = libvlc_new(0, NULL);ui.btnOpen->setFocusPolicy(Qt::NoFocus);ui.btnPlay->setFocusPolicy(Qt::NoFocus);ui.btnPause->setFocusPolicy(Qt::NoFocus);ui.btnStop->setFocusPolicy(Qt::NoFocus);ui.hSliderVolumn->setFocusPolicy(Qt::NoFocus);ui.cbxRate->setFocusPolicy(Qt::NoFocus);ui.horizontalSlider->installEventFilter(this);connect(ui.btnOpen, &QPushButton::clicked, this, &showWidget::slotOpenFile);connect(ui.btnPlay, &QPushButton::clicked, this, &showWidget::slotPlay);connect(ui.btnPause, &QPushButton::clicked, this, &showWidget::slotPause);connect(ui.btnStop, &QPushButton::clicked, this, &showWidget::slotStop);connect(ui.btnSnap, &QPushButton::clicked, this, &showWidget::slotSnap);connect(ui.btnAddSubtitle, &QPushButton::clicked, this, &showWidget::slotAddSubtitle);connect(ui.hSliderVolumn, &QSlider::valueChanged, this, &showWidget::slotValueChanged);connect(ui.cbxRate,SIGNAL(currentIndexChanged(int)), this, SLOT(slotCurrentIndexChanged(int)));
}showWidget::~showWidget()
{libvlc_release(vlc_base); //减少libvlc实例的引用计数,并销毁
}void showWidget::mouseDoubleClickEvent(QMouseEvent *event)
{if (this->isFullScreen()){this->showNormal();}else{this->showFullScreen();}
}void showWidget::keyPressEvent(QKeyEvent *event)
{if (!vlc_mediaPlayer)return;int value = ui.hSliderVolumn->value();if (event->key() == Qt::Key_W)	//添加音量{qDebug() << "up";slotValueChanged(value+10);}else if (event->key() == Qt::Key_S)	//减小音量{slotValueChanged(value - 10);}else if (event->key() == Qt::Key_Space){if (vlc_mediaPlayer && libvlc_media_player_get_state(vlc_mediaPlayer) == libvlc_Playing){libvlc_media_player_pause(vlc_mediaPlayer);}else if (vlc_mediaPlayer && libvlc_media_player_get_state(vlc_mediaPlayer) == libvlc_Paused){libvlc_media_player_play(vlc_mediaPlayer);}}
}bool showWidget::eventFilter(QObject *watched, QEvent *event)
{if (watched == ui.horizontalSlider) {if (event->type() == QEvent::MouseButtonPress) {if (!vlc_mediaPlayer)return false;QMouseEvent *mouse = static_cast<QMouseEvent*>(event);libvlc_time_t totalLen = libvlc_media_player_get_length(vlc_mediaPlayer);QPoint pos = mouse->pos();libvlc_time_t time = 0;time = (double)pos.x() / ui.horizontalSlider->width() * totalLen;libvlc_media_player_set_time(vlc_mediaPlayer, time);return true;}else {return false;}}else {// pass the event on to the parent classreturn QWidget::eventFilter(watched, event);}
}void showWidget::slotOpenFile()
{/*选择文件*/QString filename = QFileDialog::getOpenFileName(this, "选择打开的文件", "D:/", tr("*.*"));std::replace(filename.begin(), filename.end(), QChar('/'), QChar('\\'));vlc_media = libvlc_media_new_path(vlc_base, filename.toUtf8().data());if (!vlc_media) {return;}// 创建libvlc实例和媒体播放器vlc_mediaPlayer = libvlc_media_player_new_from_media(vlc_media);if (!vlc_mediaPlayer) {return;}// 等待元数据加载完成libvlc_media_parse(vlc_media);libvlc_video_set_mouse_input(vlc_mediaPlayer, 0);libvlc_video_set_key_input(vlc_mediaPlayer, 0);// 获取各种元数据const char *title = libvlc_media_get_meta(vlc_media, libvlc_meta_Title);const char *artist = libvlc_media_get_meta(vlc_media, libvlc_meta_Artist);const char *album = libvlc_media_get_meta(vlc_media, libvlc_meta_Album);const char *url = libvlc_media_get_meta(vlc_media, libvlc_meta_URL);const char *date = libvlc_media_get_meta(vlc_media, libvlc_meta_Date);const char *lang = libvlc_media_get_meta(vlc_media, libvlc_meta_Language);int duration = libvlc_media_get_duration(vlc_media);  // 获取时长(单位:毫秒)qDebug("Title: %s", title ? title : "N/A");qDebug("Artist: %s", artist ? artist : "N/A");qDebug("Album: %s", album ? album : "N/A");qDebug("Duration: %d ms", duration);qDebug("url: %s", url ? url : "N/A");qDebug("date: %s", date ? date : "N/A");qDebug("lang: %s", lang ? lang : "N/A");libvlc_media_track_t **tracks;int track_count = libvlc_media_tracks_get(vlc_media,&tracks);for (unsigned i = 0; i < track_count; i++) {libvlc_media_track_t* track = tracks[i];// 显示轨道信息printf("Track #%u: %s\n", i, track->psz_description);// 这里可以获取到每一个轨道的信息,比如轨道类型 track->i_type// 可能是 libvlc_track_video, libvlc_track_audio 或者 libvlc_track_text (字幕)if (track->i_type == libvlc_track_video) {// 处理视频轨道信息qDebug("width = %d",track->video->i_width);qDebug("height = %d", track->video->i_height);qDebug("rate_num = %d", track->video->i_frame_rate_num);qDebug("rate_den = %d", track->video->i_frame_rate_den);}else if (track->i_type == libvlc_track_audio) {// 处理音频轨道信息qDebug("channels = %d", track->audio->i_channels);qDebug("rate = %d", track->audio->i_rate);}else if (track->i_type == libvlc_track_text) {// 处理字幕轨道信息qDebug("psz_encoding = %s", track->subtitle->psz_encoding);}}//获取事件管理器libvlc_event_manager_t *em = libvlc_media_player_event_manager(vlc_mediaPlayer);// 注册事件监听器libvlc_event_attach(em, libvlc_MediaPlayerTimeChanged, vlcEvents, this);libvlc_event_attach(em, libvlc_MediaPlayerEndReached, vlcEvents, this);libvlc_event_attach(em, libvlc_MediaPlayerStopped, vlcEvents, this);libvlc_event_attach(em, libvlc_MediaPlayerPlaying, vlcEvents, this);libvlc_event_attach(em, libvlc_MediaPlayerPaused, vlcEvents, this);libvlc_media_player_set_hwnd(vlc_mediaPlayer, (void *)ui.widgetShow->winId());QTimer::singleShot(1000, this, &showWidget::slotPlay);}void showWidget::slotPlay()
{if (vlc_mediaPlayer)libvlc_media_player_play(vlc_mediaPlayer);
}void showWidget::slotPause()
{if (vlc_mediaPlayer)libvlc_media_player_pause(vlc_mediaPlayer);
}void showWidget::slotStop()
{if (vlc_mediaPlayer)libvlc_media_player_stop(vlc_mediaPlayer);
}void showWidget::slotValueChanged(int value)
{if (vlc_mediaPlayer)libvlc_audio_set_volume(vlc_mediaPlayer, value);
}void showWidget::slotCurrentIndexChanged(int index)
{if (vlc_mediaPlayer)libvlc_media_player_set_rate(vlc_mediaPlayer, m_lstRate[index]);
}void showWidget::slotSnap()
{if (vlc_mediaPlayer){QString path = "./snap.png";libvlc_video_take_snapshot(vlc_mediaPlayer, 0, path.toUtf8().data(), 0, 0);}
}void showWidget::slotAddSubtitle()
{QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),"./",tr("videos (*.srt *.ssa *.ass *.txt)"));if (fileName.isEmpty())return;if (!vlc_mediaPlayer)return;const QString nativePath = QDir::toNativeSeparators(fileName);int res = libvlc_video_set_subtitle_file(vlc_mediaPlayer, nativePath.toUtf8().constData());if (res != 0) {qDebug("Could not add subtitle file.\n");}
}//事件回调
void showWidget::vlcEvents(const libvlc_event_t *ev, void *param)
{showWidget *w = (showWidget*)param;//处理不同的事件switch (ev->type) {case libvlc_MediaPlayerTimeChanged:{//qDebug() << "VLC媒体播放器时间已更改";qint64 len = libvlc_media_player_get_time(w->vlc_mediaPlayer);libvlc_time_t lenSec = len / 1000;libvlc_time_t totalLen = libvlc_media_player_get_length(w->vlc_mediaPlayer);libvlc_time_t totalLenSec = totalLen / 1000;int thh, tmm, tss;thh = lenSec / 3600;tmm = (lenSec % 3600) / 60;tss = (lenSec % 60);QTime time(thh, tmm, tss);w->ui.lbCurTime->setText(time.toString("hh:mm:ss"));thh = totalLenSec / 3600;tmm = (totalLenSec % 3600) / 60;tss = (totalLenSec % 60);QTime TotalTime(thh, tmm, tss);w->ui.lbTotalTime->setText(TotalTime.toString("hh:mm:ss"));double pos = (double)lenSec / totalLenSec * 100;w->ui.horizontalSlider->setValue(pos);}break;case libvlc_MediaPlayerEndReached:qDebug() << "VLC播放完毕.";break;case libvlc_MediaPlayerStopped:qDebug() << "VLC停止播放";break;case libvlc_MediaPlayerPlaying:qDebug() << "VLC开始播放";break;case libvlc_MediaPlayerPaused:qDebug() << "VLC暂停播放";break;}
}

其他:

字幕文件下载地址分享交流下载字幕平台 - SubHD

根据自己已有的电影去下载相应的字幕文件。

更多参考:

Qt+FFmpeg+opengl从零制作视频播放器-1.项目介绍_qt opengl视频播放器-CSDN博客

libVLC 提取视频帧使用OpenGL渲染-CSDN博客

QT UDP通信(单播、广播、组播)-CSDN博客

QCharts -1.概述-CSDN博客


http://www.ppmy.cn/news/1414953.html

相关文章

PCB封装库的创建及引入

法1 1.创建lib 2.放置 找到你想要画的封装的器件的数据手册了解相关信息。 直插式选Multi-layer 贴片选Top-layer 焊盘尺寸 焊盘空尺寸 法2 嘉立创eda直接copy 再嘉立创中找到你想要的pcb&#xff0c;导出为ad 然后再ad中找到我们导出的文件 复制他 然后再库中粘贴 pcb库…

VS选择数据源数据提供程序的区别

VS选择数据源数据提供程序的区别 1、用于OLE DB的.net framework 数据提供程序 OLE DB是微软提供的一种数据访问技术&#xff0c;它允许应用程序访问存储在不同类型的数据源中的数据。.NET Framework 提供了一个用于OLE DB的数据提供程序&#xff0c;允许开发人员使用ADO.NET…

什么是Java中的方法重载

目录 引言 方法重载的定义 方法重载的使用场景 方法重载的规则 方法重载与方法重写的区别 实例代码 总结 引言 在Java编程语言中&#xff0c;方法重载是一个非常重要的概念&#xff0c;它允许一个类中定义多个名称相同但参数列表不同的方法。这一特性不仅增强了Java语言…

springboot如何切换内置web服务器?

切换内置web服务器 这是没有引入web依赖的服务 这是引入web依赖的服务 由此可知默认是tomcat服务器 那么如何切换内置服务器 只要有对应服务器的坐标即可自动切换&#xff0c;先排除tomcat再引入依赖&#xff0c;比如切换成jetty服务器 <dependency><groupId>org…

ClickHouse入门篇:一文带你学习ClickHouse

ClickHouse 是一个用于联机分析处理(OLAP)的列式数据库管理系统(DBMS)。由于其独特的数据存储和处理架构&#xff0c;ClickHouse 能够提供高速数据插入和实时查询性能。下面是对 ClickHouse 的详细介绍&#xff0c;包括其特性、应用场景和架构&#xff1a; 特性 列式存储: 数…

超越ChatGPT,国内快速访问的强大 AI 工具 Claude

claude 3 opus面世后&#xff0c;网上盛传吊打了GPT-4。网上这几天也已经有了许多应用&#xff0c;但竟然还有很多小伙伴不知道国内怎么用gpt&#xff0c;也不知道怎么去用这个据说已经吊打了gpt-4的claude3。 今天我们想要进行的一项尝试就是—— 用claude3和gpt4&#xff0c…

安卓四大组件——ContentProvider

1.作用 管理 结构化数据集的访问 &#xff0c;封装数据&#xff0c;应用间数据共享 2.生命周期 只是它属于系统应用、所以随系统启动而初始化&#xff0c;随系统关机而结束&#xff1b; 3.具体实现 自定义的ContentProvider 有六个需要重写的方法&#xff0c;分别是创建和增删改…

搭建PyTorch神经网络进行气温预测(手写+调包两种方法)(保证学会!)+找到神经网络的最优情况

代码上有注释&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01; 本篇主要包括三大部分&#xff1a; 第一部分&#xff1a;导入数据集导入第三方库数据集简单介绍与可视化数据集简单预处理 第二部分&#xff1a;手写神经网络代码实现气温预测&#…