https://img-blog.csdnimg.cn/32db9ce43ef64316a2e37a31f4cee033.gif
编程小鱼酱yu612.com,点击前往

Qt 播放 QSound和QMediaPlayer

在.pro文件中
追加
QT += multimedia

QSound::play(url);
用于简短声音的播放,要求格式wav

QMediaPlayer就是我们可以用做播放器 API的哦。
代码路径:
包含了很多的小例子,可以给我个星哦。
https://github.com/hiwoshixiaoyu/Qt-Demo
L
ibAudio.h

#ifndef LIBAUDIO_H
#define LIBAUDIO_H

#include "common.h"


#include <QMediaPlayer>
#include <QMediaPlaylist>
class LibAudio
{
public:
    LibAudio();
     virtual ~LibAudio();
    //播放简短音乐 wav格式
    void playSound(QString url);

    //播放其它格式音乐
    QT_RESULT playMusic(QString url,bool isRepeat=false);
    QT_RESULT pauseMusic();
    QT_RESULT continueMusic();
    QT_RESULT stopMusic();

private:
    QMediaPlayer musicPlayer;
    QMediaPlaylist  playlist;
};

#endif // LIBAUDIO_H

LibAudio.cpp

#include "LibAudio.h"
#include <QSound>


IMPLEMENT_SINGLETON(LibAudio)

LibAudio::LibAudio()
{
    //设置音量
     musicPlayer.setVolume(80);
}

LibAudio::~LibAudio()
{

}



void LibAudio::playSound(QString url)
{
    QSound::play(url);
    return;
}


QT_RESULT LibAudio::playMusic(QString url, bool isRepeat)
{
    if(isRepeat)
    {
        playlist.clear();
        playlist.addMedia(QUrl(url));
        playlist.setCurrentIndex(1);
        playlist.setPlaybackMode(QMediaPlaylist::CurrentItemInLoop);
        musicPlayer.setPlaylist(&playlist);
        musicPlayer.play();
        return QT_SUCCESS;
    }

    musicPlayer.setMedia(QUrl::fromLocalFile(url));
    musicPlayer.play();
    return QT_SUCCESS;
}

QT_RESULT LibAudio::pauseMusic()
{
    musicPlayer.pause();
    return QT_SUCCESS;
}

QT_RESULT LibAudio::continueMusic()
{
    musicPlayer.play();
    return QT_SUCCESS;
}

QT_RESULT LibAudio::stopMusic()
{
    musicPlayer.stop();
    return QT_SUCCESS;
}

posted @ 2018-11-27 08:57  鱼酱  阅读(3834)  评论(0编辑  收藏  举报

https://img-blog.csdnimg.cn/32db9ce43ef64316a2e37a31f4cee033.gif
编程小鱼酱yu612.com,点击前往