How to play music continuously in pyglet - python

me and my friend are working on a game and we want our music to loop as long as the game is running. Help please there seems to be no function to put music on repeat

In current versions of pyglet, you should use a SourceGroup, setting the loop attribute to True. You can then queue it into a Player to play it:
snd = pyglet.media.load('sound.wav')
looper = pyglet.media.SourceGroup(snd.audio_format, None)
looper.loop = True
looper.queue(snd)
p = pyglet.media.Player()
p.queue(looper)
p.play()
Not sure if there's a more compact way of doing this but it seems to work...

To make a sound play in a loop, you can use a Player:
# create a player and queue the song
player = pyglet.media.Player()
sound = pyglet.media.load('lines.mp3')
player.queue(sound)
# keep playing for as long as the app is running (or you tell it to stop):
player.eos_action = pyglet.media.SourceGroup.loop
player.play()
To play more background sounds simultaneously, just start up another player for each of the sounds, with the same EOS_LOOP "eos_action" setting as above for each of them.

For playing continuously you can use this code
This will allow you to play files from your root directory
import pyglet
from pyglet.window import key
import glob
window = pyglet.window.Window(1280, 720, "Python Player", resizable=True)
window.set_minimum_size(400,300)
songs=glob.glob("*.wav")
player=pyglet.media.Player()
#window.event
def on_key_press(symbol, modifiers):
if symbol == key.ENTER:
print("A key was pressed")
#window.event
def on_draw():
global player
for i in range(len(songs)):
source=pyglet.resource.media(songs[i])
player.queue(source)
player.play()
pyglet.app.run()

this works for me
myplayer = pyglet.media.Player()
Path = "c:/path/to/youraudio.mp3"
source = pyglet.media.load(filename=source, streaming=False)
myplayer.queue(self.slowCaseSongSource)
myplayer.eos_action = 'loop'

this might be irrelevant:
import pyglet
import time
import random
#WARNING: You have to download your own sounds and define them like this:
#sound_1 = pyglet.resource.media("sound_file.wav", streaming=False)
#replacing "sound_file" with your own file.
# Add the sound variables here
BACKGROUND_OPTIONS = ()
player = pyglet.media.Player()
def play_background_sound():
global player
player.queue(random.choice(BACKGROUND_OPTIONS))
player.play()
# This is optional; it's just a function that keeps the player filled so there aren't any breaks.
def queue_sounds():
global player
while True:
player.queue(random.choice(BACKGROUND_OPTIONS))
time.sleep(60) # change this if the background music you have is shorter than 3 minutes
threading.Thread(target=queue_sounds).start()

Related

My program crashes after i hold the w key to move the turtle for too long in the turtle library

The code is as follows:
import turtle
width = 400
length = 300
wn = turtle.Screen()
wn.bgcolor("black")
wn.title("x")
drawer = turtle.Turtle()
drawer.speed(3)
drawer.begin_fill()
drawer.color("blue", "yellow")
def drawern():
drawer.seth(90)
drawer.fd(1)
def drawerw():
drawer.seth(180)
drawer.fd(1)
def drawers():
drawer.seth(270)
drawer.fd(1)
def drawere():
drawer.seth(0)
drawer.fd(1)
wn.onkeypress(drawern, "w")
wn.onkeypress(drawerw, "a")
wn.onkeypress(drawers, "s")
wn.onkeypress(drawere, "d")
wn.listen()
wn.mainloop()
It gives a stack overflow error. Does anyone know why this issue persists? It doesn't happen when i let go of it once in a while.
I believe the stack overflow error is due to repeated assigning of angle to the stack. To prevent this, you can introduce a debounce. We will name our debounce as move.
A debounce, in simple terms, is fail-safe to prevent an event for triggering again and again while keeping the rest of the code running.
Define the variable in global space:
move = False
As for the function:
def drawern():
global move #To let the function know the variable is from global scope
if not move: #The key is pressed first time
drawer.seth(90)
move = True #Sets our debounce to True, it will not activate until the key is released
drawer.fd(1)
wn.onkeypress(drawern, "w")
We need to have another function with an event to reset our debounce:
def reset_db():
global move
move = False #Resets the debounce, referencing the key has been released
wn.onkeyrelease(reset_db, "w") #Connects the event
I have demonstrated for w key here only. You can duplicate it for the rest of the keys too.

Pause Function Ursina - Python

I'm trying to do a pause menu for my game in Ursina Engine and I can't fount informatino how the function pause() works or how to do it.
Can someone help me?
Pausing is already implemented in ursina. Just set application.paused to True or False. application.pause() and application.resume() does the same.
from ursina import *
app = Ursina()
# Make a simple game so we have something to test with
from ursina.prefabs.first_person_controller import FirstPersonController
player = FirstPersonController(gravity=0, model='cube', color=color.azure)
camera.z = -10
ground = Entity(model='plane', texture='grass', scale=10)
# Create an Entity for handling pausing an unpausing.
# Make sure to set ignore_paused to True so the pause handler itself can still recieve input while the game is paused.
pause_handler = Entity(ignore_paused=True)
pause_text = Text('PAUSED', origin=(0,0), scale=2, enabled=False) # Make a Text saying "PAUSED" just to make it clear when it's paused.
def pause_handler_input(key):
if key == 'escape':
application.paused = not application.paused # Pause/unpause the game.
pause_text.enabled = application.paused # Also toggle "PAUSED" graphic.
pause_handler.input = pause_handler_input # Assign the input function to the pause handler.
app.run()

Static sources not supported for video yet

I was trying to play a song using Pyglet, but encountered this error
NotImplementedError: Static sources not supported for video yet.
But the file is mp3 format. I have AVbin11-win64.exe installed (avbin64.dll) which is copied in 'C:\Windows\SysWOW64' Folder, downloaded from https://github.com/AVbin/AVbin/downloads.
Here is the script I am using :
import pyglet
player = pyglet.media.Player()
source = pyglet.media.load(r'C:\Users\MANDAV\Desktop\New folder (2)\Diamond-
Platnumz-All-The-Way-Up-v2.mp3', streaming=False)
player.play()
player.app.run()
Your code contains a few issues.
The first being player.app.run(), player doesn't have .app - you're probably looking for pyglet.app.run().
The second thing is that you try to call player.play(), but you never did player.queue(source). So either do source.play() or player.queue(source) (both does exactly the same thing, playing the source directly will create a player in the background.)
The third thing being streaming=False. avbin (10 at least) have issues decoding mp3 as a static source. Not quite sure why, but the project has been dead for soon to be a century (yes, in just a few short years, this code has been dead for 10 years).
Here's a minimal working example:
import pyglet
source = pyglet.media.load('epic.mp3')
source.play()
pyglet.app.run()
Altho, you probably want some more functionality while playing your stuff. So here's a bigger example of how you could put together a start for a music playing application:
import pyglet
from pyglet.gl import *
from collections import OrderedDict
key = pyglet.window.key
class main(pyglet.window.Window):
def __init__ (self, width=800, height=600, fps=False, *args, **kwargs):
super(main, self).__init__(width, height, *args, **kwargs)
self.keys = OrderedDict() # This just keeps track of which keys we're holding down. In case we want to do repeated input.
self.alive = 1 # And as long as this is True, we'll keep on rendering.
## Add more songs to the list, either here, via input() from the console or on_key_ress() function below.
self.songs = ['A.wav', 'B.wav', 'C.wav']
self.song_pool = None
self.player = pyglet.media.Player()
for song in self.songs:
media = pyglet.media.load(song)
if self.song_pool is None:
## == if the Song Pool hasn't been setup,
## we'll set one up. Because we need to know the audio_format()
## we can't really set it up in advance (consists more information than just 'mp3' or 'wav')
self.song_pool = pyglet.media.SourceGroup(media.audio_format, None)
## == Queue the media into the song pool.
self.song_pool.queue(pyglet.media.load(song))
## == And then, queue the song_pool into the player.
## We do this because SourceGroup (song_pool) as a function called
## .has_next() which we'll require later on.
self.player.queue(self.song_pool)
## == Normally, you would do self.player.eos_action = self.function()
## But for whatever fucky windows reasons, this doesn't work for me in testing.
## So below is a manual workaround that works about as good.
self.current_track = pyglet.text.Label('', x=width/2, y=height/2+50, anchor_x='center', anchor_y='center')
self.current_time = pyglet.text.Label('', x=width/2, y=height/2-50, anchor_x='center', anchor_y='center')
def on_draw(self):
self.render()
def on_close(self):
self.alive = 0
def on_key_release(self, symbol, modifiers):
try:
del self.keys[symbol]
except:
pass
def on_key_press(self, symbol, modifiers):
if symbol == key.ESCAPE: # [ESC]
self.alive = 0
elif symbol == key.SPACE:
if self.player.playing:
self.player.pause()
else:
self.player.play()
elif symbol == key.RIGHT:
self.player.seek(self.player.time + 15)
## == You could check the user input here,
## and add more songs via the keyboard here.
## For as long as self.song_pool has tracks,
## this player will continue to play.
self.keys[symbol] = True
def end_of_tracks(self, *args, **kwargs):
self.alive=0
def render(self):
## Clear the screen
self.clear()
## == You could show some video, image or text here while the music plays.
## I'll drop in a example where the current Track Name and time are playing.
## == Grab the media_info (if any, otherwise this returns None)
media_info = self.player.source.info
if not media_info:
## == if there were no meta-data, we'll show the file-name instead:
media_info = self.player.source._file.name
else:
## == But if we got meta data, we'll show "Artist - Track Title"
media_info = media_info.author + ' - ' + media_info.title
self.current_track.text = media_info
self.current_track.draw()
## == This part exists of two things,
## 1. Grab the Current Time Stamp and the Song Duration.
## Check if the song_pool() is at it's end, and if the track Cur>=Max -> We'll quit.
## * (This is the manual workaround)
cur_t, end_t = int(self.player.time), int(self.player.source._get_duration())
if self.song_pool.has_next() is False and cur_t >= end_t:
self.alive=False
## 2. Show the current time and maximum time in seconds to the user.
self.current_time.text = str(cur_t)+'/'+str(end_t) + 'seconds'
self.current_time.draw()
## This "renders" the graphics:
self.flip()
def run(self):
while self.alive == 1:
self.render()
# -----------> This is key <----------
# This is what replaces pyglet.app.run()
# but is required for the GUI to not freeze
#
event = self.dispatch_events()
x = main()
x.run()
If you're just interested in playing sounds.
I wholeheartedly recommend Pydub.
Not only does it use libav which is more of a defacto standard when encoding and decoding, but it's also rich in features. Such as converting .mp3 to .wav and you can control audio gain, play two sources at the same time etc.

Pyglet Player.seek() function not working?

I am trying to build a simple media tool in Pyglet, which requires a seek feature. Files are loaded, paused, and then told to seek to a specific time; however, the file does not seek when Player.seek() is called. Below is the test code I am using:
import os
import pyglet
from os.path import abspath, isfile
def loadsong(filename):
# check for file
print("Attempting to load "+filename)
filename = abspath(filename)
if not ( isfile(filename) ):
raise Exception(filename+" not found.")
# create a player for this file
song = pyglet.media.load(filename)
source = song.play()
source.eos_action = source.EOS_LOOP
source.pause()
return source
music = loadsong("test.mp3")
music.seek(57)
music.play()
pyglet.app.run()
What am I doing wrong here? I am using Python 3.5.2, Pyglet 1.2 alpha 1, and AVBin 11 alpha 4.
First of all, the error you're getting is quite important.
But I'll assume it's a Segmentation fault (core dumped) on the row:
music.seek(12)
Another quick note, fix your indentation! You're using 3 spaces and whether you are a space guy or a tab guy - 3 spaces is just odd -
The reason for you getting a segmentation fault when trying to seek is most likely because of AVbin, it's an old (and dead afaik) project.
I hacked together something more similar to a music player and here's an example on how you can use Seek with wav files:
import pyglet
from pyglet.gl import *
from os.path import abspath, isfile
pyglet.options['audio'] = ('pulseaudio', 'alsa', 'openal', 'silent')
pyglet.have_avbin=False
key = pyglet.window.key
def loadsong(filename):
# check for file
filename = abspath(filename)
# create a player for this file
player = pyglet.media.Player()
player.queue(pyglet.media.load(filename, streaming=False))
#player.play()
#song.eos_action = song.EOS_LOOP
#song.pause()
return player
class main(pyglet.window.Window):
def __init__ (self):
super(main, self).__init__(300, 300, fullscreen = False)
self.alive = 1
self.player = loadsong('./test.wav')
def on_draw(self):
self.render()
def on_close(self):
self.alive = 0
def on_key_press(self, symbol, modifiers):
if symbol == key.ESCAPE: # [ESC]
self.alive = 0
elif symbol == key.SPACE:
if self.player.playing:
self.player.pause()
else:
self.player.play()
elif symbol == key.RIGHT:
print('Skipping to:',self.player.time+2)
self.player.source.seek(self.player.time+2)
elif symbol == key.LEFT:
print('Rewinding to:',self.player.time-2)
self.player.source.seek(self.player.time-2)
def render(self):
self.clear()
#source = pyglet.text.Label(str(self.player.source.info.title.decode('UTF-8')), x=20, y=300-30)
volume = pyglet.text.Label(str(self.player.volume*100)+'% volume', x=20, y=40)
p_time = pyglet.text.Label(str(self.player.time), x=20, y=20)
#source.draw()
volume.draw()
p_time.draw()
self.flip()
def run(self):
while self.alive == 1:
self.render()
# -----------> This is key <----------
# This is what replaces pyglet.app.run()
# but is required for the GUI to not freeze
#
event = self.dispatch_events()
x = main()
x.run()
A few important notes:
pyglet.have_avbin=False
This will turn off AVbin completely, there is probably a way to turn it off for individual sources.. But since I rarely play around with it I honestly have no idea of how to.. So off it goes :)
Secondly:
streaming=False
On the media.load() call is quite important, otherwise you might get weird artifacts in your sound and or no sound at all. I got instance to a super high pitched scratching noise that almost made me deaf without that flag.
Other than that, the code is quite straight forward.
self.player.source.seek(<time>)
Is called on the player object that is a instance of pyglet.media.Player(). And it works brilliantly.
Another work-around would be to manually install AVbin 7 which appears to be working better, but I'm reluctant to install it on this machine just for testing purposes.. But the overall info i've gathered over the years is that that old library works better with Mp3 files.
Please ensure Player.playing is True before invoking Player.seek().
In the end of loadsong() function, you invoked the pause() that will set the Player.playing to False.
you could try:
music.play()
music.seek(57)
instead of:
music.seek(57)
music.play()
The following example uses pyglet 1.5.6, the seek() function works on my macbook pro, but negative on my windows 10:
import pyglet
from pyglet.window import key
source = pyglet.media.load(VIDEO_FILE_PATH)
fmt = source.video_format
player = pyglet.media.Player()
player.queue(source)
player.play()
window = pyglet.window.Window(width=fmt.width, height=fmt.height)
#window.event
def on_draw():
player.get_texture().blit(0, 0)
#window.event
def on_key_press(symbol, modifiers):
if symbol == key.LEFT:
player.seek(player.time - 3.5)
elif symbol == key.RIGHT:
player.seek(player.time + 3.5)
elif symbol == key.SPACE:
if player.playing:
player.pause()
else:
player.play()
pyglet.app.run()

Trying to do animation but the program would close before it

I'm a beginner and was wondering if there was any way to finish the current animation before the program closes. Here is the sample of the code:
if playerHealth <= 0: # If the player dies
expl = Explosion(hit.rect.center, 'lg')
all_sprites.add(expl) # Show animation of him blowing up
running = False # End the game
Basically the running = False code would run before the animation(expl) starts. Is there a better way of showing this animation fully?
This sounds like a case for using a callback function. Pygame's animation class has the on_finished property which is intended to be assigned to a callback. The callback would be called once the animation is finished playing and would stop the game. Here's an example Explosion class.
class Explosion:
def __init__(self, rect, size, cb_func):
self.animate_explosion(cb_func)
...
def animate_explosion(self, cb_func):
# start animation here
...
# when animation finishes
self.on_finished = cb_func()
And then within your game logic you have something like the following:
def callback():
running = False
if playerHealth <= 0: # If the player dies
expl = Explosion(hit.rect.center, 'lg', callback())
all_sprites.add(expl) # Show animation of him blowing up
Probably You need more modifications, but one of them is:
if playerHealth <= 0 and not blowing_up_animation_started: # If the player dies
expl = Explosion(hit.rect.center, 'lg')
all_sprites.add(expl) # Show animation of him blowing up
blowing_up_animation_started = True
blowing_up_animation_finished = False
if blowing_up_animation_finished:
running = False # End the game

Categories

Resources