简体   繁体   中英

Play Subset of audio file using Pyglet

How can I use the pyglet API for sound to play subsets of a sound file eg 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?

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".

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM