帮我写一个基于C++和QT的音乐播放器
时间: 2023-03-21 09:03:35 浏览: 129
C++开发基于Qt的音乐播放器的设计与实现项目源码+项目使用说明(毕业设计).zip
5星 · 资源好评率100%
好的,我可以回答这个问题。下面是一个基于C和QT的音乐播放器的示例代码:
```
#include <QtGui>
#include <QtWidgets>
#include <QtCore>
#include <phonon>
class MusicPlayer : public QWidget
{
Q_OBJECT
public:
MusicPlayer(QWidget *parent = 0);
private slots:
void openFile();
void play();
void pause();
void stop();
void seek(int seconds);
void updatePosition(qint64 position);
void updateDuration(qint64 duration);
private:
QMediaPlayer *player;
QSlider *positionSlider;
QLabel *positionLabel;
QLabel *durationLabel;
QPushButton *playButton;
QPushButton *pauseButton;
QPushButton *stopButton;
};
MusicPlayer::MusicPlayer(QWidget *parent)
: QWidget(parent)
{
QGridLayout *layout = new QGridLayout(this);
positionSlider = new QSlider(Qt::Horizontal, this);
positionSlider->setRange(0, 0);
positionSlider->setToolTip(tr("Position"));
connect(positionSlider, SIGNAL(sliderMoved(int)), this, SLOT(seek(int)));
layout->addWidget(positionSlider, 0, 0, 1, 3);
positionLabel = new QLabel(this);
positionLabel->setMinimumWidth(50);
positionLabel->setText("00:00");
layout->addWidget(positionLabel, 1, 0);
durationLabel = new QLabel(this);
durationLabel->setMinimumWidth(50);
durationLabel->setText("00:00");
layout->addWidget(durationLabel, 1, 2);
playButton = new QPushButton(tr("Play"), this);
connect(playButton, SIGNAL(clicked()), this, SLOT(play()));
layout->addWidget(playButton, 2, 0);
pauseButton = new QPushButton(tr("Pause"), this);
connect(pauseButton, SIGNAL(clicked()), this, SLOT(pause()));
layout->addWidget(pauseButton, 2, 1);
stopButton = new QPushButton(tr("Stop"), this);
connect(stopButton, SIGNAL(clicked()), this, SLOT(stop()));
layout->addWidget(stopButton, 2, 2);
player = new QMediaPlayer(this);
connect(player, SIGNAL(positionChanged(qint64)), this, SLOT(updatePosition(qint64)));
connect(player, SIGNAL(durationChanged(qint64)), this, SLOT(updateDuration(qint64)));
}
void MusicPlayer::openFile()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), QDir::homePath());
if (!fileName.isEmpty()) {
player->setMedia(QUrl::fromLocalFile(fileName));
playButton->setEnabled(true);
durationLabel->setText(QString::fromStdString(std::to_string(player->duration() / 1000 / 60) + ":" + std::to_string(player->duration() / 1000 % 60)));
}
}
void MusicPlayer::play()
{
player->play();
playButton->setEnabled(false);
pauseButton->setEnabled(true);
stopButton->setEnabled(true);
}
void MusicPlayer::pause()
{
player->pause();
playButton->setEnabled(true);
pauseButton->setEnabled(false);
}
void MusicPlayer::stop()
{
player->stop();
playButton->setEnabled(true);
pauseButton->setEnabled(false);
stopButton->setEnabled(false);
positionSlider->setValue(0);
}
void MusicPlayer::seek(int seconds)
{
player->setPosition(seconds * 1000);
}
void MusicPlayer::updatePosition(qint64 position)
{
positionLabel->setText(QString::fromStdString(std::to_string(position
阅读全文