Mp3 Player using python 2.7 and pyglet on Ubuntu - linux

I am trying to make an mp3 player in python using pyglet and I want to display the current song name that is playing. I tried to use SourceInfo class, but I don't know how it works
pyglet.media.SourceInfo.title doesn't show anything. Could you please help me?
Thanks

First all all, make sure you got AvBin installed!
Otherwise you won't be able to play much other than wav files.
Remember that this is just a rough mock up of what you need.
Build on it, scrap it.. But this is a start.
import pyglet
pyglet.options['audio'] = ('pulse', 'alsa')
window = pyglet.window.Window(width=800, height=600)
player=pyglet.media.Player()
# == Queue more tracks,
# the label will update automatically
player.queue( pyglet.media.load('./Downloads/music/Pendulum - Hold Your Color.mp3', streaming=True) )
player.volume=0.3
# window is the variable 'window' from earlier.
#window.event
def on_draw():
window.clear()
if player.playing:
label = pyglet.text.Label('{artist} - {song}'.format(**{'artist' : player.source.info.author.decode('UTF-8'),
'song' : player.source.info.title.decode('UTF-8')}),
font_size=36,
x=window.width//2, y=window.height//2, # same here, window on line 6
anchor_x='center', anchor_y='center')
else:
label = pyglet.text.Label('Music paused!', font_size=36, x=window.width//2, y=window.height//2, anchor_x='center', anchor_y='center')
label.draw()
window.flip() # This is overkill but ensures proper rendering at all times.
#window.event
def on_key_press(symbol, modifiers):
# Up and Down controls the volume for instance
if symbol == pyglet.window.key.UP:
player.volume = player.volume+0.1
elif symbol == pyglet.window.key.DOWN:
player.volume = player.volume-0.1
# Any key really will start/pause the playback
elif player.playing:
player.pause()
else:
player.play()
pyglet.app.run()

Related

'_Screen' object has no attribute 'tk' when trying to use canvasvg.saveall() on turtle

I have made a strange program that can draw fractals and circles and spirals and I have been trying for hours to get a way to save the turtle output to a image file (preferably png or jpeg).
I am getting the '_Screen' object has no attribute 'tk' when trying to use canvasvg.saveall() on turtle. here is the code:
import turtle
import random
import canvasvg
root = turtle.Screen()
drawing = 1
def save():
canvasvg.saveall("spircles.svg", root)
print("turning angle:")
turningangle = float(input())
print("size:")
forward = float(input())
print("spiral:")
try:
spiral = float(input())
if spiral == None:
spiral = random.random()
except:
pass
spiral = random.random()
turtle = turtle.Turtle(visible=False)
turtle.speed(speed=0)
turtle.hideturtle()
turtle.ht()
print("drawing. spiral:", spiral)
try:
while drawing == 1:
root.listen()
root.onkey(save, "s")
turtle.left(turningangle)
turtle.forward(forward)
turningangle += spiral
spiral += (spiral / turningangle)
except Exception as e:
drawing = 0
pass
print("done. press enter to exit. error:", e)
input()
exit()
turtle.mainloop()
anybody know an easy way of doing this? have tried PIL and it hasn't worked. I also want to not have to install third party programs. I want to be able to install some modules with pip (if necessary) and be able to run it without hassle. it should save to an image file when the user presses "s".
I have tried PIL, and canvasvg.saveall() and I want canvasvg.saveall() as it seems to be the easiest way of doing this.
While Turtle uses tkinter.Canvas to draw your shapes, the Screen object is not a tkinter.Canvas object, nor is it a tkinter.Widget at all. Turtle provides a method for this task, it's called turtle.getcanvas and you can use it on your Screen object. So canvas = root.getcanvas() should work just fine.
It seems like you can use canvasvg.saveall(filename, canvas), but be aware that they state not all items are supported.
def save():
canvas = root.getcanvas()
canvasvg.saveall("spircles.svg", canvas)

randomize background music for pygame project

I am trying to shuffle my background music in this very basic space invaders game. I just want it to randomly play a song from a list of 5 songs whenever the game starts or is restarted(I haven't added a restart button yet)I'm not getting any errors in the terminal but there is also nothing playing.
# background music
play_list = []
play_list.append("./toonz/toon1.mp3")
play_list.append("./toonz/toon2.mp3")
play_list.append("./toonz/toon3.mp3")
play_list.append("./toonz/toon4.mp3")
play_list.append("./toonz/toon5.mp3")
def play_toonz(play_list):
random.shuffle(play_list)
pygame.mixer.music.load(play_list[songNumber])
pygame.mixer.music.play(-1)
for num, song in enumerate(play_list):
if num == songNumber:
continue
mixer.music.queue(song)
Thinking I may have written the function incorrectly??
This code works for me:
import pygame
import random
pygame.mixer.init()
# background music
play_list = []
play_list.append(r"D:\MikeStuff\MP3\04-Zombie.mp3")
play_list.append(r"D:\MikeStuff\MP3\03 Invincible.mp3")
play_list.append(r"D:\MikeStuff\MP3\10. Kashmir.mp3")
play_list.append(r"D:\MikeStuff\MP3\11-fozzy-sos.mp3")
play_list.append(r"D:\MikeStuff\MP3\104-radiohead-creep.mp3")
songNumber = 1
def play_toonz(play_list):
random.shuffle(play_list)
pygame.mixer.music.load(play_list[songNumber])
pygame.mixer.music.play(10)
for num, song in enumerate(play_list):
if num == songNumber:
continue
pygame.mixer.music.queue(song)
play_toonz(play_list)
input("Press Enter to Exit....")

mouse click events on a saved video using opencv and python

I want to draw a rectangle in a saved video. While drawing the rectangle,the video must freeze. I am successful in drawing a rectangle on a image,but I don't know how to do the same on a saved video using opencv and python.
I was in need of a ROI selection mechanism using opencv and I finally figured how to implement it.
The implementation can be found here (opencvdragrect). It uses opencv 3.1.0 and Python 2.7
For a saved video till the time you don't read another frame and display it, the video is considered as paused.
In terms of how to add it to a paused video (frame), this code below might help.
import cv2
import selectinwindow
wName = "select region"
video = cv2.VideoCapture(videoPath)
while(video.isOpened()):
# Read frame
ret, RGB = video.read()
frameCounter += 1
if frameCounter == 1 : # you can pause any frame you like
rectI = selectinwindow.dragRect
selectinwindow.init(rectI, I, wName, I.shape[1], I.shape[0])
cv2.namedWindow(wName)
cv2.setMouseCallback(wName, selectinwindow.dragrect, rectI)
while True:
# display the image
cv2.imshow(wName, rectI.image)
key = cv2.waitKey(1) & 0xFF
# if returnflag is set break
# this loop and run the video
if rectI.returnflag == True:
break
box = [rectI.outRect.x,rectI.outRect.y,rectI.outRect.w,rectI.outRect.h]
# process the video
# ...
# ...
In the (opencvdragrect) library you use double-click to stop the rectangle selection process and continue with video.
Hope this helps.

I'm new to coding. A while loop in Python won't work properly, but has no errors

I got this code from a book called "Python for Kids," by Jason Briggs. This code was ran in Python 3.4.3. I don't have any outside coding experience outside from this book. I tried multiple possibilities to fix this and looked online, but I couldn't find anything that would work or help my problem. If you have new code or edits for this code, that would be helpful to me continuing to learn Python.
from tkinter import *
import random
import time
class Game:
def __init__(self):
self.tk = Tk()
self.tk.title("Mr. Stick Man Races for The Exit")
self.tk_resizable(0, 0)
self.tk.wm_attributes("-topmost", 1)
self.canvas = Canvas(self.tk, width=500, height=500, highlightthickness=0)
self.canvas.pack()
self.tk.update()
self.canvas_height = 500
self.canvas_width = 500
self.bg = PhotoImage(file="Wallpaper.gif")
w = self.bg.width()
h = self.bg.height()
for x in range(0, 5):
for y in range(0, 5):
self.canvas.create_image(x * w, y * h, image=self.bg, anchor='nw')
self.sprites = []
self.running = True
def mainloop(self):
while 1:
if self.running == True:
for sprite in self.sprites:
sprites.move()
self.tk.update_idletasks()
self.tk.update()
time.sleep(0.01)
g = Game()
g.mainloop()
This code was supposed to make a window with a wallpaper I created in Gimp to fill the window. When I ran the code, nothing happened and no errors appeared. What I need help on is making a window with my wallpaper appear. If you can help, can you give me an explanation with code. I'm sorry if my mistakes are obvious.
These two statements need to be all the way to the left, with no indentation:
g = Game()
g.mainloop()
The code class Game: creates a class, which can be thought of as a recipe for how to create a game. It does not actually create the game, it only provides code to create the game.
In order to actually create the game -- called instantiatiation -- you need to call Game as if it was a function. When you do g = Game() you are actually creating the game object and saving a reference to it. Unless you do this, the game will never be created. Thus, to create a instance of the game, you must define it in one step (class Game()) and create it in another (g = Game())
Warning, there are other problems in the code. This answers your specific question, but you need to fix the indentation of the def mainloop statemen, and there may be other issues.
The biggest problem is that this simply isn't the right way to do animation in Tkinter. It might be ok as a learning tool, but ultimately this is simply not proper usage of tkinter. I don't know if this code is straight from the book or if this is code you're trying on your own, but tkinter simply isn't designed to work this way. You shouldn't be creating your own mainloop function because tkinter has one that is built in.
To fix the mainloop issue, remove the existing mainloop function, and add this in its place (properly indented under class Game():
def mainloop(self):
# start the animation
self.animate()
# start the event loop
self.tk.mainloop()
def animate(self):
if self.running == True:
for sprite in self.sprites:
sprites.move()
self.tk.after(10, self.animate)

Python load timer [duplicate]

So I have a .gif picture on a canvas in tkinter. I want this picture to change to another picture...but only for 3 seconds. and for it revert back to the original picture.
def startTurn(self):
newgif = PhotoImage(file = '2h.gif')
self.__leftImageCanvas.itemconfigure(self.__leftImage, image = newgif)
self.__leftImageCanvas.image = newgif
while self.cardTimer > 0:
time.sleep(1)
self.cardTimer -=1
oldgif = PhotoImage(file = 'b.gif')
self.__leftImageCanvas.itemconfigure(self.__leftImage, image = oldgif)
self.__leftImageCanvas.image = oldgif
this is a first attempt after a quick view of the timer. i know that this code does not make sense, but before i keep mindlessly trying to figure it out, i would much rather have more experienced input.
Tkinter widgets have a method named after which can be used to run a function after a specified period of time. To create an image and then change it three seconds later, you would do something like this:
def setImage(self, filename):
image = PhotoImage(file=filename)
self.__leftImageCanvas.itemconfigure(self.__leftImage, image=image)
self.__leftImageCanvas.image = image
def startTurn(self):
'''Set the image to "2h.gif", then change it to "b.gif" 3 seconds later'''
setImage("2h.gif")
self.after(3000, lambda: self.setImage("b.gif"))

Resources