新写的python 插入声音代码,大家一起学习!!!

import pygame
import sys
from pygame.locals import*

pygame.init()
pygame.mixer.init() #初始化混音器模块

pygame.mixer.music.load(“blackground.ogg”)
pygame.mixer.music.set_volume(0.2)
pygame.mixer.music.play()

#加载音效
cat_sound = pygame.mixer.Sound(“cat.wav”)
cat_sound.set_volume(0.2)
dog_sound = pygame.mixer.Sound(“bird.wav”)
dog_sound.set_volume(0.2)
bg_size = width,height = 300,300
screen = pygame.display.set_mode(bg_size)
pygame.display.set_caption(“Wallace-music”)
pause = False
pause_image = pygame.image.load(“pause.png”).convert_alpha()
unpause_image = pygame.image.load(“unpause.png”).convert_alpha()
pause_rect = pause_image.get_rect()
pause_rect.left,pause_rect.top = (width - pause_rect.width)//2,
(height - pause_rect.height)//2
clock = pygame.time.Clock()

while True:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
if event.type == MOUSEBUTTONDOWN:
if event.button == 1:
cat_sound.play()
if event.button == 3:
dog_sound.play()
if event.type == KEYDOWN:
if event.key == K_SPACE:
pause = not pause
screen.fill ((255,255,255))
if pause:
screen.blit(pause_image,pause_rect)
pygame.mixer.music.pause()
else:
screen.blit(unpause_image,pause_rect)
pygame.mixer.music.unpause()

pygame.display.flip()
clock.tick(30)

wav、ogg格式的文件为python支持的音频格式,mp3格式的音频需要转成上面的格式才能播放

你可能感兴趣的:(一怒)