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 
#include 
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 


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;
}

你可能感兴趣的:(#,[,Qt,])