pygame.mixer PyQt5 threading子线程 播放 停止按钮 具体代码
时间: 2023-08-23 07:05:58 浏览: 164
以下是一个使用 PyQt5 和 threading 模块来实现在子线程中播放音乐,并且在主线程中可以通过按钮控制音乐播放和停止的示例代码:
```python
import sys
import threading
import time
import pygame
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(100, 100, 250, 100)
self.setWindowTitle("音乐播放器")
self.play_button = QPushButton("播放", self)
self.play_button.move(30, 30)
self.play_button.clicked.connect(self.play_music)
self.stop_button = QPushButton("停止", self)
self.stop_button.move(150, 30)
self.stop_button.clicked.connect(self.stop_music)
self.show()
def play_music(self):
self.thread = threading.Thread(target=self.play_music_thread)
self.thread.start()
def play_music_thread(self):
pygame.mixer.init()
pygame.mixer.music.load("music.mp3")
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
time.sleep(1)
def stop_music(self):
pygame.mixer.music.stop()
self.thread.join()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec_())
```
这个示例程序创建了一个主窗口,其中包含两个按钮,一个用于播放音乐,另一个用于停止音乐。当点击播放按钮时,程序会在子线程中使用 pygame 模块播放音乐,并且在主线程中不会被阻塞,可以继续执行其他任务。当点击停止按钮时,程序会停止音乐并且等待子线程结束。需要注意的是,直接调用 pygame.mixer.music.stop() 会导致音乐播放线程被阻塞,所以需要在停止音乐时等待子线程结束。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20210720083447.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)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)