QT5 内置Multimedia开发音乐播放器

QT内置的Multimedia把播放器的功能基本都封装了,所以开发起来非常快。我自己参考官方文档和网上的资料做一个自己用。

最简单 的播放器,只有播放,暂停,停止功能,还有打开音乐文件的功能。

新建一个QT Widgets Application, 

打开项目目录下的.pro文件,开头的

QT += core gui 后面加上 multimedia。

打开forms目录下的mainwindow.ui

 

 

默认的窗口下添加3个按钮,分别为播放,停止,打开文件,

对应的ObjectName和后面实现的方法名有关,我自己分别命名为playButton,stopButton,selectFile。

打开headers目录下的mainwindow.h文件,开头添加引入

#include <QSoundEffect>
#include <QMediaPlayer>

class MainWindow中添加方法变量

private slots:
    void on_playButton_clicked(); //一个按键实现播放暂停两个操作
    void on_stopButton_clicked(); //一个按键实现停止操作
    void on_selectFile_clicked(); //选取文件

private:
    Ui::MainWindow *ui;
    QMediaPlayer *voi; //要播放的文件指针
    bool isPlay = false; //判断按键的状态

修改后如下

...

#include <QMainWindow>
#include <QSoundEffect>
#include <QMediaPlayer>

...class MainWindow : public QMainWindow
{
    Q_OBJECT

...private slots:
    void on_playButton_clicked(); 
    void on_stopButton_clicked(); 
    void on_selectFile_clicked(); 

private:
    Ui::MainWindow *ui;
    QMediaPlayer *voi; 
    bool isPlay = false; 
};

...

 

打开sources目录下的mainwindow.cpp文件,把头文件的功能实现

#include <QFileDialog>
#include <QDebug>
#include <QMessageBox>

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("音乐播放器");
    voi = new QMediaPlayer();
 
    qDebug("voi ready");
    ui->playButton->setEnabled(false);

}

MainWindow::~MainWindow()
{
    delete ui;
}


//一个按键实现播放暂停两个操作
void MainWindow::on_playButton_clicked()
{
    //如果没有在播放
    if(this->isPlay)
    {
        voi->pause();
        qDebug("voi pause");
        this->ui->playButton->setText(tr("播放"));
        this->isPlay = !this->isPlay;
    }
    else  //如果没有在播放
    {
        voi->play();
        qDebug("voi play");
        this->ui->playButton->setText(tr("暂停"));
        this->isPlay = !this->isPlay;
    }
}

//一个按键实现停止操作
void MainWindow::on_stopButton_clicked()
{
    //如果没有在播放
    if(this->isPlay)
    {
        voi->stop();
        qDebug("voi stop");
        this->ui->playButton->setText(tr("播放"));
        this->isPlay = !this->isPlay;
    }

}

//选取要播放的音乐文件
void MainWindow::on_selectFile_clicked()
{
    //筛选文件,只能选择mp3或wav格式的文件
    QUrl path = QFileDialog::getOpenFileUrl(this, tr("请选择音乐"), QUrl("c:/"), "music(*.mp3 *.wav)" );

    //选取文件后自动播放
    if(!path.isEmpty())
    {
        qDebug("file ready");
        voi->setMedia(path);
        ui->playButton->setEnabled(true);

        voi->play();
        qDebug("voi play");
        this->ui->playButton->setText(tr("暂停"));
        this->isPlay = !this->isPlay;
    }
}

参考文章 https://zhuanlan.zhihu.com/p/113188097

posted @ 2020-06-08 22:30  hanzhang  阅读(1590)  评论(0编辑  收藏  举报