I'm using MediaListPlayer
from the python-vlc
library. I use the following code to create a list of all the songs in a directory and begin them playing as a playlist, so that once one song ends another begins.
import os
from vlc import MediaListPlayer
class Music:
def __init__(self, path):
self.path = path
self.get_playlist()
self.play()
def get_songs(self):
self.pathlist = []
for file in os.listdir(self.path):
if file.endswith('.mp3'):
self.pathlist.append(os.path.join(self.path, file))
def get_playlist(self):
self.player = MediaListPlayer()
inst = self.player.get_instance()
playlist = inst.media_list_new()
self.get_songs()
for path in self.pathlist:
song = inst.media_new(path)
playlist.add_media(song)
self.player.set_media_list(playlist)
def play(self):
self.player.play()
Music('path/to/music')
This works perfectly, and plays one song after the next. What I'm looking for is a way to get the file path of the current track. Something along the lines of self.player.get_current_track()
.
I've scoured the documentation, found here, and there seems to be no way to do this. Does anybody have a solution?
I've discovered an answer to this problem based on help I received on another thread here. I use the get_media()
method of the MediaPlayer
object to retrieve the current Media
object. I then use the get_mrl()
method of the current Media
object to obtain a file path in the format 'file:///home/pi/Desktop/music/Radio%20Song.mp3'
. The thread I've linked showed me how to convert this into a traditional file path, in the format '/home/pi/Desktop/music/Radio Song.mp3'
. This is done by using the urllib
module.
import os
from urllib.request import url2pathname
from urllib.parse import urlparse
from vlc import Media, MediaList, MediaListPlayer
class Music(object):
def __init__(self, path):
self.path = path
self.player = MediaListPlayer()
self.get_playlist()
def get_playlist(self):
self.playlist = MediaList()
for file in os.listdir(self.path):
if file.endswith('.mp3'):
song = os.path.join(self.path, file)
self.playlist.add_media(song)
self.player.set_media_list(self.playlist)
def item_at_index(self, idx):
mrl = self.playlist.item_at_index(idx).get_mrl()
return url2pathname(urlparse(mrl).path)
def index_of_current_item(self):
item = self.player.get_media_player().get_media()
return self.playlist.index_of_item(item)
def path_to_current_item(self):
return self.item_at_index(self.index_of_current_item())
def play(self):
self.player.play()
print(self.path_to_current_item()) # testing
if __name__ == "__main__":
music = Music('path/to/music')
music.play()