Controlling the VLC media player using python-vlc module
I have tried the code below but am getting the error:
Traceback (most recent call last): File "", line 1, in
import vlc File "vlc.py", line 2, in <module>
# -*- coding: utf-8 -*-
AttributeError: 'module' object has no attribute 'MediaPlayer'
Using code:
import vlc
media_player = vlc.MediaPlayer("path_to_your_song.mp3")
media_player.play()
I want the script to run and play the file
Just change the path,your good to go..
from vlc import Instance
import time
import os
class VLC:
def __init__(self):
self.Player = Instance('--loop')
def addPlaylist(self):
self.mediaList = self.Player.media_list_new()
path = r"C:\Users\dell5567\Desktop\engsong"
songs = os.listdir(path)
for s in songs:
self.mediaList.add_media(self.Player.media_new(os.path.join(path,s)))
self.listPlayer = self.Player.media_list_player_new()
self.listPlayer.set_media_list(self.mediaList)
def play(self):
self.listPlayer.play()
def next(self):
self.listPlayer.next()
def pause(self):
self.listPlayer.pause()
def previous(self):
self.listPlayer.previous()
def stop(self):
self.listPlayer.stop()
Create a object
player = VLC()
Add playlist
player.addPlaylist()
Play the song
player.play()
time.sleep(9)
Play the next song
player.next()
time.sleep(9)
Pause the song
player.pause()
time.sleep(9)
Resume the song
player.play()
time.sleep(9)
Previous song
player.previous()
time.sleep(9)
Stop the song
player.stop()
You need to create a vlc Instance.
The minimum required would be something like this, but there are many variations.
>>> import vlc
>>> i = vlc.Instance()
>>> media_player = i.media_player_new()
>>> media_player.set_mrl('./vp1.mp3')
>>> media_player.play()
Related
I'd like to the ability to run some code when the timestamp of a file has been reached (i.e. trigger an alert)
How can this be achieved?
I was looking at this https://www.geeksforgeeks.org/python-vl ... edia-time/
However, I feel like I'm really looking for some kind of daemon (i.e. start the media file with VLC and then have this "listener" perform an action when timestamp on vlc has been reached)
I'm not opposed to pulling down the code, modifying changes to add a hook, and re-compiling to get what I need. I just need some pointers on where in the codebase this would all live.
What direction may I be pointed to to achieve this? Thanks!
You want the EventManager class, the documentation for which can be found
here. Here's an example of how to use it to notify you when a video stops playing.
import vlc
def callback(event, player):
print('FPS:', player.get_fps())
print('Time(ms):', player.get_time())
print('Frame:', .001 * player.get_time() * player.get_fps())
# Create new media
inst = vlc.Instance()
media = inst.media_new('path/to/video')
# Create new instance of vlc player
player = inst.media_player_new()
# Add a callback
em = player.event_manager()
em.event_attach(vlc.EventType.MediaPlayerStopped, \
callback, player)
# Load video into vlc player instance
player.set_media(media)
# Play media
player.play()
Edit: Could you try this code?
import vlc
def callback(player):
print('FPS:', player.get_fps())
print('Time(ms):', player.get_time())
print('Frame:', .001 * player.get_time() * player.get_fps())
media_player.stop()
# creating vlc media player object
media_player = vlc.MediaPlayer()
# media object
media = vlc.Media("src/backtalk/default/oscar.mp4")
# setting media to the media player
media_player.set_media(media)
# start playing video
media_player.play()
while True:
if media_player.get_state() == vlc.State.Ended:
callback(media_player)
I'm trying to make a simple script that will play a video (.mp4) in python. I don't want to play a you tube video or anything online, just a video on my computer.
Here's my code:
import vlc
Instance = vlc.Instance()
player = Instance.media_player_new()
Media = Instance.media_new('test.mp4')
Media.get_mrl()
player.set_media(Media)
player.play()
I keep getting this error when I run it (talking about line 3):
AttributeError: 'NoneType' object has no attribute 'media_player_new'
I'm using python 3.5.4 in the IDLE on macOS Sierra.
I solved the problem by comment out find_lib() in vlc.py.
p = os.getcwd()
os.chdir(os.path.join(p, 'sdk'))
dll = ctypes.CDLL("libvlc.dll")
plugin_path = os.path.join(os.getcwd(), r'sdk\plugins')
You are not holding the instance open
import vlc
Instance = vlc.Instance()
player = Instance.media_player_new()
Media = Instance.media_new('2005.mp3')
Media.get_mrl()
player.set_media(Media)
player.play()
while player.get_state() !=6:
continue
Should work or
try this:
import vlc
import time
import sys
def progressbar(progress,guage_length=50):
div = 100 / float(guage_length)
prog = int(progress / div) # ensure progress fits in guage
text = "\rPlaying: {0}{1}{2} [{3}%]".format(">"*prog,"|","-"*(guage_length - prog),format(progress,'.2f'))
sys.stdout.write(text)
sys.stdout.flush()
instance = vlc.Instance()
player = instance.media_player_new()
player.set_mrl("V2.mp4")
player.play()
playing = set([1,2,3,4])
play=True
guage_length=30
while play == True:
time.sleep(0.5)
play_state = player.get_state()
if play_state in playing:
length = player.get_length()
ptime = player.get_time()
progress = ptime/float(length)*100
progressbar(progress,guage_length)
continue
else:
progressbar(100,guage_length)
play = False
print ("\nPlay terminated")
Note that # State 0: None,1 Opening,2 Buffering,3 Playing,4 Paused,5 Stopped,6 Ended,7 Error
Caveat: tested on Linux only
You could simplify your code using simply
import vlc
p = vlc.MediaPlayer('2005.mp3')
p.play()
but this would not solve your problem. Apparently, the vlc instance is not correctly created. This can be caused by a variety of issues. Use
i = vlc.Instance('--verbose 3')
to see possible error messages.
I got this error message on a Raspberry Pi Zero with Raspbian Buster Lite. I searched a long time for the answer but suddenly I noticed the remark on the pypi project page of python-vlc:
Note that it relies on an already present install of VLC.
So installing vlc with sudo apt install vlc solved the problem!
I am using kivy to make a small music player but i have some issues with it. I am using a screen manager which will direct the user to either his libraries, or the entire tracks list. When one of the two is selected i want to find and load all the titles as buttons, to be played when pressed. Here's the basic track class:
class Track(Button):
path = 'C:/Users/...../tracks/'
def __init__(self,title,**kwargs):
self.title = title
super(Track,self).__init__(text=self.title,**kwargs)
def playTrack(self):
self.sound = SoundLoader.load(self.path+self.title)
self.sound.play()
also here is a music class that finds all the tracks in the directory and adds them to a list:
class mymusic():
path = 'C:/Users/...../tracks'
def __init__(self,**kwargs):
self.tracks=os.listdir(self.path)
print self.tracks
def loadTracks(self):
trackslist = []
for i in self.tracks:
trackslist.append(Track(i))
return trackslist
Finally, here is the code i use, that is supposed to create the buttons (the sm below is the screen manager, and root,libraries and music are subclasses of screen):
f = lambda obj: obj.playTrack()
Music = music(name='Music')
layout = BoxLayout()
Music.add_widget(layout)
sm.add_widget(root(name='Root'))
sm.add_widget(libraries(name='My libaries'))
sm.add_widget(Music)
musicobj = mymusic()
tracklist = musicobj.loadTracks()
for i in tracklist:
print i
i.bind(on_press=f(i))
This does not work. By running it i get the following error:
Traceback (most recent call last):
File "C:\Users\Vlassis\Desktop\test.py", line 108, in <module>
i.bind(on_press=f(i))
File "kivy\_event.pyx", line 430, in kivy._event.EventDispatcher.bind (kivy\_event.c:5903)
AssertionError: None is not callable
also the last track in the directory plays in the background. I can't figure out why. Is the logic behind the code correct? How should i go about doing this? Thanks in advance.
Can I get input and play music from pygame at the same time?
The code I have now:
from pygame import mixer
mixer.init()
mixer.music.load('song.mp3')
mixer.music.play()
var = raw_input("Input: ")
print "you said ", var
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)
It works fine until I enter something, and then the program stops:
Input: test
you said test
Traceback (most recent call last):
File "play.py", line 10, in <module>
while pygame.mixer.music.get_busy():
NameError: name 'pygame' is not defined
from pygame import mixer
puts mixer in your namespace, but not pygame
You can either:
while mixer.music.get_busy():
or
import pygame
from pygame import mixer
importing pygame as well as it's subpackages you need is usually a good approach
Im new to Python and I am trying to make a class where I will play some music with the spotify library pyspotify. I have the code below and I taught that it would be playing music if I run the play method. This does not work because I can't hear any music playing, no error messages appear from what I can see. What do I have to do more?
import spotify
import threading
class Music:
session = None
def __init__(self):
logged_in_event = threading.Event()
def connection_state_listener(session):
if session.connection.state is spotify.ConnectionState.LOGGED_IN:
logged_in_event.set()
self.session = spotify.Session()
loop = spotify.EventLoop(self.session)
loop.start()
self.session.on(
spotify.SessionEvent.CONNECTION_STATE_UPDATED,
connection_state_listener)
self.session.login('accountname', 'password')
logged_in_event.wait()
print self.session.connection.state
print self.session.user
def play(self):
track = self.session.get_track('spotify:track:2Foc5Q5nqNiosCNqttzHof')
track.load()
self.session.player.load(track)
self.session.player.play(play=True)
And in another Python file I do:
music = Music.Music()
music.play()
I added the line
audio = spotify.AlsaSink(session)
and now it works!