pyqt5 Audio play

햄스터아저씨·2023년 6월 20일
0

gen by GPT4

import sys
import os
from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QCheckBox
from PyQt5.QtMultimedia import QMediaPlayer, QMediaContent

class AudioPlayer(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Audio Player")
        self.resize(300, 200)
        self.setAcceptDrops(True)
        
        btn = QPushButton("Play", self)
        btn.clicked.connect(self.playAudio)
        btn.move(100, 40)  # Move button to a desired position within the widget
        
        self.muteCheckBox = QCheckBox("Mute", self)
        self.muteCheckBox.move(100, 80)
        self.muteCheckBox.stateChanged.connect(self.toggleMute)

        self.mediaPlayer = QMediaPlayer()
        self.playCount = 0
        self.mediaPlayer.mediaStatusChanged.connect(self.checkMediaStatus)

    def playAudio(self):
        self.playCount = 0  # Reset play count
        path = os.path.join(os.path.dirname(__file__), "alarm.mp3")
        if not os.path.exists(path):
            print("File not found:", path)
            return

        url = QUrl.fromLocalFile(path)
        content = QMediaContent(url)
        self.mediaPlayer.setMedia(content)
        self.mediaPlayer.play()

    def checkMediaStatus(self, status):
        if status == QMediaPlayer.EndOfMedia:
            self.playCount += 1
            if self.playCount < 3:
                self.mediaPlayer.play()
    
    def toggleMute(self, state):
        self.mediaPlayer.setMuted(state)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    player = AudioPlayer()
    player.show()
    sys.exit(app.exec_())
profile
서버도 하고 웹도 하고 시스템이나 인프라나 네트워크나 그냥 다 함.

0개의 댓글