如何在pyglet中连续播放音乐

时间:2014-12-10 00:07:56

标签: python pyglet

我和我的朋友正在制作游戏,我们希望我们的音乐在游戏运​​行时循环播放。请帮助,似乎没有功能将音乐重复播放

5 个答案:

答案 0 :(得分:3)

在当前版本的pyglet中,您应该使用SourceGroup,将loop属性设置为True。然后,您可以将其排队到Player进行播放:

snd = pyglet.media.load('sound.wav')
looper = pyglet.media.SourceGroup(snd.audio_format, None)
looper.loop = True
looper.queue(snd)
p = pyglet.media.Player()
p.queue(looper)
p.play()

不确定是否有更紧凑的方法,但似乎有效...

答案 1 :(得分:1)

要在循环中播放声音,可以使用播放器:

# create a player and queue the song
player = pyglet.media.Player()
sound = pyglet.media.load('lines.mp3')
player.queue(sound) 

# keep playing for as long as the app is running (or you tell it to stop):
player.eos_action = pyglet.media.SourceGroup.loop

player.play()

要同时播放更多背景音,只需为每个声音启动另一个播放器,并为每个声音设置相同的EOS_LOOP“eos_action”设置。

答案 2 :(得分:0)

这对我有用

myplayer = pyglet.media.Player()
Path = "c:/path/to/youraudio.mp3"
source = pyglet.media.load(filename=source, streaming=False)
myplayer.queue(self.slowCaseSongSource)
myplayer.eos_action = 'loop'

答案 3 :(得分:0)

要连续播放,您可以使用此代码

这将允许您播放根目录中的文件

import pyglet
from pyglet.window import key
import glob

window = pyglet.window.Window(1280, 720, "Python Player", resizable=True)
window.set_minimum_size(400,300)
songs=glob.glob("*.wav")
player=pyglet.media.Player()

@window.event
def on_key_press(symbol, modifiers):
    if symbol == key.ENTER:
        print("A key was pressed")
        @window.event
        def on_draw():
            global player
            for i in range(len(songs)):
                source=pyglet.resource.media(songs[i])
                player.queue(source)
            player.play()

pyglet.app.run()

答案 4 :(得分:-1)

这可能无关紧要:

import pyglet
import time
import random

#WARNING: You have to download your own sounds and define them like this:
#sound_1 = pyglet.resource.media("sound_file.wav", streaming=False)
#replacing "sound_file" with your own file.

# Add the sound variables here
BACKGROUND_OPTIONS = ()

player = pyglet.media.Player()

def play_background_sound():
  global player
  player.queue(random.choice(BACKGROUND_OPTIONS))
  player.play()

  # This is optional; it's just a function that keeps the player filled so there aren't any breaks.
  def queue_sounds():
    global player
    while True:
      player.queue(random.choice(BACKGROUND_OPTIONS))
      time.sleep(60) # change this if the background music you have is shorter than 3 minutes

threading.Thread(target=queue_sounds).start()