我有一个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秒的时间循环中运行。10秒后,同一首歌再次播放,所以在那一刻有2首歌在播放。再过10秒,它开始了第三次,等等,ect。
有没有可能更改我的代码,所以如果有一首歌正在播放,它不会启动另一首歌。如果是,我需要添加/更改哪些内容才能使其工作。
Gr。埃德温
发布于 2022-02-27 12:23:07
只需在player仍在使用while循环时将其打开即可。
例如:
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发布于 2022-02-26 18:51:11
我发现了这个:https://www.olivieraubert.net/vlc/python-ctypes/doc/vlc.MediaPlayer-class.html#is_playing
基本上,有一种检查球员是否已经在玩的方法(player.is_playing())。因此,您只需在代码中的某个地方保留对vlc.MediaPlayer的引用,然后在再次启动播放机之前检查它是否正在播放。
https://stackoverflow.com/questions/71279020
复制相似问题