本文主要是介绍python快速实现简易电子音乐盒(电子钢琴),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
首先第一步附上完整源码(基于pygame库)
import pygame# 初始化pygame
pygame.init()# 设置窗口大小
window_size = (800, 600)
screen = pygame.display.set_mode(window_size)# 加载音频文件
C4 = pygame.mixer.Sound("test1/C4.wav")
D4 = pygame.mixer.Sound("test1/D4.wav")
E4 = pygame.mixer.Sound("test1/E4.wav")
F4 = pygame.mixer.Sound("test1/F4.wav")
G4 = pygame.mixer.Sound("test1/G4.wav")
A4 = pygame.mixer.Sound("test1/A4.wav")
B4 = pygame.mixer.Sound("test1/B4.wav")# 设置按键位置和大小
C4_rect = pygame.Rect(50, 50, 50, 200)
D4_rect = pygame.Rect(120, 50, 50, 200)
E4_rect = pygame.Rect(190, 50, 50, 200)
F4_rect = pygame.Rect(260, 50, 50, 200)
G4_rect = pygame.Rect(330, 50, 50, 200)
A4_rect = pygame.Rect(400, 50, 50, 200)
B4_rect = pygame.Rect(470, 50, 50, 200)# 绘制按键
pygame.draw.rect(screen, (255, 255, 255), C4_rect)
pygame.draw.rect(screen, (255, 255, 255), D4_rect)
pygame.draw.rect(screen, (255, 255, 255), E4_rect)
pygame.draw.rect(screen, (255, 255, 255), F4_rect)
pygame.draw.rect(screen, (255, 255, 255), G4_rect)
pygame.draw.rect(screen, (255, 255, 255), A4_rect)
pygame.draw.rect(screen, (255, 255, 255), B4_rect)# 设置按键文字
font = pygame.font.Font(None, 36)
C4_text = font.render("C4", True, (0, 0, 0))
D4_text = font.render("D4", True, (0, 0, 0))
E4_text = font.render("E4", True, (0, 0, 0))
F4_text = font.render("F4", True, (0, 0, 0))
G4_text = font.render("G4", True, (0, 0, 0))
A4_text = font.render("A4", True, (0, 0, 0))
B4_text = font.render("B4", True, (0, 0, 0))# 绘制按键文字
screen.blit(C4_text, (C4_rect.x + 10, C4_rect.y + 80))
screen.blit(D4_text, (D4_rect.x + 10, D4_rect.y + 80))
screen.blit(E4_text, (E4_rect.x + 10, E4_rect.y + 80))
screen.blit(F4_text, (F4_rect.x + 10, F4_rect.y + 80))
screen.blit(G4_text, (G4_rect.x + 10, G4_rect.y + 80))
screen.blit(A4_text, (A4_rect.x + 10, A4_rect.y + 80))
screen.blit(B4_text, (B4_rect.x + 10, B4_rect.y + 80))# 更新屏幕
pygame.display.flip()# 循环监听事件
while True:for event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit()exit()elif event.type == pygame.MOUSEBUTTONDOWN:# 判断鼠标点击位置是否在按键内if C4_rect.collidepoint(event.pos):C4.play()elif D4_rect.collidepoint(event.pos):D4.play()elif E4_rect.collidepoint(event.pos):E4.play()elif F4_rect.collidepoint(event.pos):F4.play()elif G4_rect.collidepoint(event.pos):G4.play()elif A4_rect.collidepoint(event.pos):A4.play()elif B4_rect.collidepoint(event.pos):B4.play()
第二步直接展示运行效果
由于没有录视频,只能看一下运行截图,实际用鼠标点击琴键则会播放音乐/音效
当你点击每一个琴键时,就会产生音乐/音效。如果你把每个键都点一遍,则会7个对应的音频文件合起来产生混合音效(或者连续点击某一个琴键时也是如此)
可以根据需要修改自己的音频文件,以及相应的路径,wav格式可以直接把mp4格式的音频修改后缀名即可。
此版本为基础性雏形实现,后期如有需要可基于此进行扩展和优化,实现一个真正的完整的音乐盒或者电子琴 。音乐盒使用多个正常时长的音乐音频文件,电子琴使用多个特定的瞬时音效音频文件。
这篇关于python快速实现简易电子音乐盒(电子钢琴)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!