Playing music on loop until a key is released. Python
<p>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 - <a href="http://stackoverflow.com/questions/27391240/how-to-play-music-continuously-in-pyglet">How to play music continuously in pyglet</a>, the problem with this one is that I can't get the sound to stop after it starts. </p>

<p>EDIT: I found a way to play the sound until keyrelease, but ran into another problem</p>

<p>Right now the code that is supposed to play the music looks like this:</p>

<pre><code>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
</code></pre>

<p>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.</p>

<p>NOTE: The statement - <code>if chr(key)=="h"</code> may not be the best solution to keypress handling, but I'm relitively new to using cocos2d and pyglet modules.</p>

<p>Nevermind, I have figured this out, all I had to do was move the line <code>player.queue(loop)</code> from the initialization function to the function that handles keypresses. The updated code looks like this: </p>

<pre><code>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
</code></pre>

<p>NOTE: I ommited statements such as import and others, used for initialization as they are not relevant to this issue.</p>

python python-3.x audio pyglet keyrelease