You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python的if/else语句触发不同音频声道切换?

问题分析与修复方案

你的代码核心问题是逻辑搞反了:现在是玩家猜错且猜的次数不是3/5/10时,会触发Rickroll播放;而真正猜对的时候,循环直接结束,根本没执行任何音频切换的代码。另外,原代码里的else分支会在每次猜错且次数不满足3/5/10时误触发音乐,完全不符合你“猜对才播放”的需求,必须删掉。

修复步骤

  • 移除while循环内的else分支,避免错误触发音乐切换
  • 在while循环结束后(即玩家猜对答案时),添加暂停主音乐、恢复Rickroll音乐的代码

修改后的完整代码

# Adding rickroll Audio via pygame
import pygame

pygame.init()
main_channel = pygame.mixer.Channel(0)
pause_channel = pygame.mixer.Channel(1)
# 加载并循环播放主背景音乐
main_channel.play(pygame.mixer.Sound('quiztime.ogg'), loops=-1, fade_ms=5000)
# 加载Rickroll音频并先暂停
rickroll_sound = pygame.mixer.Sound('rickroll.ogg')
pause_channel.play(rickroll_sound, loops=-1, fade_ms=5000)
pause_channel.pause()

# 秘密单词
secret_word = 'rickroll'

# 初始猜测输入
guess = input('Can you guess the secret word?: ')

guess_count = 0

# 猜词循环
while guess != secret_word:
    guess_count += 1
    print('Almost... Try Again! ')
    guess = input('New Guess here plz: ')
    
    if guess_count == 3:
        print('Tis an old meme good friend...')
        guess = input('New Guess here plz: ')
    elif guess_count == 5:
        print('Think of a ginger man with soul~')
        guess = input('New Guess here plz: ')
    elif guess_count == 10:
        print("I wouldn't give you up ;)")
        guess = input('New Guess here plz: ')

# 猜对后切换到Rickroll
main_channel.pause()
pause_channel.unpause()
print("We're no strangers to loooooove~")

print('Press ENTER to exit!')
input()  # 防止程序立刻退出,方便听完音乐

额外注意事项

  • 确保quiztime.ogg和rickroll.ogg文件与Python脚本在同一文件夹,或填写完整文件路径
  • 若没有声音,检查pygame是否正确安装:执行pip install pygame
  • 最后添加的input()可根据需求保留或删除,作用是避免程序打印提示后直接退出

内容的提问来源于stack exchange,提问作者Jay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 04:43:16