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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM