环境:

python2.7

pygame

功能:

播放指定目录下的歌曲(暂时mp3),可以上一曲、下一曲播放。

文件目录:

font  字体文件夹

image  图片文件夹

music  音乐文件夹

play.py  主程序

settings.py  配置文件

settings.py

  1. # -*- coding: utf-8 -*-
  2. # setting 配置文件
  3. import os
  4. from os import path
  5. d = os.path.dirname(__file__)
  6. ## music file path
  7. MUSIC_PATH = path.join(d, 'music/')
  8. ## image file path
  9. IMAGE_PATH = path.join(d, 'image/')
  10. ## auto play
  11. AUTO_PALY = False
  12. ## paly type we can wav or m4a -> mp3
  13. PLAY_TYPE = ['.mp3','.wav','.m4a']
  14. ## DEFAULT play start
  15. PLAY_START = 0

play.py

  1. # -*- coding: utf-8 -*-
  2. import time
  3. import pygame
  4. from pygame.locals import *
  5. import os
  6. import sys
  7. from settings import *
  8. d = os.path.dirname(__file__)
  9. class window:
  10. def __init__(self):
  11. pygame.init()
  12. pygame.display.set_caption("player")
  13. bgColor = (255, 230, 230)
  14. self.screen = pygame.display.set_mode((640, 480))
  15. self.screen.fill(bgColor)
  16. ## 显示上一曲
  17. prve = pygame.image.load("image/prve.png").convert_alpha()
  18. width, height = prve.get_size()
  19. self.screen.blit(prve, (240 - width / 2, 40))
  20. self.prveX = (240 - width / 2, 320 + width / 2)
  21. self.prveY = (40, 40 + height)
  22. self.show_play_pause()
  23.  
  24. ## 显示下一曲按钮
  25. next = pygame.image.load("image/next.png").convert_alpha()
  26. self.screen.blit(next, (400 - width / 2, 40))
  27. self.nextX = (320 - width / 2, 400 + width / 2)
  28. self.nextY = (40, 40 + height)
  29.  
  30. ## 显示logo
  31. logo = pygame.image.load("image/pygame_logo.gif").convert_alpha()
  32. width, height = logo.get_size()
  33. self.screen.blit(logo, (320 - width / 2, 200))
  34.  
  35. pygame.display.flip()
  36. def show_play_pause(self, type='player'):
  37. '''显示播放按钮'''
  38. print type
  39. if type == 'player':
  40. player = pygame.image.load("image/player.png").convert_alpha()
  41. else:
  42. player = pygame.image.load("image/pause.png").convert_alpha()
  43. width, height = player.get_size()
  44. self.screen.blit(player, (320 - width / 2, 40))
  45. self.playerX = (320 - width / 2, 320 + width / 2)
  46. self.playerY = (40, 40 + height)
  47. pygame.display.flip()
  48.  
  49. def text_objects(self, text, font):
  50. ''' font'''
  51. textSurface = font.render(text, True, (233,150,122))
  52. return textSurface, textSurface.get_rect()
  53.  
  54. def message_diaplay(self, text):
  55. '''show font'''
  56. largeText = pygame.font.Font('font/Deng.ttf', 14)
  57. TextSurf, TextRect = self.text_objects(text, largeText)
  58. TextRect.center = ((320), (150))
  59. self.screen.blit(TextSurf, TextRect)
  60. pygame.display.update()
  61.  
  62. class Mp3:
  63. def __init__(self):
  64. self.playTrue = False ##播放与停止
  65. self.playStart = False ##是否已经开始
  66.  
  67. def load_music(self, musicPath):
  68. print musicPath
  69. pygame.mixer.init()
  70. self.track = pygame.mixer.music.load(musicPath.encode('utf-8'))
  71.  
  72. def play(self):
  73. if self.playTrue == False:
  74. if self.playStart == False:
  75. print '[*] start play'
  76. pygame.mixer.music.play()
  77. Mywindow.message_diaplay(u'正在播放: %s' % musicList[PLAY_START])
  78. self.playTrue = True
  79. self.playStart = True
  80. Mywindow.show_play_pause(type="pause")
  81. else:
  82. print '[*] start unpause'
  83. pygame.mixer.music.unpause()
  84. Mywindow.message_diaplay(u'正在播放: %s' % musicList[PLAY_START])
  85. self.playTrue = True
  86. Mywindow.show_play_pause(type="pause")
  87. else:
  88. print '[*] start pause'
  89. pygame.mixer.music.pause()
  90. Mywindow.message_diaplay(u'暂停播放: %s' % musicList[PLAY_START])
  91. self.playTrue = False
  92. Mywindow.show_play_pause()
  93.  
  94. def getmusicList():
  95. print '[*] get music pool!!'
  96. musicFileList= os.listdir(MUSIC_PATH)
  97. # print file_lists
  98. ## get music type
  99. musicList = []
  100. for v in musicFileList:
  101. print u'[*] this song is %s' % v.decode('gbk')
  102. v = v.decode('gbk')
  103. file = os.path.splitext(v)
  104. filename, type = file
  105. print '[*] filename is %s' % filename
  106. print '[*] type is %s' % type
  107. ## 判断当前类型是否存在可以播放的类型
  108. if type.lower() in PLAY_TYPE:
  109. print '[*] this song we can play!!'
  110. musicList.append(v)
  111. else:
  112. print '[*] this song we can not play!!'
  113. print '[*] this musiclist is ', musicList
  114. return musicList
  115. def changeMusic():
  116. print '[*] change music !!'
  117.  
  118. if __name__ == '__main__':
  119. print ''' ____ __ __ __ __ _______ _______
  120. /__ \\ \\_\\/_/ / / / /____ / ___ / / ___ /
  121. / /_/ / \\__/ / /___ / /__ / / / / / / / / /
  122. / ____/ / / / /___/ / / / / / /__/ / / / / /
  123. /_/ /_/ /_/___/ /_/ /_/ \\_____/ /_/ /_/'''
  124. musicList = getmusicList()
  125. Mywindow = window()
  126. mp3Player = Mp3()
  127. ## exit()
  128. if AUTO_PALY:
  129. print '[*] auto play!!'
  130. ## default load first song
  131. mp3Player.load_music(MUSIC_PATH + musicList[PLAY_START])
  132. ## play
  133. mp3Player.play()
  134. else:
  135. print '[*] no auto paly!!'
  136. while True:
  137. # 游戏主循环
  138. for event in pygame.event.get():
  139. if event.type == QUIT:
  140. # 接收到退出事件后退出程序
  141. print 'Good Bye~~'
  142. exit()
  143. elif event.type == MOUSEBUTTONDOWN:
  144. pressed_array = pygame.mouse.get_pressed()
  145. for index in range(len(pressed_array)):
  146. if pressed_array[index]:
  147. if index == 0:
  148. if Mywindow.playerX[0] < event.pos[0] < Mywindow.playerX[1] and Mywindow.playerY[0] < \
  149. event.pos[1] < Mywindow.playerY[1]:
  150. print '[*] click this player!!'
  151. ## 默认打开第一首歌曲
  152. if mp3Player.playStart:
  153. mp3Player.play()
  154. else:
  155. mp3Player.load_music(MUSIC_PATH + musicList[PLAY_START])
  156. mp3Player.play()
  157. elif Mywindow.prveX[0] < event.pos[0] < Mywindow.prveX[1] and Mywindow.prveY[0] < \
  158. event.pos[1] < Mywindow.prveY[1]:
  159. print '[*] click this prve!!'
  160. if mp3Player.playStart:
  161. if PLAY_START == 0:
  162. print '[*] no song to prve_play'
  163. else:
  164. PLAY_START -= 1
  165. mp3Player = Mp3()
  166. mp3Player.load_music(MUSIC_PATH + musicList[PLAY_START])
  167. mp3Player.play()
  168. else:
  169. print '[*] no song is play!!'
  170. elif Mywindow.nextX[0] < event.pos[0] < Mywindow.nextX[1] and Mywindow.nextY[0] < \
  171. event.pos[1] < Mywindow.nextY[1]:
  172. print '[*] click this next!!'
  173. if mp3Player.playStart:
  174. if PLAY_START == len(musicList)-1:
  175. print '[*] no song to next_play'
  176. else:
  177. PLAY_START += 1
  178. mp3Player = Mp3()
  179. mp3Player.load_music(MUSIC_PATH + musicList[PLAY_START])
  180. mp3Player.play()
  181. else:
  182. print '[*] no song is play!!'
  183.  
  184. '''
  185. some problems:
  186. 1、pygame 写的字如何更新值,而不是在同一位置再写入
  187. '''

运行效果:

还有部分问题需要解决,当然也只能玩玩~

pygame 简单播放音乐程序的更多相关文章

  1. Python使用Pygame.mixer播放音乐

    Python使用Pygame.mixer播放音乐 frequency这里是调频率... 播放网络中的音频: #!/usr/bin/env python # -*- coding: utf-8 -*- ...

  2. python3用pygame实现播放音乐文件

    import pygameimport time #导入音乐文件file = r'C:\1.wav'pygame.mixer.init()track = pygame.mixer.music.load ...

  3. 用PHP+H5+Boostrap做简单的音乐播放器(进阶版)

    前言:之前做了一个音乐播放器(纯前端),意外的受欢迎,然后有人建议我把后台一起做了,正好也想学习后台,所以学了两天php(不要吐槽我的速度,慢工出细活嘛~)然后在之前的基础上也又完善了一些功能,所以这 ...

  4. 简单的音乐播放器(VS 2010 + Qt 4.8.5)

    昨天历经千辛万苦,配置好了VS 2010中的Qt环境(包括Qt for VS插件),今天决定浅浅地品味一下将两者结合进行编程的魅力. 上网查了一些资料,学习了一些基础知识,决定做一个简单的音乐播放器, ...

  5. C#播放音乐,调用程序

    一:C# 播放音乐 string sound = Application.StartupPath + "/sound/msg.wav"; //Application.Startup ...

  6. Android之通过网络播放一首简单的音乐

    首先,附上程序执行后的效果.例如以下图所看到的: 一.部署一个web项目到tomcatserver上: 1.这个小程序是结合网络来播放一首音乐的,首先,把我们搞好的一个web项目放置在tomcat安装 ...

  7. 使用Service组件实现简单的音乐播放器功能 --Android基础

    1.本例利用Service实现简单的音乐播放功能,下面是效果图.(点击开始播放开启服务,音乐播放,点击“停止播放”关闭服务,音乐停止播放.) 2.核心代码: MusicService.java: pa ...

  8. swift3.0 简单直播和简单网络音乐播放器

    本项目采用swift3.0所写,适配iOS9.0+,所有界面均采用代码布局. 第一个tab写的是简单直播,传统MVC模式,第二个tab写的是简单网络音乐播放器.传说MVVM模式(至于血统是否纯正我就不 ...

  9. matlab播放音乐

    最近在做计算,写了一些matlab代码,脑壳还疼,所以决定发挥一下逗B精神,写一个程序玩一下. 想了想,既然写代码的时候喜欢听歌,而且我的电脑打开网易音乐的速度巨慢(不知道为什么..),那些一个程序直 ...

随机推荐

  1. MapServer Tutorial——MapServer7.2.1教程学习——第一节用例实践:Example 1.4 Labeling the Map

    MapServer Tutorial——MapServer7.2.1教程学习——第一节用例实践:Example 1.4 Labeling the Map 一.前言 MapServer拥有非常灵活的标签 ...

  2. iOS sqlite大数据分段加载的实现,sqlite数据库的操作

    数据库管理类(自己封装的,挺简单的) // //  MyDataBaseManger.m //  DB_Test // //  Created by admin on 17/2/7. //  Copy ...

  3. SQL Server--------SQL Server问题错误解决

    1.错误提示: 修改字段属性时,提示: 消息 5074,级别 16,状态 1,第 1 行对象'DF__dms_deliv__sync___51BAE991' 依赖于 列'sync_ff_result_ ...

  4. LNMP(二)

    第二十一课 LNMP(二) 目录 一.默认虚拟主机 二.Nginx用户认证 三.Nginx域名重定向 四.Nginx访问日志 五.Nginx日志切割 六.静态文件不记录日志和过期时间 七.Nginx防 ...

  5. Codeforces Round #281 (Div. 2) D(简单博弈)

    题目:http://codeforces.com/problemset/problem/493/D 题意:一个n*n的地图,有两个人在比赛,第一个人是白皇后开始在(1,1)位置,第二个人是黑皇后开始在 ...

  6. VBS下载者助以一臂之力

    当拿到shell到手,服务器是内网,你又没有条件映射,服务器又穿不上东西 是不是很郁闷,还有我们还有vbs,能执行cmd命令就有希望 一.VBS下载者: 复制代码 代码如下: Set Post = C ...

  7. Echarts tooltip 坐标值修改

    tooltip: { trigger: 'axis', position:function(p){ //其中p为当前鼠标的位置 console.log(p); ] + , p[] - ]; } },

  8. keil的可烧写hex文件生成

    右键Target1 Options Target for ‘Target1’ ...->Output->Create Executable:->Create HEX File Bui ...

  9. 关于Error during managed flush [Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1]错误

    控制台报错: 08:07:09.293 [http-bio-8080-exec-2] ERROR org.hibernate.internal.SessionImpl - HHH000346: Err ...

  10. 框架tensorflow1

    TensorFlow   1 分类: 1,protocol Buffer  处理结构化数据工具: (xml,json) 2,Bazel        自动化构建工具, 编译: tensor 张量:   ...