• pygame 简单播放音乐程序


    环境:

    python2.7

    pygame 

    功能:

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

    文件目录:

    font  字体文件夹

    image  图片文件夹

    music  音乐文件夹

    play.py  主程序

    settings.py  配置文件

    settings.py

    # -*- coding: utf-8 -*-
    # setting 配置文件
    import os
    from os import path
    d = os.path.dirname(__file__)
    ## music file path
    MUSIC_PATH = path.join(d, 'music/')
    ## image file path
    IMAGE_PATH = path.join(d, 'image/')
    ## auto play
    AUTO_PALY = False
    ## paly type    we can wav or m4a  -> mp3
    PLAY_TYPE = ['.mp3','.wav','.m4a']
    ## DEFAULT play start
    PLAY_START = 0

    play.py

    # -*- coding: utf-8 -*-
    import time
    import pygame
    from pygame.locals import *
    import os
    import sys
    from settings import  *
    d = os.path.dirname(__file__)
    class window:
        def __init__(self):
            pygame.init()
            pygame.display.set_caption("player")
            bgColor = (255, 230, 230)
            self.screen = pygame.display.set_mode((640, 480))
            self.screen.fill(bgColor)
            ## 显示上一曲
            prve = pygame.image.load("image/prve.png").convert_alpha()
            width, height = prve.get_size()
            self.screen.blit(prve, (240 - width / 2, 40))
            self.prveX = (240 - width / 2, 320 + width / 2)
            self.prveY = (40, 40 + height)
            self.show_play_pause()
    
            ## 显示下一曲按钮
            next = pygame.image.load("image/next.png").convert_alpha()
            self.screen.blit(next, (400 - width / 2, 40))
            self.nextX = (320 - width / 2, 400 + width / 2)
            self.nextY = (40, 40 + height)
    
            ## 显示logo
            logo = pygame.image.load("image/pygame_logo.gif").convert_alpha()
            width, height = logo.get_size()
            self.screen.blit(logo, (320 - width / 2, 200))
    
            pygame.display.flip()
        def show_play_pause(self, type='player'):
            '''显示播放按钮'''
            print type
            if type == 'player':
                player = pygame.image.load("image/player.png").convert_alpha()
            else:
                player = pygame.image.load("image/pause.png").convert_alpha()
            width, height = player.get_size()
            self.screen.blit(player, (320 - width / 2, 40))
            self.playerX = (320 - width / 2, 320 + width / 2)
            self.playerY = (40, 40 + height)
            pygame.display.flip()
    
        def text_objects(self, text, font):
            ''' font'''
            textSurface = font.render(text, True, (233,150,122))
            return textSurface, textSurface.get_rect()
    
        def message_diaplay(self, text):
            '''show font'''
            largeText = pygame.font.Font('font/Deng.ttf', 14)
            TextSurf, TextRect = self.text_objects(text, largeText)
            TextRect.center = ((320), (150))
            self.screen.blit(TextSurf, TextRect)
            pygame.display.update()
    
    class Mp3:
        def __init__(self):
            self.playTrue = False   ##播放与停止
            self.playStart = False   ##是否已经开始
    
        def load_music(self, musicPath):
            print musicPath
            pygame.mixer.init()
            self.track = pygame.mixer.music.load(musicPath.encode('utf-8'))
    
        def play(self):
            if self.playTrue == False:
                if self.playStart == False:
                    print '[*] start play'
                    pygame.mixer.music.play()
                    Mywindow.message_diaplay(u'正在播放: %s' % musicList[PLAY_START])
                    self.playTrue = True
                    self.playStart = True
                    Mywindow.show_play_pause(type="pause")
                else:
                    print '[*] start unpause'
                    pygame.mixer.music.unpause()
                    Mywindow.message_diaplay(u'正在播放: %s' %  musicList[PLAY_START])
                    self.playTrue = True
                    Mywindow.show_play_pause(type="pause")
            else:
                print '[*] start pause'
                pygame.mixer.music.pause()
                Mywindow.message_diaplay(u'暂停播放: %s' % musicList[PLAY_START])
                self.playTrue = False
                Mywindow.show_play_pause()
    
    def getmusicList():
        print '[*] get music pool!!'
        musicFileList= os.listdir(MUSIC_PATH)
        # print file_lists
        ## get music type
        musicList =  []
        for v in musicFileList:
            print u'[*] this song is %s' % v.decode('gbk')
            v = v.decode('gbk')
            file = os.path.splitext(v)
            filename, type = file
            print '[*] filename is %s' % filename
            print '[*] type is %s' % type
            ## 判断当前类型是否存在可以播放的类型
            if type.lower() in PLAY_TYPE:
                print '[*] this song we can play!!'
                musicList.append(v)
            else:
                print '[*] this song we can not play!!'
        print '[*] this musiclist is ', musicList
        return musicList
    def changeMusic():
        print '[*] change music !!'
    
    
    if __name__ == '__main__':
        print '''          ____  __  __  __      __       _______  _______
             /__  \ \_\/_/ / /     / /____  / ___  / / ___  /
            / /_/ /  \__/ / /___  / /__  / / /  / / / /  / /
           / ____/   / / / /___/ / /  / / / /__/ / / /  / /
          /_/       /_/ /_/___/ /_/  /_/  \_____/ /_/  /_/'''
        musicList = getmusicList()
        Mywindow = window()
        mp3Player = Mp3()
        ## exit()
        if AUTO_PALY:
            print '[*] auto play!!'
            ## default load first song
            mp3Player.load_music(MUSIC_PATH + musicList[PLAY_START])
            ## play
            mp3Player.play()
        else:
            print '[*] no auto paly!!'
        while True:
            # 游戏主循环
            for event in pygame.event.get():
                if event.type == QUIT:
                    # 接收到退出事件后退出程序
                    print 'Good Bye~~'
                    exit()
                elif event.type == MOUSEBUTTONDOWN:
                    pressed_array = pygame.mouse.get_pressed()
                    for index in range(len(pressed_array)):
                        if pressed_array[index]:
                            if index == 0:
                                if Mywindow.playerX[0] < event.pos[0] < Mywindow.playerX[1] and Mywindow.playerY[0] < 
                                        event.pos[1] < Mywindow.playerY[1]:
                                    print '[*] click this player!!'
                                    ## 默认打开第一首歌曲
                                    if mp3Player.playStart:
                                        mp3Player.play()
                                    else:
                                        mp3Player.load_music(MUSIC_PATH + musicList[PLAY_START])
                                        mp3Player.play()
                                elif Mywindow.prveX[0] < event.pos[0] < Mywindow.prveX[1] and Mywindow.prveY[0] < 
                                        event.pos[1] < Mywindow.prveY[1]:
                                    print '[*] click this prve!!'
                                    if mp3Player.playStart:
                                        if PLAY_START == 0:
                                            print '[*] no song to prve_play'
                                        else:
                                            PLAY_START -= 1
                                            mp3Player = Mp3()
                                            mp3Player.load_music(MUSIC_PATH + musicList[PLAY_START])
                                            mp3Player.play()
                                    else:
                                        print '[*] no song is play!!'
                                elif Mywindow.nextX[0] < event.pos[0] < Mywindow.nextX[1] and Mywindow.nextY[0] < 
                                        event.pos[1] < Mywindow.nextY[1]:
                                    print '[*] click this next!!'
                                    if mp3Player.playStart:
                                        if PLAY_START == len(musicList)-1:
                                            print '[*] no song to next_play'
                                        else:
                                            PLAY_START += 1
                                            mp3Player = Mp3()
                                            mp3Player.load_music(MUSIC_PATH + musicList[PLAY_START])
                                            mp3Player.play()
                                    else:
                                        print '[*] no song is play!!'
    
    
    
    
    '''
    some problems:
    1、pygame 写的字如何更新值,而不是在同一位置再写入
    '''

    运行效果:

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

  • 相关阅读:
    从一个线上服务器警告谈谈backlog
    聊聊服务器的负载
    Apache 配置说明
    Apache 服务器性能评估
    php之apc浅探
    Linux 服务器 监控命令
    小白学习mysql 之 innodb locks
    小白学习mysql之存储过程的优劣分析以及接入控制
    小白学习mysql之索引初步
    小白学习mysql之优化基础(EXPLAIN的连接类型)
  • 原文地址:https://www.cnblogs.com/shuangzikun/p/python_taotao_pygame_mp3.html
Copyright © 2020-2023  润新知