Python vlc 检查歌曲是否正在播放

Python vlc check if song is playing

我有这个 Python 脚本:

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)

此代码检查 mysql 数据库中是否有记录,如果时间匹配,它将播放该歌曲。 到目前为止没有问题,但脚本处于 10 秒的 while 循环中。 10 秒后再次播放同一首歌曲,因此此时播放了 2 首歌曲。 又过了 10 秒,它开始第 3 次,依此类推。

是否可以更改我的代码,以便在播放歌曲时不会开始播放另一首歌曲。 如果是,我需要做什么 add/change 才能完成这项工作。

Gr。埃德温

我找到了这个:https://www.olivieraubert.net/vlc/python-ctypes/doc/vlc.MediaPlayer-class.html#is_playing

基本上,有一种方法可以检查玩家是否已经在玩 (player.is_playing())。 所以你只需要在代码中的某处保留对 vlc.MediaPlayer 的引用,然后在再次启动播放器之前检查它是否正在播放。

player 仍在播放 while 循环时,只需保持 player 打开即可。

例如

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)

输出:

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