QT中实现音乐播放器的歌词显示代码?
时间: 2024-05-09 20:17:21 浏览: 158
以下是一个简单的示例代码,用于在QT中实现音乐播放器的歌词显示:
```
#include <QMainWindow>
#include <QMediaPlayer>
#include <QMediaPlaylist>
#include <QLabel>
#include <QTimer>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr)
: QMainWindow(parent)
{
// 创建媒体播放器和播放列表
player = new QMediaPlayer(this);
playlist = new QMediaPlaylist(this);
player->setPlaylist(playlist);
// 创建标签用于显示歌词
lyricsLabel = new QLabel(this);
lyricsLabel->setAlignment(Qt::AlignCenter);
lyricsLabel->setStyleSheet("font-size: 20px; color: white;");
setCentralWidget(lyricsLabel);
// 加载歌曲和歌词文件
playlist->addMedia(QUrl::fromLocalFile("song.mp3"));
loadLyrics("song.lrc");
// 设置定时器用于更新歌词
QTimer *timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, &MainWindow::updateLyrics);
timer->start(100);
// 播放歌曲
player->play();
}
private:
QMediaPlayer *player;
QMediaPlaylist *playlist;
QLabel *lyricsLabel;
QList<QPair<int, QString>> lyrics;
void loadLyrics(const QString &fileName)
{
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
lyrics.clear();
QTextStream stream(&file);
while (!stream.atEnd()) {
QString line = stream.readLine();
QStringList parts = line.split("]");
for (int i = 0; i < parts.size() - 1; ++i) {
QString timeStr = parts[i].mid(1);
QTime time = QTime::fromString(timeStr, "mm:ss.zzz");
int ms = time.minute() * 60000 + time.second() * 1000 + time.msec();
QString text = parts.last();
lyrics.append(qMakePair(ms, text));
}
}
std::sort(lyrics.begin(), lyrics.end());
}
void updateLyrics()
{
int position = player->position();
int index = -1;
for (int i = 0; i < lyrics.size(); ++i) {
if (lyrics[i].first > position) {
break;
}
index = i;
}
QString text;
if (index >= 0 && index < lyrics.size()) {
text = lyrics[index].second;
}
lyricsLabel->setText(text);
}
};
```
此代码假设歌词文件使用LRC格式,并且每行歌词都以时间戳为开头,格式为`[mm:ss.zzz]lyrics`。代码将歌词文件解析为一个包含时间和文本的QList,当播放器播放时,使用定时器更新当前播放位置的歌词。
阅读全文