import pygame
import sys
初始化 Pygame
pygame.init()
设置窗口大小
screen_width = 640
screen_height = 480
screen = pygame.display.set_mode((screen_width, screen_height))
设置标题
pygame.display.set_caption(‘Play Sound Example’)
加载音乐文件
pygame.mixer.init()
pygame.mixer.music.load(‘s1.wav’)
按钮的设置
button_play = pygame.Rect(500, 200, 90, 300) # 按钮的位置和大小
button_play_color = (0, 0, 255) # 按钮的颜色
button_play_clicked = False
主循环
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
sys.exit()
# 检测鼠标点击事件
if event.type == pygame.MOUSEBUTTONDOWN:
# 检测点击位置是否在按钮区域内
if button_play.collidepoint(event.pos):
button_play_clicked = True
# 检查按钮是否被点击
if button_play_clicked:
pygame.mixer.music.play()
button_play_clicked = False # 重置点击状态
# 绘制按钮
screen.fill((255, 255, 255)) # 填充背景色
pygame.draw.rect(screen, button_play_color, button_play) # 绘制按钮
pygame.display.flip() # 更新屏幕显示
# 控制游戏循环速度
pygame.time.Clock().tick(60)