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

发布于 2024-08-16 17:49:02 字数 111 浏览 6 评论 0原文

如何使用 pyglet API 来播放声音文件的子集,例如 6 秒声音剪辑的 1 秒到 3.5 秒?

我可以加载声音文件并播放它,并且可以寻找所需间隔的开始,但我想知道如何在指示的点停止播放?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

嘿看小鸭子会跑 2024-08-23 17:49:02

pyglet 似乎不支持设置停止时间。您的选项有:

  1. 轮询当前时间并在到达所需终点时停止播放。这对您来说可能不够精确。
  2. 或者,使用声音文件库将所需的部分提取到临时声音文件中,然后使用 pyglet 完整播放该声音文件。 Python 内置了对 .wav 文件(“wave”模块)的支持,或者您也可以使用“sox”等命令行工具。

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".
南城旧梦 2024-08-23 17:49:02

这种方法似乎有效:不要手动轮询当前时间来停止播放,而是使用 pyglet 时钟调度程序在给定的时间间隔后运行一次停止回调。这对于我的用例来说足够精确了;-)

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

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文