Question

How can I use the pyglet API for sound to play subsets of a sound file e.g. from 1 second in to 3.5seconds of a 6 second sound clip?

I can load a sound file and play it, and can seek to the start of the interval desired, but am wondering how to stop playback at the point indicated?

Was it helpful?

Solution

It doesn't appear that pyglet has support for setting a stop time. Your options are:

  1. Poll the current time and stop playback when you've reached your desired endpoint. This may not be precise enough for you.
  2. Or, use a sound file library to extract the portion you want into a temporary sound file, then use pyglet to play that sound file in its entirety. Python has built-in support for .wav files (the "wave" module), or you could shell out to a command-line tool like "sox".

OTHER TIPS

This approach seems to work: rather than poll the current time manually to stop playback, use the pyglet clock scheduler to run a stop callback once after a given interval. This is precise enough for my use case ;-)

player = None

def stop_callback(dt):
  if player != None:
    player.stop()

def play_sound_interval(mp3File, start=None, end=None):
  sound = pyglet.resource.media(mp3File)
  global player
  player = pyglet.media.ManagedSoundPlayer()
  player.queue(sound)
  if start != None:
    player.seek(start)
  if end != None and start != None:
    pyglet.clock.schedule_once(stop_callback, end-start)
  elif end != None and start == None:
    pyglet.clock.schedule_once(stop_callback, end)
  player.play()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top