I'm making a little GUI with python, using cocos2d and pyglet modules. The GUI should play a sound while the "h" is pressed and stop when it is released. The problem here is that I can't find a solution to this. After searching this site I've found this question - How to play music continuously in pyglet, the problem with this one is that I can't get the sound to stop after it starts.
EDIT: I found a way to play the sound until keyrelease, but ran into another problem
Right now the code that is supposed to play the music looks like this:
class Heartbeat (cocos.layer.Layer):
is_event_handler=True
def __init__ (self):
super(Heartbeat, self).__init__()
global loop, music, player
music = pyglet.media.load('long_beep.wav')
loop=pyglet.media.SourceGroup(music.audio_format, None)
player=pyglet.media.Player()
loop.queue(music)
player.queue(loop)
def on_key_press(self, key, modifiers):
if chr(key)=='h':
loop.loop=True
player.play()
def on_key_release (self, key, modifiers):
if chr(key)=="h":
loop.loop=False
This code works when the "h" key is pressed and held down for the first time, it doesn't work in subsequent attempts. Python doesn't raise an exception, it just seems to ignore "h" key presses that occur after the first release.
NOTE: The statement - if chr(key)=="h"
may not be the best solution to keypress handling, but I'm relitively new to using cocos2d and pyglet modules.
Nevermind, I have figured this out, all I had to do was move the line player.queue(loop)
from the initialization function to the function that handles keypresses. The updated code looks like this:
class Heartbeat (cocos.layer.Layer):
is_event_handler=True
def __init__ (self):
super(Heartbeat, self).__init__()
global loop, music, player
music = pyglet.media.load('long_beep.wav')
loop=pyglet.media.SourceGroup(music.audio_format, None)
player=pyglet.media.Player()
loop.queue(music)
def on_key_press(self, key, modifiers):
if chr(key)=='h':
loop.loop=True
player.queue(loop) #This is the line that had to be moved
player.play()
def on_key_release (self, key, modifiers):
if chr(key)=="h":
loop.loop=False
NOTE: I ommited statements such as import and others, used for initialization as they are not relevant to this issue.