简体   繁体   English

使用Pyglet播放音频文件的子集

[英]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? 如何使用pyglet API播放声音,以播放声音文件的子集,例如从6秒声音片段的1秒到3.5秒?

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. pyglet似乎不支持设置停止时间。 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. 或者,使用声音文件库将所需的部分提取到临时声音文件中,然后使用pyglet完整播放该声音文件。 Python has built-in support for .wav files (the "wave" module), or you could shell out to a command-line tool like "sox". Python内置了对.wav文件(“ wave”模块)的支持,或者您可以使用诸如“ 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. 这种方法似乎有效:与其手动轮询当前时间以停止播放,不如使用pyglet时钟调度程序在给定间隔后运行一次stop回调。 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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