Although the playback is done asynchronously, you must keep running the process that creates the instance of the player while the playback does not end.
Your problem is that after the sleep
the Python process has nothing more to do and it ends, also ending the playback. You have several options, my preferred for flexibility is to use vlc.MediaListPlayer.get_state
that allows you to know the status of the player at any time, returns an instance of vlc.State
and you can compare by:
╔════════════════╦══════════════════════════╗
║ ESTADO ║ VALOR ║
╠════════════════╬══════════════════════════╣
║ Buffering ║ vlc.State.Buffering ║
╠════════════════╬══════════════════════════╣
║ Error ║ vlc.State.Error ║
╠════════════════╬══════════════════════════╣
║ Ended ║ vlc.State.Ended ║
╠════════════════╬══════════════════════════╣
║ NothingSpecial ║ vlc.State.NothingSpecial ║
╠════════════════╬══════════════════════════╣
║ Opening ║ vlc.State.Opening ║
╠════════════════╬══════════════════════════╣
║ Paused ║ vlc.State.Paused ║
╠════════════════╬══════════════════════════╣
║ Playing ║ vlc.State.Playing ║
╠════════════════╬══════════════════════════╣
║ Stopped ║ vlc.State.Stopped ║
╚════════════════╩══════════════════════════╝
Simplifying you can do this:
import vlc
import time
instance = vlc.Instance()
player = instance.media_player_new()
media = instance.media_new('1.mp3')
player.set_media(media)
player.play()
while player.get_state() != vlc.State.Ended:
time.sleep(1) # Solo para evitar un uso innecesario de CPU
Another option is to use vlc.MediaListPlayer.is_playing
that returns 1/True
if the player is playing something and 0/False
otherwise:
import vlc
import time
instance = vlc.Instance()
player = instance.media_player_new()
media = instance.media_new('1.mp3')
player.set_media(media)
player.play()
time.sleep(5) # Dar un tiempo prudencial para que la reproducción inicie.
while player.is_playing():
time.sleep(1)
The idea is that the process does not end before finishing the reproduction, the medium will depend on what you want to do and how you implement it. For example, if you are going to create a graphical interface and the instance of the player is done in the same process as the GUI you will not need any of this, since the process does not end until you close the interface thanks to the mainloop of it. / p>