Search code examples
pythonpython-3.xaudiopyglet

How to play audio(in generator loop) with Pyglet?


Version of pyglet - 1.4.2.
Python - 3.6.6
Ubuntu - 18.04

Code example:

import pyglet
import time

pyglet.options['audio'] = ('openal', 'pulse', 'directsound', 'silent')
source = pyglet.media.StaticSource(pyglet.media.load('explosion.wav'))

def my_playlist():
    while True:
        print(time.time())
        print(1)
        yield source


player = pyglet.media.Player()
player.queue(my_playlist())
player.play()

pyglet.app.run()

Code was writed based on documentation:

Logs in console:

1566296930.8165386  # played once
1
1566296931.529639  # won't play
1
1566296931.5301056  # won't play and etc.
1
1566296931.5304687
1
1566296931.5309348
1

Expected result:

Audio should play in loop with sounds which is returned from generator.

Current result:

Audio is played once.

Question:

What I did wrong here and how to achive expected result?


Solution

  • Not sure if you're trying to accomplish something more, but if all you need from your loop is to loop sound, you shouldn't actually use a loop of any kind. Instead, use the designated EOS_LOOP flag/trigger.

    import pyglet
    import time
    
    pyglet.options['audio'] = ('openal', 'pulse', 'directsound', 'silent')
    source = pyglet.media.StaticSource(pyglet.media.load('explosion.wav'))
    
    player = pyglet.media.Player()
    player.queue(source)
    player.EOS_LOOP = 'loop'
    player.play()
    
    pyglet.app.run()
    

    And since it's deprecated, you should move away to using the SourceGroup with the loop flag set.