qt循环播放背景音乐
时间: 2023-10-09 08:16:04 浏览: 69
你可以使用Qt框架的QMediaPlayer和QMediaPlaylist类来实现循环播放背景音乐。首先,在你的头文件(bgmusic.h)中包含QMediaPlayer和QMediaPlaylist类,并创建一个继承自QThread的bgmusic类。在这个类中,你可以使用QMediaPlayer和QMediaPlaylist类来管理音乐的播放和循环。在run方法中,你可以调用player的play方法来开始播放背景音乐。在初始化bgmusic对象时,你可以添加音乐文件到playerList中,并设置播放模式为循环播放。最后,你可以通过调用start方法来启动bgmusic对象的线程,从而开始循环播放背景音乐。下面是一个bgmusic类的示例实现:
引用:
```cpp
#ifndef BGMUSIC_H
#define BGMUSIC_H
#include <QThread>
#include <QMediaPlayer>
#include <QMediaPlaylist>
class bgmusic : public QThread
{
Q_OBJECT
public:
bgmusic();
protected:
void run() override;
private:
QMediaPlayer* player;
QMediaPlaylist* playerList;
};
#endif // BGMUSIC_H
```
引用:
```cpp
#include "bgmusic.h"
bgmusic::bgmusic()
{
playerList = new QMediaPlaylist();
player = new QMediaPlayer();
playerList->addMedia(QUrl("qrc:/res/LevelWinSound.wav"));
playerList->addMedia(QUrl("qrc:/res/TapButtonSound.wav"));
playerList->setPlaybackMode(QMediaPlaylist::Loop);
playerList->setCurrentIndex(0);
player->setPlaylist(playerList);
player->setVolume(100);
}
void bgmusic::run()
{
player->play();
}
```
现在,你可以在需要播放背景音乐的地方创建一个bgmusic对象,并调用其start方法来启动循环播放背景音乐。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)