aboutsummaryrefslogtreecommitdiffstats
path: root/AudioPlayer.py
blob: 8bf66e64bfb5a127cdc28f1489026178851a367e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# Soundboard Engine - customizable soundboard
# Copyright (C) 2026  Vidhu Kant Sharma <vidhukant@vidhukant.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

from PySide6.QtCore import QObject, QUrl, Signal
from PySide6.QtMultimedia import QAudioOutput, QMediaPlayer

from Soundboard import SoundboardSound


class PlayerStatus:
    def __init__(self, sound, status):
        self.sound = sound
        self.status = status


class AudioPlayer(QObject):
    status_updated = Signal(PlayerStatus)

    def __init__(self, parent=None):
        super().__init__(parent)

        self.status = PlayerStatus(SoundboardSound("", ""), "STOPPED")
        self.player = QMediaPlayer(self)
        self.audio_output = QAudioOutput(self)
        self.player.setAudioOutput(self.audio_output)

        self.player.mediaStatusChanged.connect(self._on_media_status_changed)
        self.player.playbackStateChanged.connect(self._on_state_changed)

    def play_sound(self, sound):
        if not sound or not sound.path:
            return

        self.status.sound = sound
        self.player.setSource(QUrl.fromLocalFile(self.status.sound.path))
        self.audio_output.setVolume(1.0)
        self.status.status = "PLAYING"
        self.player.play()

    def stop_sound(self):
        self.player.stop()

    def _on_media_status_changed(self, status):
        if status == QMediaPlayer.MediaStatus.EndOfMedia:
            self.status.status = "STOPPED"

        self.status_updated.emit(self.status)

    def _on_state_changed(self, state):
        if state == QMediaPlayer.PlaybackState.PlayingState:
            self.status.status = "PLAYING"
        elif state == QMediaPlayer.PlaybackState.StoppedState:
            self.status.status = "STOPPED"

        self.status_updated.emit(self.status)