I am writing code for music player using pyglet package in python. I could play a song successfully. But i cannot pause the song after calling pyglet.app.run()
.
If i call pyglet.app.run()
after calling pause i can not play the song. How can i manage play and pause in my code ?
My code:
import pyglet
import time
player = pyglet.media.Player()
player.queue(pyglet.resource.media('1.mp3'))
player.play()
pyglet.app.run()
time.sleep(5)
player.pause()
print player.time()
#This should play the video then pause after 12 seconds of
# play. Stay paused for 4 seconds and play again.
#Note AVbin7 needs to be installed to play mp4s
import pyglet
from time import sleep
vidPath="/home/path/to/file.mp4"
window = pyglet.window.Window()
player = pyglet.media.Player()
source = pyglet.media.StreamingSource()
MediaLoad = pyglet.media.load(vidPath)
pt = 0
player.queue(MediaLoad)
player.play()
@window.event
def on_draw():
global pt
window.clear()
if player.source and player.source.video_format:
player.get_texture().blit(0,0)
if player.time >= 12 and pt == 0:
print("pausing")
player.pause()
sleep(4)
player.play()
pt = 1
pyglet.app.run()
pyglet.app.run()
This function is an infinite loop. You could create new thread, which you may sleep.
class ControllerThread(threading.Thread):
def __init__(self, player):
threading.Thread.__init__(self)
self.player = player
def run(self):
time.sleep(10)
self.player.pause()
player = pyglet.media.Player()
pyglet.resource.path = [r'path/to/music']
pyglet.resource.reindex()
music = pyglet.resource.media(r'awesomeSong.mp3')
player.queue(music)
player.play()
c = ControllerThread(player)
c.start()
pyglet.app.run()
This code should work for you
import pyglet
import threading
import time
class ControllerThread(threading.Thread):
def __init__(self, player):
threading.Thread.__init__(self)
self.player = player
def run(self):
self.player.pause()
player = pyglet.media.Player()
pyglet.resource.path = [r'/your/source/path/']
pyglet.resource.reindex()
def muz():
music = pyglet.resource.media(r'file.mp3')
player.queue(music)
player.play()
t=threading.Thread(target=muz)
a=''
while a!=' ':
a=raw_input("STOP/Play S/P: ")
if a=='s':
c = ControllerThread(player)
c.start()
elif a=='p':
if t.isAlive():
player.play()
else:
t=threading.Thread(target=muz)
t.start()
pyglet.app.run()