'Volume slider in Tkinter with PyDub
Usually with audio you would access volume with: sound.volume = 10 However with Pydub, the volume is accessed using: sound + 10 The problem with this as I cannot exactly 'set' the volume, just adjust the volume that the song is currently at. I would like to create a Tkinter slider that I can vary between not hearable and loud. This is what I have so far:
root = tk.Tk()
root.geometry("500x500")
song1 = AudioSegment.from_file("./song.mp3")
def current_value(event):
song1 + slider.get()
#song1.volume = event
print(event)
slider = ttk.Scale(root, from_=-50, to=50, orient="horizontal",command=current_value)
slider.place(rely=.5, relx=.5)
def play_music(song):
play(song)
thread1 = threading.Thread(target=play_music, args=(song1,))
thread1.start()
root.mainloop()
#This mostly just lags the audio file
Solution 1:[1]
fixed with:
from pycaw.pycaw import AudioUtilities
class AudioController:
def __init__(self, process_name):
self.process_name = process_name
self.volume = self.process_volume()
def process_volume(self):
sessions = AudioUtilities.GetAllSessions()
for session in sessions:
interface = session.SimpleAudioVolume
if session.Process and session.Process.name() == self.process_name:
#print("Volume:", interface.GetMasterVolume()) # debug
return interface.GetMasterVolume()
def set_volume(self, decibels):
sessions = AudioUtilities.GetAllSessions()
for session in sessions:
interface = session.SimpleAudioVolume
if session.Process and session.Process.name() == self.process_name:
# only set volume in the range 0.0 to 1.0
self.volume = min(1.0, max(0.0, decibels))
interface.SetMasterVolume(self.volume, None)
#print("Volume set to", self.volume) # debug
def volume_slider_controller(event):
audio_controller = AudioController("python.exe") #will need to be punge.exe
audio_controller.set_volume(float(event))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | NedNoodleHead |