python 使用 vlc 从 RaspberryPi 播放音频的脚本

python script to play audio from RaspberryPi using vlc

我每天都在同一时间在我的 RaspberryPi 上获取歌曲列表 运行。为此,我编写了一个 python 脚本并计划 运行 作为一个 cronjob。

下面是我写的脚本

import vlc
import glob
import time

base_folder = '/home/pi/Music/'


def play_song(song):
    player = vlc.MediaPlayer(song)
    player.play()

    
def add_media(player, media_list, playlist):
    for song in playlist:
        print('sing " {0}'.format(song))
        media = player.media_new(song)    
        media_list.add_media(media)
        
    media_player.set_media_list(media_list)

  
playlist = glob.glob(base_folder + "/" + "*.mp3")
media_player = vlc.MediaListPlayer()
player = vlc.Instance()    
media_list = vlc.MediaList()
add_media(player, media_list, playlist)

我对上述程序有一个问题。

当我 运行 来自 Thonny 的 python 程序时,它是 RaspberryPi 的默认 python IDE 它可以工作。 (即它播放歌曲)。但是当我从命令行 运行 as

python3 audioplayer.py

不播放歌曲就退出了。如何让它在从命令行 运行ning 时播放歌曲。

您发布的脚本中似乎缺少一些代码,即 play 命令。

我怀疑 IDE 正在为 vlc 保持主循环打开,因此它起作用了。
但是,从命令行看,没有循环,这就是你所缺少的。

尝试以下操作:

import vlc
import glob
import time

base_folder = '/home/rolf'
# vlc State 0: Nowt, 1 Opening, 2 Buffering, 3 Playing, 4 Paused, 5 Stopped, 6 Ended, 7 Error
playing = set([1,2,3,4])

def add_media(inst, media_list, playlist):
    for song in playlist:
        print('Loading: - {0}'.format(song))
        media = inst.media_new(song)    
        media_list.add_media(media)
        
playlist = glob.glob(base_folder + "/" + "*.mp3")
playlist = sorted(playlist)
#playlist = ['./2005.mp3', './vp1.mp3']
media_player = vlc.MediaListPlayer()
inst = vlc.Instance('--no-xlib --quiet ') 
media_list = vlc.MediaList()
add_media(inst, media_list, playlist)

media_player.set_media_list(media_list)
media_player.play()
time.sleep(0.1)
current = ""
idx = 1
player = media_player.get_media_player()
while True:
    state = player.get_state()
    if state.value not in playing:
        break
    title = player.get_media().get_mrl()
    if title != current:
        print("\nPlaying - {0}\t{1} of {2}".format(str(title), idx, len(playlist)))
        current = title
        idx += 1
    time.sleep(1.0)
print("\nPlaylist Finished")