Qt5+VS 2013 Mediaplayer 音乐播放器 代码

代码主要包含5块:main、musicplayer、myPlayList、myLyric、mySettings

可能可读性不高,实在不想弄了。 不过稍微看下,还是能看懂的。嘿嘿

1、myLyric.h

#ifndef MYLYRIC_H
#define MYLYRIC_H


#include
class QTimer;


class MyLyric : public QLabel
{
Q_OBJECT
public:
explicit MyLyric(QWidget * parent = 0);
void startLrcMask(qint64 intervalTime);
void stopLrcMask();
protected:
void paintEvent(QPaintEvent *);
void mousePressEvent(QMouseEvent *ev);
void mouseMoveEvent(QMouseEvent *ev);
void contextMenuEvent(QContextMenuEvent * event);


private slots:
void timeout();
private:
QLinearGradient linearGradient;
QLinearGradient maskLinearGradient;
QFont font;
QTimer * timer;
qreal lrcMaskWidth;
qreal lrcMaskWidthInterval;
QPoint offset;
};

#endif // !MYLYRIC_H

2、myLyric.cpp

#include "myLyric.h"
#include
#include
#include
#include
#include
#include
#include


MyLyric::MyLyric(QWidget *parent) :
QLabel(parent)
{
setWindowFlags(Qt::Window | Qt::FramelessWindowHint);
// 设置背景透明
setAttribute(Qt::WA_TranslucentBackground);
setText(QStringLiteral("听 ---  Jin Xin 作品"));
setAlignment(Qt::AlignCenter);
// 固定部件大小
setMaximumSize(1000, 60);
setMinimumSize(1000, 60);
resize(1000, 60);
QDesktopWidget* desktop = QApplication::desktop();
move((desktop->width() - this->width()) / 2, desktop->height() * 3 / 4);

// 歌词的线性渐变填充
linearGradient.setStart(0, 10);
linearGradient.setFinalStop(0, 40);
linearGradient.setColorAt(0.1, QColor(14, 179, 255));
linearGradient.setColorAt(0.5, QColor(114, 232, 255));
linearGradient.setColorAt(0.9, QColor(14, 179, 255));
// 遮罩的线性渐变填充
maskLinearGradient.setStart(0, 10);
maskLinearGradient.setFinalStop(0, 40);
maskLinearGradient.setColorAt(0.1, QColor(222, 54, 4));
maskLinearGradient.setColorAt(0.5, QColor(255, 72, 16));
maskLinearGradient.setColorAt(0.9, QColor(222, 54, 4));
// 设置字体
font.setFamily("Times New Roman");
font.setBold(true);
font.setPointSize(30);
// 设置定时器
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(timeout()));
lrcMaskWidth = 0;
lrcMaskWidthInterval = 0;
}


void MyLyric::paintEvent(QPaintEvent *)
{
QPainter painter(this);


painter.setFont(font);
// 先绘制底层文字,作为阴影,这样会使显示效果更加清晰,且更有质感
painter.setPen(QColor(0, 0, 0, 200));
painter.drawText(1, 1, 800, 60, Qt::AlignLeft, text());
// 再在上面绘制渐变文字
painter.setPen(QPen(linearGradient, 0));
painter.drawText(0, 0, 800, 60, Qt::AlignLeft, text());


// 设置歌词遮罩
painter.setPen(QPen(maskLinearGradient, 0));
painter.drawText(0, 0, lrcMaskWidth, 60, Qt::AlignLeft, text());
}


// 开启遮罩,需要指定当前歌词开始与结束之间的时间间隔
void MyLyric::startLrcMask(qint64 intervalTime)
{
// 这里设置每隔30毫秒更新一次遮罩的宽度,因为如果更新太频繁
// 会增加CPU占用率,而如果时间间隔太大,则动画效果就不流畅了
qreal count = intervalTime / 30;
// 获取遮罩每次需要增加的宽度,这里的800是部件的固定宽度
lrcMaskWidthInterval = 800 / count;
lrcMaskWidth = 0;
timer->start(30);
}


// 停止遮罩
void MyLyric::stopLrcMask()
{
timer->stop();
lrcMaskWidth = 0;
update();
}


// 两个鼠标事件处理函数实现了部件的拖动
void MyLyric::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
offset = event->globalPos() - frameGeometry().topLeft();
}
void MyLyric::mouseMoveEvent(QMouseEvent *event)
{
if (event->buttons() & Qt::LeftButton) {
setCursor(Qt::PointingHandCursor);
move(event->globalPos() - offset);
}
}


// 实现右键菜单来隐藏部件
void MyLyric::contextMenuEvent(QContextMenuEvent *event)
{
QMenu menu;
menu.addAction(QStringLiteral("隐藏"), this, SLOT(hide()));
menu.exec(event->globalPos());
}


// 定时器溢出时增加遮罩的宽度,并更新显示
void MyLyric::timeout()
{
lrcMaskWidth += lrcMaskWidthInterval;
update();
}

3、myPlayList.h

#ifndef MUSICPLAYLIST_H
#define MUSICPLAYLIST_H


#include
#include
#include
#include


class MyPlaylist : public QWidget
{
Q_OBJECT
public:
explicit MyPlaylist(QWidget *parent = 0);
~MyPlaylist();
QMediaPlaylist *musicPlayList;
QTableWidget * songTableWidget;
private:
QPoint offset;
QString initialName;
QPushButton * openMusicFileButton;
QPushButton * sortMusicFileButton;
QPushButton * closeMusicListWindowButton;
QPushButton * deleteSelectedMusicButton;
QPushButton * openPlayListButton;
QPushButton * saveAsPlayListButton;
QPushButton * ascendingOrderButton;
QPushButton * descendingOrderButton;
QString curFile;                        // 保存当前文件路径
void setCurrentFile(const QString &fileName);
protected:
void contextMenuEvent(QContextMenuEvent *event);
void closeEvent(QCloseEvent *event);
void mousePressEvent(QMouseEvent *ev);
void mouseMoveEvent(QMouseEvent *ev);


signals:
void playlistReduced();
void playlistAdded();
void musicFilesChanged();
void playlistReady(int );
void isModified();
private slots:
void clearPlaylist();
void deleteSelectedMusic();
void savePlayList();
void importSongs();
void importPlayList();
void playListWindowHideOrShow();
void changeMusicPlayList(int);
void sortButtonHideOrShow();
void ascendingSortMusicFiles();
void descendingSortMusicFiles();
void setMusicPlaylist();
void setSaveButtonEnabledOrNot();


};


#endif // MYPLAYLIST_H

4、myPlayList.cpp

#include "myPlayList.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include


MyPlaylist::MyPlaylist(QWidget *parent) :
QWidget(parent)
{
setWindowTitle(QStringLiteral("播放列表"));
setWindowFlags(Qt::Window | Qt::FramelessWindowHint);
setMaximumSize(300, 500);
setMinimumSize(300, 300);
resize(300, 300);
setWindowIcon(QIcon(":/images/myPlayer.png"));
setAutoFillBackground(true);
setPalette(QPalette(QColor(120, 214, 255, 255)));
// 打开文件
openMusicFileButton = new QPushButton(this);
openMusicFileButton->setFixedSize(100, 20);
openMusicFileButton->move(2, 2);
openMusicFileButton->setFlat(true);
openMusicFileButton->setText(QStringLiteral("+添加本地歌曲"));
initialName = QDir::homePath();
// 播放列表窗口(添加音乐列表排序按钮)
sortMusicFileButton = new QPushButton(this);
sortMusicFileButton->setFixedSize(40, 20);
sortMusicFileButton->move(104, 2);
sortMusicFileButton->setFlat(true);
sortMusicFileButton->setText(QStringLiteral("排序"));
//// 排序窗口 (Ascending)
ascendingOrderButton = new QPushButton(this);
ascendingOrderButton->setFixedSize(20, 20);
ascendingOrderButton->move(150, 2);
ascendingOrderButton->hide();
QPixmap im = QPixmap(":/images/Ascending.png");
ascendingOrderButton->setIconSize(QSize(20, 20));
ascendingOrderButton->setIcon(im.scaled(20, 20));
// 排序窗口 (Descending)
descendingOrderButton = new QPushButton(this);
descendingOrderButton->setFixedSize(20, 20);
descendingOrderButton->move(176, 2);
im = QPixmap(":/images/Descending.png");
descendingOrderButton->setIconSize(QSize(20, 20));
descendingOrderButton->setIcon(im.scaled(20, 20));
descendingOrderButton->hide();


// 播放列表窗口(关闭播放列表窗口)
closeMusicListWindowButton = new QPushButton(this);
closeMusicListWindowButton->setFixedSize(20, 20);
closeMusicListWindowButton->move(271, 2);
closeMusicListWindowButton->setFlat(true);
closeMusicListWindowButton->setToolTip(QStringLiteral("关闭窗口"));
im = QPixmap(":/images/quit.png");
closeMusicListWindowButton->setIconSize(QSize(20, 20));
closeMusicListWindowButton->setIcon(im.scaled(20, 20));
// 删除选中音乐
deleteSelectedMusicButton = new QPushButton(this);
deleteSelectedMusicButton->setFixedSize(20, 20);
deleteSelectedMusicButton->move(246, 2);
deleteSelectedMusicButton->setFlat(true);
deleteSelectedMusicButton->setToolTip((QStringLiteral("删除")));
im = QPixmap(":/images/Delete.png");
deleteSelectedMusicButton->setIconSize(QSize(20, 20));
deleteSelectedMusicButton->setIcon(im.scaled(20, 20));
// 保存播放列表
openPlayListButton = new QPushButton(this);
openPlayListButton->setFixedSize(20, 20);
openPlayListButton->move(196, 2);
openPlayListButton->setFlat(true);
openPlayListButton->setToolTip((QStringLiteral("打开播放列表")));
im = QPixmap(":/images/OpenPlayList.png");
openPlayListButton->setIconSize(QSize(20, 20));
openPlayListButton->setIcon(im.scaled(20, 20));
// 另存为
saveAsPlayListButton = new QPushButton(this);
saveAsPlayListButton->setFixedSize(20, 20);
saveAsPlayListButton->move(221, 2);
saveAsPlayListButton->setFlat(true);
saveAsPlayListButton->setToolTip((QStringLiteral("保存播放列表")));
im = QPixmap(":/images/saveAs.png");
saveAsPlayListButton->setIconSize(QSize(16, 16));
saveAsPlayListButton->setIcon(im.scaled(16, 16));


songTableWidget = new QTableWidget(0, 3, this);
QStringList TableHeader;
TableHeader << QStringLiteral("标题") << QStringLiteral("类型");
songTableWidget->setHorizontalHeaderLabels(TableHeader);
songTableWidget->setFixedSize(300, 276);
songTableWidget->move(0, 24);
songTableWidget->setPalette(QPalette(QColor(120, 214, 255, 255)));
songTableWidget->setShowGrid(false);
songTableWidget->setColumnWidth(0, 215);
songTableWidget->setColumnWidth(1, 50);
songTableWidget->setColumnWidth(2, 10);
songTableWidget->setColumnHidden(2,true);
songTableWidget->setEditTriggers(QTableWidget::NoEditTriggers);
songTableWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
// 设置只能选择单行
songTableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
songTableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);//整行选中
// 设置不显示网格
songTableWidget->setShowGrid(false);
musicPlayList = new QMediaPlaylist(this);
musicPlayList->setPlaybackMode(QMediaPlaylist::Loop);
connect(openMusicFileButton, SIGNAL(clicked()), this, SLOT(importSongs()));
connect(openPlayListButton, SIGNAL(clicked()), this, SLOT(importPlayList()));
connect(closeMusicListWindowButton, SIGNAL(clicked()), this, SLOT(playListWindowHideOrShow()));
connect(deleteSelectedMusicButton, SIGNAL(clicked()), this, SLOT(deleteSelectedMusic()));
connect(this, SIGNAL(isModified()), this, SLOT(setSaveButtonEnabledOrNot()));
connect(saveAsPlayListButton, SIGNAL(clicked()), this, SLOT(savePlayList()));


connect(sortMusicFileButton, SIGNAL(clicked()), this, SLOT(sortButtonHideOrShow()));
connect(ascendingOrderButton, SIGNAL(clicked()), this, SLOT(ascendingSortMusicFiles()));
connect(descendingOrderButton, SIGNAL(clicked()), this, SLOT(descendingSortMusicFiles()));

connect(songTableWidget, SIGNAL(cellDoubleClicked(int, int)), this, SLOT(changeMusicPlayList(int)));

connect(this, SIGNAL(musicFilesChanged()), this, SLOT(setMusicPlaylist()));
}
MyPlaylist::~MyPlaylist()
{
delete musicPlayList;
delete songTableWidget;
delete openMusicFileButton;
delete sortMusicFileButton;
delete closeMusicListWindowButton;
delete deleteSelectedMusicButton;
delete ascendingOrderButton;
delete descendingOrderButton;
}
void MyPlaylist::contextMenuEvent(QContextMenuEvent *event)
{
QMenu menu;
menu.addAction(QStringLiteral("保存播放列表"), this, SLOT(savePlayList()));
menu.addAction(QStringLiteral("删除歌曲"), this, SLOT(deleteSelectedMusic()));
menu.addAction(QStringLiteral("清空列表"), this, SLOT(clearPlaylist()));
menu.exec(event->globalPos());
}
void MyPlaylist::clearPlaylist()
{
while (songTableWidget->rowCount()){
songTableWidget->removeRow(0);
musicPlayList->removeMedia(0);
}
emit isModified();
emit playlistReduced();
}
void MyPlaylist::deleteSelectedMusic()
{
QTableWidgetItem * item = songTableWidget->currentItem();
if (item == Q_NULLPTR)return;
musicPlayList->removeMedia(songTableWidget->currentRow());
songTableWidget->removeRow(item->row());
emit isModified();
emit playlistReduced();
}
void MyPlaylist::closeEvent(QCloseEvent *event)
{
if (isVisible()) {
hide();
event->ignore();
}
}
void MyPlaylist::importSongs()
{
QStringList pathList = QFileDialog::getOpenFileNames(this, QStringLiteral("选择文件"), initialName, tr("(*.mp3)"));
bool flag = false;
if (musicPlayList->isEmpty())
flag = true;
for (int i = 0; i < pathList.size(); ++i)
{
QString path = QDir::toNativeSeparators(pathList.at(i));
if (!path.isEmpty())
{
musicPlayList->addMedia(QUrl::fromLocalFile(path));
QString fileName = path.split("\\").last();
int rownum = songTableWidget->rowCount();
songTableWidget->insertRow(rownum);
songTableWidget->setItem(rownum, 0, new QTableWidgetItem(fileName.split(".").front()));
songTableWidget->setItem(rownum, 1, new QTableWidgetItem(fileName.split(".").last()));
songTableWidget->setItem(rownum, 2, new QTableWidgetItem(QDir::toNativeSeparators(pathList.at(i))));
}
}
if (pathList.size() != 0)
{
initialName = pathList.at(0).left(pathList.at(0).lastIndexOf('/', -1));
emit isModified();
if (flag)
emit playlistAdded();
}   
}
void MyPlaylist::playListWindowHideOrShow()
{
if (isHidden())
{
move(frameGeometry().topRight());
show();
}
else
hide();
}
void MyPlaylist::changeMusicPlayList(int row)
{
if (row >= songTableWidget->rowCount())
return;
musicPlayList->setCurrentIndex(row);
}
void MyPlaylist::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
offset = event->globalPos() - frameGeometry().topLeft();
}
void MyPlaylist::mouseMoveEvent(QMouseEvent *event)
{
if (event->buttons() & Qt::LeftButton) {
setCursor(Qt::PointingHandCursor);
move(event->globalPos() - offset);
}
}
void MyPlaylist::sortButtonHideOrShow()
{
if (ascendingOrderButton->isHidden())
{
ascendingOrderButton->show();
descendingOrderButton->show();
}
else{
ascendingOrderButton->hide();
descendingOrderButton->hide();
}
}
void MyPlaylist::ascendingSortMusicFiles()
{
songTableWidget->sortItems(0, Qt::AscendingOrder);
emit isModified();
emit musicFilesChanged();
}
void MyPlaylist::descendingSortMusicFiles()
{
songTableWidget->sortItems(0, Qt::DescendingOrder);
emit isModified();
emit musicFilesChanged();
}
void MyPlaylist::setMusicPlaylist()
{
QString Q = musicPlayList->currentMedia().canonicalUrl().fileName(); 
musicPlayList->clear();
int index = 0;
emit playlistReduced();
for (int i = 0; i < songTableWidget->rowCount(); i++){
musicPlayList->addMedia(QUrl::fromLocalFile(songTableWidget->item(i, 2)->text()));
QString Q1 = songTableWidget->item(i, 0)->text() +'.'+ songTableWidget->item(i, 1)->text();
if (Q == Q1)
index = i;
}
musicPlayList->setCurrentIndex(index);
}
void MyPlaylist::savePlayList()
{
QString fileName = QFileDialog::getSaveFileName(this, QStringLiteral("另存为"), curFile, tr("(*.txt)"));
if (!fileName.isEmpty())
{
QFile file(fileName);
if (!file.open(QFile::WriteOnly | QFile::Text)){
QMessageBox::warning(this, QStringLiteral("听"), QStringLiteral("无法写入文件 %1:\n%2.").arg(fileName).arg(file.errorString()));
}
QTextStream out(&file);
QApplication::setOverrideCursor(Qt::WaitCursor);
for (int i = 0; i < songTableWidget->rowCount(); i++)
{
out << songTableWidget->item(i, 2)->text();
if (i < songTableWidget->rowCount() - 1)
out << endl;
}
QApplication::restoreOverrideCursor();
setCurrentFile(fileName);
}

}
void MyPlaylist::setCurrentFile(const QString &fileName)
{
// canonicalFilePath()可以除去路径中的符号链接,“.”和“..”等符号
curFile = QFileInfo(fileName).canonicalFilePath();
// 文档没有被更改过
saveAsPlayListButton->setDisabled(true);
}
void MyPlaylist::setSaveButtonEnabledOrNot()
{
saveAsPlayListButton->setEnabled(true);
}
void MyPlaylist::importPlayList()
{
QString playListFileName = QFileDialog::getOpenFileName(this, QStringLiteral("选择文件"), initialName, tr("(*.txt)"));
bool flag = false;
if (musicPlayList->isEmpty())
flag = true;
QFile file(playListFileName);
QString path;
if (!file.open(QFile::ReadOnly | QFile::Text))
QMessageBox::warning(this, QStringLiteral("听"), QStringLiteral("无法打开文件 %1:\n%2.").arg(playListFileName).arg(file.errorString()));
else{
QTextStream stream(&file);
int i =0;
while (!stream.atEnd()){
path = stream.readLine();
musicPlayList->addMedia(QUrl::fromLocalFile(path));
QString fileName = path.split("\\").last();
int rownum = songTableWidget->rowCount();
songTableWidget->insertRow(rownum);
songTableWidget->setItem(rownum, 0, new QTableWidgetItem(fileName.split(".").front()));
songTableWidget->setItem(rownum, 1, new QTableWidgetItem(fileName.split(".").last()));
songTableWidget->setItem(rownum, 2, new QTableWidgetItem(QDir::toNativeSeparators(path)));
i = i + 1;
}
if (i != 0){
initialName = path.left(path.lastIndexOf('/', -1));
emit isModified();
if (flag)
emit playlistAdded();
saveAsPlayListButton->setDisabled(true);
}
}
}

5、mySettings.h

#ifndef MYSETTINGS_H
#define MYSETTINGS_H


#include
#include
#include


class MySettings : public QWidget
{
Q_OBJECT
public:
explicit MySettings(QWidget *parent = 0);
~MySettings();
QPushButton *playPauseOrPlayButton;
QPushButton *playPrevious;
QPushButton *playNext;
QPushButton *playModeButton;
QPushButton *randomn;
QPushButton *allCycle;
QPushButton *singleCycle;
QPushButton *playVolumeButton;
QPushButton *playMuteButton;
QSlider * VolumeSlider;
private:
QPoint offset;
QWidget * modeSetting;
QWidget * volumeSetting;
QPushButton * closeButton;
protected:
void mousePressEvent(QMouseEvent *ev);
void mouseMoveEvent(QMouseEvent *ev);
private slots:
void modeSettingHideOrShow();
void volumeSettingHideOrShow();

};
#endif

6、mySettings.cpp

#include "mySettings.h"
#include


MySettings::MySettings(QWidget *parent) :
QWidget(parent)
{
 // setWindowTitle(QStringLiteral("音乐设置"));
setWindowFlags(Qt::Window | Qt::FramelessWindowHint);
  setWindowIcon(QIcon(":/images/myPlayer.png"));
  setAutoFillBackground(true);
  QPixmap im = QPixmap(":/images/musicCover_Default.jpg");
  QPalette palette;
palette.setBrush(QPalette::Background, QBrush(im.scaled(150,150)));
  setPalette(palette);
  resize(150, 150);
  setMaximumSize(150, 150);
  setMinimumSize(150, 150);
// 退出
closeButton = new QPushButton(this);
closeButton->setFixedSize(24, 24);
closeButton->move(124, 2);
closeButton->setFlat(true);
closeButton->setToolTip(QStringLiteral("关闭窗口"));
im = QPixmap(":/images/quit.png");
closeButton->setIconSize(QSize(20, 20));
closeButton->setIcon(im.scaled(20, 20));


// 暂停或播放
  playPauseOrPlayButton = new QPushButton(this); // (75,75) middle 各按键围成圆的半径为 40// 整体向右移20
playPauseOrPlayButton->setFixedSize(24, 24);
  playPauseOrPlayButton->move(43, 63);
  playPauseOrPlayButton->setIconSize(QSize(24, 24));
  playPauseOrPlayButton->setFlat(true); // 去边框
  playPauseOrPlayButton->setToolTip(QStringLiteral("播放"));
im = QPixmap(":/images/pause.png");
  playPauseOrPlayButton->setIcon(im.scaled(24, 24));
 
  // 播放前一首
  playPrevious = new QPushButton(this); // (35,75) left
playPrevious->setFixedSize(24, 24);
  playPrevious->setFlat(true);
  playPrevious->move(8, 63);
  playPrevious->setToolTip(QStringLiteral("上一首"));
  im = QPixmap(":/images/Previous.png");
  playPrevious->setIconSize(QSize(24, 24));
  playPrevious->setIcon(im.scaled(24, 24));
  // 播放下一首
  playNext = new QPushButton(this); // (115,75)  right
playNext->setFixedSize(24, 24);
  playNext->move(78, 63);
  playNext->setFlat(true);
  playNext->setToolTip(QStringLiteral("下一首"));
  im = QPixmap(":/images/next.png");
  playNext->setIconSize(QSize(24, 24));
  playNext->setIcon(im.scaled(24, 24));
// 播放模式选择
playModeButton = new QPushButton(this); // (75,35)  
playModeButton->setFixedSize(24,24);
playModeButton->move(43, 23);
  playModeButton->setFlat(true);
  playModeButton->setToolTip(QStringLiteral("循环播放"));
im = QPixmap(":/images/Loop.png");
  playModeButton->setIconSize(QSize(24, 24));
  playModeButton->setIcon(im.scaled(24, 24));
// 多模式选择按钮
  modeSetting = new QWidget(this);
  modeSetting->setWindowFlags(Qt::FramelessWindowHint);// 无边框
  modeSetting->setAutoFillBackground(true);
  modeSetting->setPalette(QPalette(QColor(100, 100, 100, 100)));
  modeSetting->resize(76, 24);
  modeSetting->move(69, 23);
  modeSetting->hide();
  // 多模式(随机)
  randomn = new QPushButton(modeSetting);
randomn->setFixedSize(24, 24);
  randomn->move(0, 0);
  randomn->setFlat(true);
  im = QPixmap(":/images/Random.png");
  randomn->setToolTip(QStringLiteral("随机播放"));
  randomn->setIconSize(QSize(24, 24));
  randomn->setIcon(im.scaled(24, 24));
  // 多模式(顺序+循环)
  allCycle = new QPushButton(modeSetting);
allCycle->setFixedSize(24, 24);
  allCycle->move(26, 0);
  allCycle->setFlat(true);
  im = QPixmap(":/images/Loop.png");
  allCycle->setToolTip(QStringLiteral("循环播放"));
  allCycle->setIconSize(QSize(24, 24));
  allCycle->setIcon(im.scaled(24, 24));
  // 多模式(单曲循环)
  singleCycle = new QPushButton(modeSetting);
singleCycle->setFixedSize(24, 24);
  singleCycle->move(52, 0);
  singleCycle->setFlat(true);
  im = QPixmap(":/images/CurrentLoop.png");
  singleCycle->setToolTip(QStringLiteral("单曲循环"));
  singleCycle->setIconSize(QSize(24, 24));
  singleCycle->setIcon(im.scaled(24, 24));
 
  // 音量按钮 及部件
  playVolumeButton = new QPushButton(this); // (75,115) down
playVolumeButton->setFixedSize(24, 24);
  playVolumeButton->move(43, 103);
  playVolumeButton->setFlat(true);
  im = QPixmap(":/images/Volume.png");
  playVolumeButton->setToolTip(QStringLiteral("音量调节"));
  playVolumeButton->setIconSize(QSize(24, 24));
  playVolumeButton->setIcon(im.scaled(24, 24));
  // 音量子部件按钮 音量条 静音
  volumeSetting = new QWidget(this);
  volumeSetting->setWindowFlags(Qt::FramelessWindowHint);// 无边框
  volumeSetting->setAutoFillBackground(true);
  volumeSetting->setPalette(QPalette(QColor(100, 100, 100, 100)));
  volumeSetting->resize(76, 24);
  volumeSetting->move(69, 103);
volumeSetting->hide();
  // 音量子部件(静音)
  playMuteButton = new QPushButton(volumeSetting); // 静音
playMuteButton->setFixedSize(20, 20);
  playMuteButton->move(0, 0);//  (2, 1)
  playMuteButton->setFlat(true);
  im = QPixmap(":/images/Volume.png");
  playMuteButton->setToolTip(QStringLiteral("静音"));
  playMuteButton->setIconSize(QSize(20, 20));
  playMuteButton->setIcon(im.scaled(20, 20));
  // 音量子部件(音量条)
  VolumeSlider = new QSlider(Qt::Horizontal, volumeSetting);
  VolumeSlider->setFixedSize(54, 10);
  VolumeSlider->setRange(0, 150);
  VolumeSlider->setValue(60);
  VolumeSlider->move(22, 7);


connect(closeButton, SIGNAL(clicked()), this, SLOT(hide()));
connect(playModeButton, SIGNAL(clicked()), this, SLOT(modeSettingHideOrShow()));
connect(playVolumeButton, SIGNAL(clicked()), this, SLOT(volumeSettingHideOrShow()));
}
MySettings::~MySettings()
{
delete playPauseOrPlayButton;
delete playPrevious;
delete playNext;
delete playModeButton;
delete randomn;
delete allCycle;
delete singleCycle;
delete playVolumeButton;
delete playMuteButton;
delete VolumeSlider;
delete modeSetting;
delete volumeSetting;
delete closeButton;
}
void MySettings::volumeSettingHideOrShow()
{
if (volumeSetting->isHidden())
volumeSetting->show();
else
volumeSetting->hide();
}
void MySettings::modeSettingHideOrShow()
{
if (modeSetting->isHidden())
modeSetting->show();
else
modeSetting->hide();
}
void MySettings::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
offset = event->globalPos() - frameGeometry().topLeft();
}
void MySettings::mouseMoveEvent(QMouseEvent *event)
{
if (event->buttons() & Qt::LeftButton) {
setCursor(Qt::PointingHandCursor);
move(event->globalPos() - offset);
}
}

7、musicPlayer.h

#ifndef MUSICPLAYER_H
#define MUSICPLAYER_H


#include "mySettings.h"
#include "myPlayList.h"
#include "myLyric.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include




class MusicPlayer : public QGraphicsView
{
Q_OBJECT


public:
MusicPlayer(QWidget *parent = 0);

~MusicPlayer();


private:
bool playListWidgetFlag;
bool optionFlag;
qint64 totalTimeValue;
QPoint offset;
QMediaPlayer * musicPlayer;
// 三大子块
MyPlaylist *playListWidget;
MySettings * option;
MyLyric *lrc;
QMap lrcMap;
// 主页背景
QGraphicsWidget *maskWidget;
QLabel * songInfoLabel;// 主页音乐信息显示
QSlider * DurationSlider;   QLabel * timeLabel;// 歌曲进度及时间显示
// 主页面5个设置按钮
QPushButton *LyricButton;
QPushButton *playListButton;
QPushButton *musicPlayerSettingButton;
QPushButton *BackToTrayButton;
QPushButton *QuitAppButton;
// 托盘
QSystemTrayIcon *trayIcon;
// 初始化音乐
void initMusicPlayer();
void resolveLrc(const QString &FileName); // 解析音乐文件


protected:
void mousePressEvent(QMouseEvent *ev);
void mouseMoveEvent(QMouseEvent *ev);


private slots:
// 进度条与音乐进步同步的3个槽
void setPosition(qint64);
void setDuration(qint64);
void setPlayPosition(int);
// 播放模式设置的6个槽
void setModeRandom();
void setModeSingleCycle();
void setModeAllCycle();
void setPlayPrevious();
void setPlayNext();
void setPlayOrPause();
// 三个子块是否显示的3个槽
void playListWindowHideOrShow();
void SettingsWindowHideOrShow();
void setLrcShown();
// 歌词同步的2个槽
void updateTime(qint64 position);
void toGetStateInfo();
// 播放列表更改响应的3个槽
void stopOrNot();
void start();
void MusicPlayListChanged();
    // 其他
void volumeStatusChange(); // 音量调节
void ShowMusicInfo(); // 显示音乐信息
void minimizeWindow(); // 最小化到托盘
void trayIconActivated(QSystemTrayIcon::ActivationReason activationReason);// 托盘激活
};


#endif // MUSICPLAYER_H

8、musicPlayer.cpp

#include "musicplayer.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include

MusicPlayer::MusicPlayer(QWidget *parent)
: QGraphicsView(parent)
{
this->setWindowIcon(QIcon(":/images/myPlayer.png"));
this->setFixedSize(300, 300);
playListWidgetFlag = false;
optionFlag = false;
this->setWindowFlags(Qt::Tool | Qt::X11BypassWindowManagerHint);
this->setWindowFlags(Qt::Window | Qt::FramelessWindowHint);
musicPlayer = new QMediaPlayer(this);
playListWidget = new MyPlaylist(this);
option = new MySettings(this);
option->hide();
lrc = new MyLyric(this);


songInfoLabel = new QLabel(this);
songInfoLabel->setFixedSize(280, 20);
songInfoLabel->move(10, 10);
songInfoLabel->setText(QStringLiteral("听"));
songInfoLabel->setStyleSheet("color:white");
QFont font;
font.setPointSize(12);
font.setBold(true);
songInfoLabel->setFont(font);
songInfoLabel->setAlignment(Qt::AlignCenter);


// 创建顶部标签,用于显示一些信息
trayIcon = new QSystemTrayIcon(QIcon(":/images/myPlayer.png"), this);
trayIcon->setToolTip(QStringLiteral("听"));
// 2个歌词同步
connect(musicPlayer, SIGNAL(positionChanged(qint64)), SLOT(updateTime(qint64)));
connect(musicPlayer, SIGNAL(metaDataChanged()), this, SLOT(ShowMusicInfo()));
// 3个播放列表同步
connect(musicPlayer, SIGNAL(currentMediaChanged(QMediaContent)), SLOT(MusicPlayListChanged()));
connect(playListWidget, SIGNAL(playlistReduced()), this, SLOT(stopOrNot()));
connect(playListWidget, SIGNAL(playlistAdded()), this, SLOT(start()));
// 6个播放模式调整
connect(option->playPauseOrPlayButton, SIGNAL(clicked()), this,SLOT(setPlayOrPause()));
connect(option->playNext, SIGNAL(clicked()), this, SLOT(setPlayNext()));
connect(option->playPrevious, SIGNAL(clicked()), this, SLOT(setPlayPrevious()));
connect(option->singleCycle, SIGNAL(clicked()), this, SLOT(setModeSingleCycle()));
connect(option->allCycle, SIGNAL(clicked()), this, SLOT(setModeAllCycle()));
connect(option->randomn, SIGNAL(clicked()), this, SLOT(setModeRandom()));
// 2个音量调节
connect(option->VolumeSlider, SIGNAL(valueChanged(int)), musicPlayer, SLOT(setVolume(int)));
connect(option->playMuteButton, SIGNAL(clicked()), this, SLOT(volumeStatusChange()));
//
initMusicPlayer();
}
MusicPlayer::~MusicPlayer()
{
delete musicPlayer;
// 三大子块
delete playListWidget;
delete option;
delete lrc;
// 主页背景
delete maskWidget;
delete songInfoLabel;// 主页音乐信息显示
delete DurationSlider;  
delete timeLabel;// 歌曲进度及时间显示
// 主页面5个设置按钮
delete LyricButton;
delete playListButton;
delete musicPlayerSettingButton;
delete BackToTrayButton;
delete QuitAppButton;
// 托盘
delete trayIcon;


}
void MusicPlayer::initMusicPlayer()
{
setRenderHint(QPainter::Antialiasing);
setCacheMode(CacheBackground);
setFixedSize(300, 300);
musicPlayer->setPlaylist(playListWidget->musicPlayList);
musicPlayer->play();
QGraphicsScene *scene = new QGraphicsScene;
scene->setSceneRect(2, 2, 296, 296);
QPixmap im = QPixmap(":/images/musicCover_Default.jpg");
scene->setBackgroundBrush(im.scaled(QSize(300, 300)));
setScene(scene);
// 加面罩
  QWidget * mask = new QWidget;
  mask->setAutoFillBackground(true);
  mask->setPalette(QPalette(QColor(120, 214, 255, 50)));
  mask->resize(300, 300);
  maskWidget = scene->addWidget(mask);
  maskWidget->setPos(0, 0);
// 设置其Z值为1,这样可以处于Z值为0的图形项上面
maskWidget->setZValue(1);
// 播放进程 显示与调节
DurationSlider = new QSlider(Qt::Horizontal, this);
DurationSlider->setFixedSize(200, 15);
DurationSlider->move(10, 260);
DurationSlider->setRange(0, 100);
connect(musicPlayer, SIGNAL(positionChanged(qint64)), this, SLOT(setPosition(qint64)));
connect(musicPlayer, SIGNAL(durationChanged(qint64)), this, SLOT(setDuration(qint64)));
connect(DurationSlider, SIGNAL(sliderMoved(int)), this, SLOT(setPlayPosition(int)));
// 播放进程 显示总时间及剩余时间
timeLabel = new QLabel(this);
timeLabel->setFixedSize(70, 15);
timeLabel->move(220, 260);
timeLabel->setStyleSheet("color:white");
timeLabel->setText(tr("00:00") + "/" + tr("00:00"));
timeLabel->setAlignment(Qt::AlignCenter);

// 歌词显示按钮
LyricButton = new QPushButton(this); // (192,108) right
LyricButton->setFixedSize(32, 32);
LyricButton->move(250, 32);
LyricButton->setFlat(true);
LyricButton->setToolTip(QStringLiteral("桌面歌词"));
im = QPixmap(":/images/Lyric.png");
LyricButton->setIconSize(QSize(32, 32));
LyricButton->setIcon(im.scaled(32, 32));
connect(LyricButton, SIGNAL(clicked()), this, SLOT(setLrcShown()));


// 显示播放列表按钮及部件
playListButton = new QPushButton(this); // (108,192) up-left
playListButton->setFixedSize(32, 32);
playListButton->move(250, 74);
playListButton->setFlat(true);
im = QPixmap(":/images/List.png");
playListButton->setToolTip(QStringLiteral("播放列表"));
playListButton->setIconSize(QSize(32, 32));
playListButton->setIcon(im.scaled(32, 32));


connect(playListButton, SIGNAL(clicked()), this, SLOT(playListWindowHideOrShow()));


// 设置面板
musicPlayerSettingButton = new QPushButton(this);
musicPlayerSettingButton->setFixedSize(32, 32);
musicPlayerSettingButton->move(250, 116);
musicPlayerSettingButton->setFlat(true);
im = QPixmap(":/images/Set.png");
musicPlayerSettingButton->setToolTip(QStringLiteral("设置"));
musicPlayerSettingButton->setIconSize(QSize(32, 32));
musicPlayerSettingButton->setIcon(im.scaled(32, 32));
connect(musicPlayerSettingButton, SIGNAL(clicked()), this, SLOT(SettingsWindowHideOrShow()));
// 最小化到托盘
BackToTrayButton = new QPushButton(this); // (108,108) up-left
BackToTrayButton->setFixedSize(32, 32);
BackToTrayButton->move(250, 158);
BackToTrayButton->setFlat(true);
im = QPixmap(":/images/Minimize.png");
BackToTrayButton->setToolTip(QStringLiteral("最小化"));
BackToTrayButton->setIconSize(QSize(32, 32));
BackToTrayButton->setIcon(im.scaled(32, 32));
connect(BackToTrayButton, SIGNAL(clicked()), this, SLOT(minimizeWindow()));// 最小化到托盘


// 退出程序
QuitAppButton = new QPushButton(this); // (192,192) down-right
QuitAppButton->setFixedSize(32, 32);
QuitAppButton->move(250, 200);
QuitAppButton->setFlat(true);
im = QPixmap(":/images/quit.png");
QuitAppButton->setToolTip(QStringLiteral("退出"));
QuitAppButton->setIconSize(QSize(32, 32));
QuitAppButton->setIcon(im.scaled(32, 32));
connect(QuitAppButton, SIGNAL(clicked()), qApp, SLOT(quit()));// 退出程序
// 托盘
trayIcon = new QSystemTrayIcon(QIcon(":/images/myPlayer.png"), this);
trayIcon->setToolTip(songInfoLabel->text());
// 创建菜单
QMenu *menu = new QMenu;
menu->addAction(QStringLiteral("退出"), qApp, SLOT(quit()));
trayIcon->setContextMenu(menu);
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason)));
trayIcon->show();
}
// 进度条
void MusicPlayer::setPosition(qint64 pos)
{
DurationSlider->setValue(pos);


QTime totalTime(0, (totalTimeValue / 60000) % 60, (totalTimeValue / 1000) % 60);
QTime currentTime(0, (pos / 60000) % 60, (pos / 1000) % 60);
QString str = currentTime.toString("mm:ss") + "/" + totalTime.toString("mm:ss");
timeLabel->setText(str);
}
void MusicPlayer::setDuration(qint64 duration)
{
DurationSlider->setRange(0, duration);
}
void MusicPlayer::setPlayPosition(int pos)
{
musicPlayer->setPosition(pos);
}
// 播放模式
void MusicPlayer::setPlayOrPause()
{
switch (musicPlayer->state())
{
case QMediaPlayer::State::PlayingState:{
  musicPlayer->pause();
  QPixmap im = QPixmap(":/images/play.png");
  option->playPauseOrPlayButton->setIcon(im.scaled(64, 64));
  option->playPauseOrPlayButton->setToolTip(QStringLiteral("暂停"));
}
break;
case QMediaPlayer::State::PausedState:{
 musicPlayer->play();
 QPixmap im = QPixmap(":/images/pause.png");
 option->playPauseOrPlayButton->setIcon(im.scaled(64, 64));
 option->playPauseOrPlayButton->setToolTip(QStringLiteral("播放"));
}
break;
default:
break;
}
}
void MusicPlayer::setPlayPrevious()
{
if (playListWidget->musicPlayList->currentIndex() == 0)
playListWidget->musicPlayList->setCurrentIndex(playListWidget->musicPlayList->mediaCount() - 1);
else playListWidget->musicPlayList->setCurrentIndex(playListWidget->musicPlayList->previousIndex());
musicPlayer->play();
}
void MusicPlayer::setPlayNext()
{
if (playListWidget->musicPlayList->currentIndex() == playListWidget->musicPlayList->mediaCount() - 1)
playListWidget->musicPlayList->setCurrentIndex(0);
else playListWidget->musicPlayList->setCurrentIndex(playListWidget->musicPlayList->nextIndex());
musicPlayer->play();
}
void MusicPlayer::setModeRandom()
{
QPixmap im = QPixmap(":/images/Random.png");
option->playModeButton->setIconSize(QSize(48, 48));
option->playModeButton->setIcon(im.scaled(48, 48));
option->playModeButton->setToolTip(QStringLiteral("随机播放"));
playListWidget->musicPlayList->setPlaybackMode(QMediaPlaylist::Random);
}
void MusicPlayer::setModeSingleCycle()
{
QPixmap im = QPixmap(":/images/CurrentLoop.png");
option->playModeButton->setIconSize(QSize(48, 48));
option->playModeButton->setIcon(im.scaled(48, 48));
option->playModeButton->setToolTip(QStringLiteral("单曲循环"));
playListWidget->musicPlayList->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop);
}
void MusicPlayer::setModeAllCycle()
{
QPixmap im = QPixmap(":/images/Loop.png");
option->playModeButton->setIconSize(QSize(48, 48));
option->playModeButton->setIcon(im.scaled(48, 48));
option->playModeButton->setToolTip(QStringLiteral("循环播放"));
playListWidget->musicPlayList->setPlaybackMode(QMediaPlaylist::Loop);
}
// 三大子块是否显示
void MusicPlayer::SettingsWindowHideOrShow()
{
if (option->isHidden())
{
option->move(frameGeometry().topRight());
option->show();
}
else
option->hide();
}
void MusicPlayer::playListWindowHideOrShow()
{
if (playListWidget->isHidden())
{
playListWidget->move(frameGeometry().topRight());
playListWidget->show();
}
else
playListWidget->hide();
}
void MusicPlayer::setLrcShown()
{
if (lrc->isHidden())
lrc->show();
else
lrc->hide();
}
// 歌词解析及同步
void MusicPlayer::toGetStateInfo()
{
switch (musicPlayer->state())
{
case QMediaPlayer::PlayingState:{
QString fileName = musicPlayer->metaData(QMediaMetaData::Title).toString()
+ " - " + musicPlayer->metaData(QMediaMetaData::Author).toString();
resolveLrc(fileName);
}
break;
case QMediaPlayer::StoppedState:
lrc->stopLrcMask();
lrc->setText(QStringLiteral("听"));
break;
case QMediaPlayer::PausedState:
if (!lrcMap.isEmpty()) {
lrc->stopLrcMask();
}
break;
default:
;
}
}
void MusicPlayer::resolveLrc(const QString &fileName)
{
lrcMap.clear();
if (fileName.isEmpty())
return;
QString lrcFileName = QDir::currentPath() + "/Lyrics/" + fileName + ".lrc";
QFile file(lrcFileName);
if (!file.open(QIODevice::ReadOnly)) {
lrc->setText(musicPlayer->metaData(QMediaMetaData::Title).toString()
+ " - " + musicPlayer->metaData(QMediaMetaData::Author).toString() + QStringLiteral(" --- 未找到歌词文件!"));
return;
}
QString allText = QTextCodec::codecForLocale()->toUnicode(file.readAll());
file.close();
QStringList lines = allText.split("\n");
QRegExp rx("\\[\\d{2}:\\d{2}\\.\\d{2}\\]");
foreach(QString oneLine, lines) {
QString temp = oneLine;
temp.replace(rx, "");
int pos = rx.indexIn(oneLine, 0);
while (pos != -1) {
QString cap = rx.cap(0);
QRegExp regexp;
regexp.setPattern("\\d{2}(?=:)");
regexp.indexIn(cap);
int minute = regexp.cap(0).toInt();
regexp.setPattern("\\d{2}(?=\\.)");
regexp.indexIn(cap);
int second = regexp.cap(0).toInt();
regexp.setPattern("\\d{2}(?=\\])");
regexp.indexIn(cap);
int millisecond = regexp.cap(0).toInt();
qint64 totalTime = minute * 60000 + second * 1000 + millisecond * 10;
lrcMap.insert(totalTime, temp);
pos += rx.matchedLength();
pos = rx.indexIn(oneLine, pos);
}
}
if (lrcMap.isEmpty()) {
lrc->setText(QStringLiteral(" 歌词文件内容错误!"));
return;
}
}
void MusicPlayer::updateTime(qint64 time)
{
if (!lrcMap.isEmpty())
{
qint64 prev = 0, next = 0;
foreach(qint64 value, lrcMap.keys())
{
if (time >= value)
prev = value;
else{
next = value;
break;
}
}
QString currentLrc = lrcMap.value(prev);
if (currentLrc.length() < 2)
currentLrc = windowTitle();
if (currentLrc != lrc->text())
{
lrc->setText(currentLrc);
qint64 intervalTime = next - prev;
lrc->startLrcMask(intervalTime);
}
}


}
// 播放列表同步
void MusicPlayer::MusicPlayListChanged()
{
musicPlayer->stop();
musicPlayer->play();


}
void MusicPlayer::stopOrNot()
{
if (playListWidget->musicPlayList->isEmpty())
{
musicPlayer->stop();
songInfoLabel->setText(QStringLiteral("听"));
}
}
void MusicPlayer::start()
{
musicPlayer->setPlaylist(playListWidget->musicPlayList);
musicPlayer->play();
}
// 其他
void MusicPlayer::volumeStatusChange()
{


if (musicPlayer->isMuted()){
QPixmap im = QPixmap(":/images/Volume.png");
option->playVolumeButton->setIcon(im.scaled(48, 48));
option->playMuteButton->setIcon(im.scaled(32, 32));
musicPlayer->setMuted(false);
}
else
{
QPixmap im = QPixmap(":/images/mute.png");
option->playVolumeButton->setIcon(im.scaled(48, 48));
option->playMuteButton->setIcon(im.scaled(32, 32));
musicPlayer->setMuted(true);
}
}
void MusicPlayer::ShowMusicInfo()
{
QString title = musicPlayer->metaData(QMediaMetaData::Title).toString();
QString artist = musicPlayer->metaData(QMediaMetaData::Author).toString();
totalTimeValue = musicPlayer->metaData(QMediaMetaData::Duration).toInt();
songInfoLabel->setText(title + " - " + artist);
toGetStateInfo();
lrc->setText(windowTitle());
int index = playListWidget->musicPlayList->currentIndex();
if (index == -1)
return;
playListWidget->songTableWidget->selectRow(index);
playListWidget->songTableWidget->setFocus();
}
// 窗体控制
void MusicPlayer::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
offset = event->globalPos() - frameGeometry().topLeft();
}
void MusicPlayer::mouseMoveEvent(QMouseEvent *event)
{
if (event->buttons() & Qt::LeftButton) {
setCursor(Qt::PointingHandCursor);
move(event->globalPos() - offset);
}
}
void MusicPlayer::minimizeWindow()
{
hide();
if (!playListWidget->isHidden())
{
playListWidget->hide();
playListWidgetFlag = true;
}
else
playListWidgetFlag = false;
if (!option->isHidden()){
option->hide();
optionFlag = true;
}
else
optionFlag = false;


}
void MusicPlayer::trayIconActivated(QSystemTrayIcon::ActivationReason activationReason)
{
if (activationReason == QSystemTrayIcon::Trigger) {
show();
if (playListWidgetFlag)
playListWidget->show();
if (optionFlag)
option->show();
}
}

9、main.cpp

#include "musicplayer.h"
#include "mySettings.h"
#include


int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MusicPlayer w;
w.show();
return a.exec();
}

你可能感兴趣的:(Qt_Explor,code)