87讲,音乐播放问题
问题:程序设置是点击空格之后暂停,再次点击空格,恢复播放音乐状态,
但是程序运行,点击空格暂停之后,再次点击空格,无法恢复
#程序运行,播放一段音乐,单机鼠标左键,和右键,分别响起两段不同的背景音乐
#点击空格,暂停,再点击一次,继续播放
import pygame
import sys
from pygame.locals import *
from random import *
pygame.init()
pygame.mixer.init()
pygame.mixer.music.load("bg_music.ogg")
pygame.mixer.music.set_volume(0.2)
pygame.mixer.music.play(loops=-1)
size= width,height = 1024, 681
bg=(0,0,0) #背景填充
screen=pygame.display.set_mode(size,RESIZABLE)
pygame.display.set_caption("播放")
background = pygame.image.load("background_ball.png").convert()
pause = False
while True:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
#pygame.mixer.music.stop()
pygame.mixer.music.load("hole.wav")
pygame.mixer.music.set_volume(0.2)
pygame.mixer.music.play(loops=-1)
if event.button == 3:
#pygame.mixer.music.stop()
pygame.mixer.music.load("laugh.wav")
pygame.mixer.music.set_volume(0.2)
pygame.mixer.music.play(loops=-1)
if event.type == pygame.KEYDOWN:
if event.key == K_SPACE:
pause = True
if pause:
pygame.mixer.music.pause() #暂停播放音乐
else:
pygame.mixer.music.unpause()#继续播放音乐
screen.blit(background, (0, 0))
pygame.display.flip()
改成这样试试:
# 程序运行,播放一段音乐,单机鼠标左键,和右键,分别响起两段不同的背景音乐
# 点击空格,暂停,再点击一次,继续播放
import pygame
import sys
from pygame.locals import *
from random import *
pygame.init()
pygame.mixer.init()
pygame.mixer.music.load("bg_music.ogg")
pygame.mixer.music.set_volume(0.2)
pygame.mixer.music.play(loops=-1)
size = width, height = 1024, 681
bg = (0, 0, 0)# 背景填充
screen = pygame.display.set_mode(size, RESIZABLE)
pygame.display.set_caption("播放")
background = pygame.image.load("background_ball.png").convert()
pause = False
while True:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
# pygame.mixer.music.stop()
pygame.mixer.music.load("hole.wav")
pygame.mixer.music.set_volume(0.2)
pygame.mixer.music.play(loops=-1)
if event.button == 3:
# pygame.mixer.music.stop()
pygame.mixer.music.load("laugh.wav")
pygame.mixer.music.set_volume(0.2)
pygame.mixer.music.play(loops=-1)
if event.type == pygame.KEYDOWN:
if event.key == K_SPACE:
pause = not pause # 更改
if pause:
pygame.mixer.music.pause()# 暂停播放音乐
else:
pygame.mixer.music.unpause()# 继续播放音乐
screen.blit(background, (0, 0))
pygame.display.flip() zltzlt 发表于 2020-4-25 18:04
改成这样试试:
谢谢老师
页:
[1]