Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait until a sound file ends in vlc in Python 3.6

Tags:

python-3.x

I have a question in vlc in python

import vlc

sound = vlc.MediaPlayer('sound.mp3')

sound.play()

# i wanna wait until the sound ends then do some code without 
time.sleep()
like image 859
Moustafa Mahmoud Avatar asked Mar 06 '18 23:03

Moustafa Mahmoud


People also ask

How do I download a Python module from VLC?

In order to install the VLC module in Python, we will use the pip installer following the command shown below: Syntax: $ pip install python-vlc.

How do I install Python with VLC?

The preferred way to install python-vlc should be using the PyPI version, with the command pip install python-vlc . You also have the option to install the (single file) module from here, or from the git repository. The code repository is available on videolan and also on Github.


Video Answer


3 Answers

import time, vlc

def Sound(sound):
    vlc_instance = vlc.Instance()
    player = vlc_instance.media_player_new()
    media = vlc_instance.media_new(sound)
    player.set_media(media)
    player.play()
    time.sleep(1.5)
    duration = player.get_length() / 1000
    time.sleep(duration)

After edit

That exactly what I wanted, thanks everyone for helping me ..

like image 113
Moustafa Mahmoud Avatar answered Oct 28 '22 06:10

Moustafa Mahmoud


You can use the get_state method (see here: https://www.olivieraubert.net/vlc/python-ctypes/doc/) to check the state of the vlc player.

Something like

    vlc_instance = vlc.Instance()
    media = vlc_instance.media_new('sound.mp3')
    player = vlc_instance.media_player_new()
    player.set_media(media)
    player.play()
    print player.get_state()# Print player's state
like image 45
filipbarak Avatar answered Oct 28 '22 08:10

filipbarak


for wait util end of vlc play sound, except your:

    player.play()
    time.sleep(1.5)
    duration = player.get_length() / 1000
    time.sleep(duration)

other possible (maybe more precise, but CPU costing) method is:


# your code ...

Ended = 6
current_state = player.get_state()
while current_state != Ended:
  current_state = player.get_state()
  # do sth you want
print("vlc play ended")

refer :

  • vlc.State definition
  • vlc.Instance
  • vlc.MediaPlayer - get_state
like image 2
crifan Avatar answered Oct 28 '22 06:10

crifan