簡體   English   中英

如何在pyglet中連續播放音樂

[英]How to play music continuously in pyglet

我和我的朋友正在制作游戲,我們希望我們的音樂在游戲運​​行時循環播放。 請幫助,似乎沒有功能可以重復播放音樂

在當前版本的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()

不確定是否有更緊湊的方式這樣做,但它似乎工作...

要在循環中播放聲音,您可以使用播放器:

# 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”設置。

這對我有用

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'

要連續播放,您可以使用此代碼

這將允許您從根目錄播放文件

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

這可能是無關緊要的:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM