Search code examples
pythonraspberry-pivlc

Python vlc check if song is playing


I have this Python script:

import mysql.connector
import os
import time
import vlc
from subprocess import Popen
from mysql.connector import Error

def program():
    connection = mysql.connector.connect(host='localhost',
                                         database='broadcast',
                                         user='****',
                                         password='****')
    if connection.is_connected():
        db_Info = connection.get_server_info()
        print("Connected to MySQL Server version ", db_Info)
        cursor = connection.cursor()
        cursor.execute("select database();")
        record = cursor.fetchone()
        print("You're connected to database: ", record)
        
    sql_select_Query = "select * from broadcast WHERE datumtijd BETWEEN now() - INTERVAL 1 MINUTE AND now()"
    cursor = connection.cursor()
    cursor.execute(sql_select_Query)
    # get all records
    records = cursor.fetchall()
    print("Total number of rows in table: ", cursor.rowcount)
    print("\n")

    #print("\nPrinting each row")
    for row in records:
        print("\nPrinting each row")
        print("id = ", row[0], )
        print("date_time  = ", row[1])
        print("audiofile  = ", row[2], "\n")
        player = vlc.MediaPlayer('/home/pi/Music/' + row[2])
        player.play()
        
        
runprogram = True
while runprogram:
    program()
    time.sleep(10)

This code check if there is a record in a mysql database and if the time matches it will play that song. No problems so far, but the script is sitting in a while loop of 10 seconds. After 10 seconds the same song is played again, so there are 2 songs playing at that moment. And after another 10 seconds it starts for the 3rd time, etc. ect.

Is there any possibility to change my code, so it doens't start another song if there is a song playing. If yes, what do I need to add/change to make this work.

Gr. Edwin


Solution

  • Simply hold the player open while it's still playing with a while loop.

    e.g.

    import time
    import vlc
    
    input_files = ['punish.mp3', 'trial.wav', 'punish2.mp3']
    
    def program():
        for row in input_files:
            print("Playing: ", row)
            player = vlc.MediaPlayer('../'+row)
            player.play()
            time.sleep(1) # allow player to start
            while player.is_playing():
                time.sleep(1)        
            
    runprogram = True
    while runprogram:
        program()
        print("Finished: Looping for more audio")
        time.sleep(10)
    

    Output:

    python 20220227.py
    Playing:  punish.mp3
    Playing:  trial.wav
    Playing:  punish2.mp3
    Finished: Looping for more audio
    Playing:  punish.mp3
    Playing:  trial.wav
    Playing:  punish2.mp3
    Finished: Looping for more audio
    Playing:  punish.mp3