python - Pygame 播放列表在后台连续播放

标签 python background pygame

<分区>

我正在尝试为我的游戏获取背景音乐,但我似乎无法完全弄清楚。我过去使用过 pygame,但在我的游戏演职员表中它只用于一首歌。 我希望播放列表随机播放每首轨道。我已经设法让它在一个单独的测试文件中工作。我将在下面发布此代码。

问题是当我在我的主游戏中调用这个函数时,音乐播放第一首轨道,然后停止。如果我输入

while pygame.mixer.music.get_busy():
    continue

它只播放音乐,不让我玩游戏。我希望它在用户玩游戏时不断循环播放列表(这是一个基于文本的游戏,所以它经常使用 raw_input()

这是我的代码:

import pygame
import random

pygame.mixer.init()

_songs = [songs, are, here]

_currently_playing_song = None

def music():
    global _currently_playing_song, _songs
    next_song = random.choice(_songs)
    while next_song == _currently_playing_song:
        next_song = random.choice(_songs)
    _currently_playing_song = next_song
    pygame.mixer.music.load(next_song)
    pygame.mixer.music.play()

while True: ## This part works for the test, but will not meet my needs
    music() ## for the full game.
    while pygame.mixer.music.get_busy():
        continue

(P.S. 我是通过 Zed Shaw 的“Learn Python The Hard Way”学习 Python 的,所以我的游戏结构使用了书中的 Engine 和 Map 系统)

最佳答案

您可以使用线程在后台播放音乐。

import threading
musicThread = threading.Thread(target=music)
musicThread.start()

如果你想在不关闭游戏的情况下停止音乐,你应该终止线程。

关于python - Pygame 播放列表在后台连续播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46459719/

相关文章:

python - 缺少位置参数

python - Pymunk Pygame 对象位置不更新

python - Numpy:索引和值的向量

python - Python 根据日期解析字符串

python - 如何在另一个 dag apache Airflow 中创建 dags

css - 页脚 Div CSS 背景颜色在 IE8 中消失

python - 在同一个容器中运行 celery worker + beat

html - 如何在CSS中对齐和背景颜色

iOS:在运行时向背景添加噪音

Python:如何将多个 Sprite 合并为一个并保存图像?