使用QT播放音频文件的几种方法:QSound、QSoundEffect、QMediaPlayer

一、环境介绍

QT版本:   QT5.12

操作系统: ubuntu18.04  、Windows10

使用QT的音频相关的类,需要在QT的pro工程文件里加入:  QT += multimedia

二、使用QSound播放WAV格式音频文件(未压缩的音频文件):最简单的播放方式

2.1 静态方法播放:  这种方法会自己创建一个子线程在后台播放,比较适合在主线程里调用,子线程里调用该函数播放音频文件会报警告: 。QObject: Cannot create children for a parent that is in a different thread.
(Parent is QApplication(0x7ffc5e9f21f0), parent's thread is QThread(0x55ddf74113e0), current thread is QThread(0x7ffc5ebb6588)

#include <QSound>
//文件的路径可以是资源文件路径也可以是本地文件系统路径
QSound::play("/mnt/hgfs/linux-share-dir/666.wav");

2.2 加载文件播放

#include <QSound>   
QSound *bells =new QSound("/mnt/hgfs/linux-share-dir/666.wav");
bells->play();

三、使用QSoundEffect播放WAV格式音频文件(未压缩的音频文件):适合提示音

#include <QSoundEffect>
QSoundEffect *effect=new QSoundEffect;
effect->setSource(QUrl::fromLocalFile("/mnt/hgfs/linux-share-dir/666.wav"));
effect->setLoopCount(1);  //循环次数
effect->setVolume(0.25f); //音量  0~1之间
effect->play();

四、使用QMediaPlayer播放音频文件: 适合做音乐播放器

4.1 播放wav格式音频文件

#include <QMediaPlayer>
QMediaPlayer *player = new QMediaPlayer;
player->setMedia(QUrl::fromLocalFile("/mnt/hgfs/linux-share-dir/666.wav"));
player->setVolume(50); //0~100音量范围,默认是100
player->play();

4.2 播放mp3格式音频文件

    #include <QMediaPlayer>
    QMediaPlayer *player = new QMediaPlayer;
    //播放进度的信号提示
    connect(player, SIGNAL(positionChanged(qint64)), this, SLOT(positionChanged(qint64)));
    player->setMedia(QUrl::fromLocalFile("/mnt/hgfs/linux-share-dir/xiaotiaowa.mp3"));
    player->setVolume(50); //0~100音量范围,默认是100
    player->play();

猜你喜欢

转载自blog.csdn.net/xiaolong1126626497/article/details/105629500