写一个QT的音乐播放器
时间: 2023-03-23 17:02:24 浏览: 172
用QT C++编写简单的音乐播放器用QT 编写具有基本功能的音乐播放器
5星 · 资源好评率100%
好的,下面是一个使用QT实现的简单的音乐播放器的代码:
```
#include <QApplication>
#include <QWidget>
#include <QPushButton>
#include <QVBoxLayout>
#include <QFileDialog>
#include <QMediaPlayer>
#include <QSlider>
#include <QLabel>
class MusicPlayer : public QWidget
{
public:
MusicPlayer(QWidget *parent = 0);
~MusicPlayer();
private slots:
void openFile();
void playFile();
void pauseFile();
void stopFile();
void changeVolume(int volume);
private:
QPushButton *openButton;
QPushButton *playButton;
QPushButton *pauseButton;
QPushButton *stopButton;
QSlider *volumeSlider;
QLabel *titleLabel;
QMediaPlayer *player;
};
MusicPlayer::MusicPlayer(QWidget *parent)
: QWidget(parent)
{
openButton = new QPushButton(tr("打开"));
playButton = new QPushButton(tr("播放"));
pauseButton = new QPushButton(tr("暂停"));
stopButton = new QPushButton(tr("停止"));
volumeSlider = new QSlider(Qt::Horizontal);
titleLabel = new QLabel(tr("请选择音乐文件"));
player = new QMediaPlayer(this);
connect(openButton, SIGNAL(clicked()), this, SLOT(openFile()));
connect(playButton, SIGNAL(clicked()), this, SLOT(playFile()));
connect(pauseButton, SIGNAL(clicked()), this, SLOT(pauseFile()));
connect(stopButton, SIGNAL(clicked()), this, SLOT(stopFile()));
connect(volumeSlider, SIGNAL(valueChanged(int)), this, SLOT(changeVolume(int)));
connect(player, SIGNAL(metaDataChanged()), this, SLOT(updateTitle()));
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(titleLabel);
layout->addWidget(openButton);
layout->addWidget(playButton);
layout->addWidget(pauseButton);
layout->addWidget(stopButton);
layout->addWidget(volumeSlider);
setLayout(layout);
}
MusicPlayer::~MusicPlayer()
{
}
void MusicPlayer::openFile()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("打开文件"), QDir::homePath(), tr("音乐文件 (*.mp3 *.wav)"));
if (!fileName.isEmpty()) {
player->setMedia(QUrl::fromLocalFile(fileName));
titleLabel->setText(QFileInfo(fileName).fileName());
}
}
void MusicPlayer::playFile()
{
player->play();
}
void MusicPlayer::pauseFile()
{
player->pause();
}
void MusicPlayer::stopFile()
{
player->stop();
}
void MusicPlayer::changeVolume(int volume)
{
player->setVolume(volume);
}
void MusicPlayer::updateTitle()
{
titleLabel->setText(player->metaData(QMediaMetaData::Title).toString());
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MusicPlayer player;
player.show();
return app.exec();
}
```
这个播放器包括打开、播放、暂停、停止、调节音量和显示歌曲标题等功能。你可以通过 `QFileDialog` 打开音乐文件,然后使用 `QMediaPlayer` 播放音乐。同时,你还可以使用 `QSlider` 控件来调节音量大小,并且在播放时显示歌曲标题。
阅读全文