pygame高级音乐播放器的python相关知识复习

1说明:
1.1pygame音乐播放器:
1.2在他基础上对代码进行删除、修改、润色、改进、注释等处理,突出重点,提高可读性。
1.3复习:python法。
1.3.1图片的相关知识,将jpg转换png法,修改图片大小。
1.3.2如何将mp3转换OGG格式。
1.4没有的模块,自己pip安装。
1.5python3.8和微软vscode编辑器,亲测过,值得收藏和分享,可以转发。
1.6增加tool文件夹,里面都是python的文件,可以进行相关转换。
2文件结构:简化过
3简化过的代码:完整版:pymusic.py
#—第1步:导出模块—importos,pygamefrompygame.localsimportfromsysimportexitfromrandomimport#—第2步:初始化pygame,窗口标题、大小设定等—pygame.init()pygame.display.set_caption(‘pygame高级音乐播放器’)#pygame的特点,就是屏幕大小的设定,与挂在屏幕上的图片和文字等有关,所以需要单独定义#尽管有点觉得代码繁琐,大型游戏和项目还是推荐这样#推荐大小1280和850SCREEN_W=1280SCREEN_H=850#注意没有H+20干嘛,就是后面的显示底部信息栏用的SCREEN_DEFAULT_SIZE=(SCREEN_W,SCREEN_H+20)screen=pygame.display.set_mode(SCREEN_DEFAULT_SIZE,0,32)#背景图片设置,需放在screen定义之后,否则报错,大小1366×768,可以用代码修改bg=pygame.image.load(‘/home/xgj/Desktop/src/image/bg.jpg’).convert()#通用字体和大小设置font=pygame.font.Font((‘/home/xgj/Desktop/src/hwfs.ttf’),24)#—第3步:个性化设置:初始化音量,图片坐标,按钮坐标等设置—VOLUME=5IMAGE_START_POS=(60,60)#图片初始化坐标IMAGE_END_POS=(245,245)#图片结束坐标#因为播放按钮的是作者画出的,所以坐标、半径、宽度定义CIRCLES_POS=[(85,350),(150,350),(215,350),(280,350),(555,425)]CIRCLR_R=25CIRCLR_W=3#—第4步:路径和歌曲列表等#注意路径和目录,如果打包,可能路径和目录需要从新设计IMAGE_DIR=‘/home/xgj/Desktop/src/image’#放音乐的路径SOUND_DIR=‘/home/xgj/Desktop/src/sound’#演唱者的图片大小=size:(240*240)SONG_FLAG=0#音乐文件OGG放在/home/xgj/Desktop/src/sound下#图片png放在/home/xgj/Desktop/src/image下#可自定义,其他信息可以自定义#比如自己换歌曲,换图片,即可#歌曲列表SONGS=[(‘1.OGG’,‘YouRaiseMeUp’,‘WestLife’,‘1.png’),(‘2.OGG’,‘不完整的旋律’,‘王力宏’,‘2.png’),(‘3.OGG’,‘APlaceNearby’,‘LeneMarlin’,‘3.png’),(‘4.OGG’,‘JustGiveMeAReason’,‘Pink’,‘4.png’),(‘5.OGG’,‘我’,‘张国荣’,‘5.png’),(‘6.OGG’,‘大城小爱’,‘王力宏’,‘6.png’),(‘7.OGG’,‘聊天’,‘郭静’,‘7.png’)]#—第5步:音量定义—VOLUME_POINTS=[]VOLUME_POINTS_START=[]VOLUME_RECT_COLORS=[]forpinrange(170,250,7):#音量位置,因为信息栏的字体变大后需要调整#减去300与下面的音量5的设置调整一下,一前一后。VOLUME_POINTS.append([SCREEN_W-p-300,SCREEN_H-40])forpsinrange(175,250,7):#位置VOLUME_POINTS_START.append([SCREEN_W-ps-300,SCREEN_H-40])#音量随机颜色VOLUME_RECT_COLORS.append((randint(0,255),randint(0,255),randint(0,255)))#—第6步:歌曲播放设置—SONG_ARRAY=[]SONG_IMAGE=[]forsonginrange(len(SONGS)):#简化过SONG_ARRAY.append(pygame.mixer.Sound(os.path.join(SOUND_DIR,SONGS[song][0])))SONG_IMAGE.append(pygame.image.load(os.path.join(IMAGE_DIR,SONGS[song][3])).convert())#—第7步:画歌曲图片定义—defdraw_picture_rect():#屏幕、颜色、坐标pygame.draw.rect(screen,(255,255,255),Rect(IMAGE_START_POS,IMAGE_END_POS))#—第8步:音乐播放等按钮绘画—#播放=play按钮defbutton_play(screen,color):pygame.draw.circle(screen,color,CIRCLES_POS[0],CIRCLR_R,CIRCLR_W)points=[(77,340),(77,360),(95,350)]pygame.draw.polygon(screen,color,points)#暂停=stop按钮defbutton_stop(screen,color):pygame.draw.circle(screen,color,CIRCLES_POS[0],CIRCLR_R,CIRCLR_W)pygame.draw.rect(screen,color,Rect(77,340,5,23))pygame.draw.rect(screen,color,Rect(88,340,5,23))#上一首=perfer按钮defbutton_perfer(screen,color):pygame.draw.circle(screen,color,CIRCLES_POS[1],CIRCLR_R,CIRCLR_W)points=[(138,340),(162,340),(150,363)]pygame.draw.polygon(screen,color,points)#删除=del按钮defbutton_del(screen,color):pygame.draw.circle(screen,color,CIRCLES_POS[2],CIRCLR_R,CIRCLR_W)pygame.draw.circle(screen,color,(215,340),6,3)pygame.draw.rect(screen,color,Rect(200,340,30,6))pygame.draw.rect(screen,color,Rect(204,340,3,20))pygame.draw.rect(screen,color,Rect(210,340,3,20))pygame.draw.rect(screen,color,Rect(217,340,3,20))pygame.draw.rect(screen,color,Rect(223,340,3,20))pygame.draw.rect(screen,color,Rect(204,360,22,5))#下一首=next按钮defbutton_next_song(screen,color):pygame.draw.circle(screen,color,CIRCLES_POS[3],CIRCLR_R,CIRCLR_W)points_one=[(270,343),(270,357),(277,350)]points_two=[(277,343),(277,357),(284,350)]pygame.draw.polygon(screen,color,points_one)pygame.draw.polygon(screen,color,points_two)pygame.draw.rect(screen,color,Rect(284,343,5,15))#—播放等按钮绘画—作者很牛是不是,点个赞—#—第9步:全局定义flag,监听鼠标点击按钮事件函数—PLAY_FLAG=TruePREFER_FLAG=True#鼠标点击播放等按钮的监听设置defmouse_down_listener(sound):globalPLAY_FLAGglobalPREFER_FLAGglobalSONG_FLAG#获取鼠标点击的坐标x,y=pygame.mouse.get_pos()forindexinrange(len(CIRCLES_POS)):p_x=(CIRCLES_POS[index][0]-x)2p_y=(CIRCLES_POS[index][1]-y)2p_r=(CIRCLR_R)**2if(p_x+p_y<=p_r):ifindex==0andPLAY_FLAG:sound.stop()PLAY_FLAG=Falseelifindex==0andnotPLAY_FLAG:sound.play(0)PLAY_FLAG=Trueelifindex==1andPREFER_FLAG:PREFER_FLAG=Falseelifindex==1andnotPREFER_FLAG:PREFER_FLAG=Trueelifindex==2:sound.stop()ifSONG_FLAG>0:SONGS.pop(SONG_FLAG)SONG_IMAGE.pop(SONG_FLAG)SONG_ARRAY.pop(SONG_FLAG)ifSONG_FLAG>=len(SONGS)-1:SONG_FLAG-=1else:#print(‘Thisisthelastsong.’)#这个注释掉后需要加个passpasselifindex==3:sound.stop()ifSONG_FLAG<len(SONGS)-1:SONG_FLAG+=1else:SONG_FLAG=0#—第10步:定义画按钮的点击函数,即播放还是暂停音乐等—defdraw_button(sound):color=(255,255,255)color_red=(230,0,0)#playorstopifPLAY_FLAG:sound.play(0)button_stop(screen,color)elifnotPLAY_FLAG:button_play(screen,color)#perfersongifPREFER_FLAG:button_perfer(screen,color)elifnotPREFER_FLAG:button_perfer(screen,color_red)#deletebutton_del(screen,color)#nextsongbutton_next_song(screen,color)#—第11步:画音量信息和调节音量设置—defdraw_volume_info():#thebackgroundofvolume#20代表音量调节背景框的高度pygame.draw.rect(screen,(255,255,255),Rect((VOLUME_POINTS_START[-1][0],VOLUME_POINTS_START[-1][1]),(VOLUME_POINTS[-10][0]-VOLUME_POINTS_START[-1][0],20)))#thesizeofvolumeforvinrange(VOLUME+1):ifv>0:#20代表目前的音量高度pygame.draw.rect(screen,VOLUME_RECT_COLORS[v],Rect((VOLUME_POINTS_START[-v][0],VOLUME_POINTS_START[-v][1]),(VOLUME_POINTS[-v][0]-VOLUME_POINTS_START[-v][0],20)))#—第12步:歌曲名显示设置—defdraw_song_title():title=font.render(SONGS[SONG_FLAG][1],True,(255,165,0))songer=font.render(SONGS[SONG_FLAG][2],True,(255,255,255))screen.blit(title,(320,60))screen.blit(songer,(320,110))#—第13步:播放状态栏信息设置—defdraw_state_bar_info():#底部歌曲信息栏的水平红线pygame.draw.line(screen,(165,42,42),(0,SCREEN_H-70),(SCREEN_W,SCREEN_H-70))#musicinfomusic_info=‘AllSongs:’+str(len(SONGS))+‘Current:’+str(SONG_FLAG+1)#font是通用字体设置text=font.render(music_info,True,(255,255,255))#-50,则信息栏的文字往上提高,便于字体变大后的显示screen.blit(text,(0,SCREEN_H-50))#volumeinfo,bug,str(VOLUME)当按左右箭头调节音量时,原来是5,之后的数字覆盖而模糊volume_text=font.render(‘Volume:’+str(VOLUME),True,(255,255,255))screen.blit(volume_text,(SCREEN_W-750,SCREEN_H-50))#authorintoauthor_info=font.render(‘hongtenzone@foxmail.com’,True,(255,255,255))screen.blit(author_info,(SCREEN_W-300,SCREEN_H-50))#—第14步:播放循环—whileTrue:screen.blit(bg,(0,0))pic=SONG_IMAGE[SONG_FLAG]bg_sound=SONG_ARRAY[SONG_FLAG]bg_sound.set_volume(0.1*VOLUME)draw_button(bg_sound)#listener()foreventinpygame.event.get():ifevent.type==QUIT:bg_sound.stop()exit()elifevent.type==KEYDOWN:#音量调节设置,←和→的定义ifevent.key==K_LEFT:ifVOLUME>0:VOLUME-=1elifevent.key==K_RIGHT:ifVOLUME<=9:VOLUME+=1pygame.display.update()elifevent.type==MOUSEBUTTONDOWN:pressed_array=pygame.mouse.get_pressed()forindexinrange(len(pressed_array)):ifpressed_array[index]:ifindex==0:#WhentheLEFTbuttondown#鼠标点击播放等按钮的监听mouse_down_listener(bg_sound)#picturerectdraw_picture_rect()#volumeinformationdraw_volume_info()#statebarinformationdraw_state_bar_info()#songtitledraw_song_title()#显示图片坐标,与上面的60和60坐标相呼应#screen.blit(pic,(62.5,62.5))#最新的python3.8和pygame1.9.6浮点数是报错screen.blit(pic,(62,62))pygame.display.update()
注意路径自定义。
4效果:
小bug:当前曲目:1~7和音量调节数字1~10,模糊不清;启动有点慢。
5相关工具介绍:3个好工具。
5.1mp3toogg.py代码:用来将mp3转换为OGG音乐文件。
奇怪,原作者为什么不用mp3格式的音乐文件呢?莫非他也是采纳国外某些人的习惯么?我也是第一次接触OGG音乐文件,是不是可以改为mp3音乐文件操作起来更简单些。
frompydubimportAudioSegment#注意路径song=AudioSegment.from_mp3(“/home/xgj/Desktop/src/1.mp3”)#song.export(“out.ogg”,format=“ogg”)#Isthesameas:song.export(“out.ogg”,format=“ogg”,codec=“libvorbis”)
5.2picsize.py代码:调节图片大小的。
fromPILimportImageimportos#获取文件大小:KBdefget_size(file):size=os.path.getsize(file)returnsize/1024#输出文件defget_outfile(infile,outfile):ifoutfile:returnoutfiledir,suffix=os.path.splitext(infile)outfile=‘{}-out{}’.format(dir,suffix)returnoutfile#修改图片函数defresize_image(infile,outfile=‘’,x_s=1376):im=Image.open(infile)#输出指定大小,60×60大小图片out=im.resize((1366,768),Image.ANTIALIAS)outfile=get_outfile(infile,outfile)out.save(outfile)#主函数ifname==‘main’:#路径可自定义resize_image(‘/home/xgj/Desktop/src/data/image/background/bg.jpg’)
5.3图片格式转换:jpgtopng.py代码:
#pipinstallPillowimportPIL.ImageasImage#以第一个像素为准,相同色改为透明deftransparent_back(img):img=img.convert(‘RGBA’)L,H=img.sizecolor_0=(255,255,255,255)#要替换的颜色forhinrange(H):forlinrange(L):dot=(l,h)color_1=img.getpixel(dot)ifcolor_1==color_0:color_1=color_1[:-1]+(0,)img.putpixel(dot,color_1)returnimgifname==‘main’:img=Image.open(‘1231.jpg’)img=transparent_back(img)img.save(‘1231.png’)
好东西拿来分享,值得收藏。