2

I have a code and this is part of it:

import PySimpleGUI as sg
import pygame

class Music:

    def __init__(self, file):
        self.sound = file

    def play(self):
        pygame.init()
        pygame.mixer.init()
        pygame.mixer.music.load(self.sound)
        pygame.mixer.music.play()

    def volchange(volume):
        pygame.mixer.music.set_volume(volume)  # The set_volume range is from 0.00 to 1.00 (every 0.01)

    def isplaying():
        return pygame.mixer.music.get_busy()

layout = [
    [sg.Button('Play'), 
     sg.Slider(key = 'volume', range=(0, 100), 
     orientation='h', size=(10, 15), default_value= 100)]
]

window = sg.Window('Help me', layout)

while True:
    event, values = window.read()
    if event == 'Play':
        path = "song.mp3"
        music = Music(path)
        music.play()
    if Music.isplaying():
        Music.volchange(float(values['volume'] / 100))

I want the volume of the audio to change in real time when I'm moving the slider. When I'm putting

if = Music.isplaying():
    Music.volchange(values['volume'] / 100)

into the loop while True: nothing works. But as I noticed, this loop keeps running every time the "Play" button is pressed. How can I set the isplaying check in the loop so that it will be worked all the time?

P.S. I try my best with English.

Cous
  • 198
  • 1
  • 7

1 Answers1

0

The slider doesn't raise events, if they are not enabled by enable_events = True.
Your application waits until the play button is pressed. See Slider Element.

layout = [
    [sg.Button('Play'), 
     sg.Slider(key = 'volume', range=(0, 100), 
     orientation='h', size=(10, 15), default_value= 100, 
     enable_events = True)] # <--- enable slider moved event
]
Rabbid76
  • 202,892
  • 27
  • 131
  • 174