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()
time = 0
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 and time == 0:
pygame.mixer.music.pause() #暂停播放音乐
time += 1
if event.key == K_SPACE and time == 1:
pygame.mixer.music.unpause()#继续播放音乐
time -= 1
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()
页:
[1]