I wanted to make a music player, and I'm playing the audio files via the vlc module. I used this code to play the file:
import vlc
p = vlc.MediaPlayer("music/song.mp3")
p.play()
in the python shell, it works fine and plays the file. if I try to use a file and run it, it just exits without playing anything.
play()
starts playing music in separated thread so in main thread you can run other code - ie. you can create GUI with buttons to control music, or display animation for this music. But if you don't run other code - like input()
- then it ends script and it ends Python and it stops thread with music.
You have to run some code in main thread to keep running Python and then thread with play music.
It can be even while True: pass
instead of input()
.
In example I use p.is_playing()
to run while
-loop until it ends music.
import vlc
import time
p = vlc.MediaPlayer("music/song.mp3")
p.play()
print('is_playing:', p.is_playing()) # 0 = False
time.sleep(0.5) # sleep because it needs time to start playing
print('is_playing:', p.is_playing()) # 1 = True
while p.is_playing():
time.sleep(0.5) # sleep to use less CPU
In Python shell
you run Python
all time so it can run thread with music all time.
EDIT:
Example which uses tkinter
to display window with button Exit
. Because windows is displayed all time so separated thread can play music all time.
import vlc
import tkinter as tk
p = vlc.MediaPlayer("music/song.mp3")
p.play()
def on_click():
p.stop() # stop music
root.destroy() # close tkinter window
root = tk.Tk()
button = tk.Button(root, text="Exit", command=on_click)
button.pack()
root.mainloop()
Using tkinter
you can build player.
vlc
has few more complex examples how to use vlc
with different GUIs
https://git.videolan.org/?p=vlc/bindings/python.git;a=tree;f=examples;hb=HEAD
Function is_playing() I found in documentation for MediaPlayer