파이썬/프로젝트

mp3 프로그램

watervin 2022. 1. 14. 16:49

mp3player

#MP3Player
#   데이터 : 노래 목록, song, BASE_DIR, current_index
#   기능 : 목록, 재생, 다음, 이전, 종료 ---> 메뉴 구성

from baseapp import Application
from pygame import mixer
import eyed3
from file_util import get_file_list
import os



class MP3Player(Application):
    def __init__(self):
        super().__init__("MP3Player")
        self.DIR_PATH = "c:/temp/music"
        self.song_list = []
        self.song = None
        self.current_index = -1

    def create_menu(self):
        self.menu.add_menu('목록', self.print_list)
        self.menu.add_menu('재생', self.play)
        self.menu.add_menu('정지', self.stop)
        self.menu.add_menu('다음', self.play_next)
        self.menu.add_menu('이전', self.play_prev)
        self.menu.add_menu('종료', self.exit)
        
    def init(self):
        super().init()
        mixer.init()
        self.song_list = get_file_list(self.DIR_PATH,'.mp3')

    def print_list(self):
    
        for ix, song in enumerate(self.song_list):
            print(f'{ix}] {song}')
        print()

   
    def play(self):
        self.current_index = int(input('선곡: '))

        self.play_music(self.current_index)

    def print_tag(file_path):
        try:
            s = eyed3.load(file_path)
            print(f'가수: {s.tag.artist}')
            print(f'앨범: {s.tag.album}')
            print(f'곡명: {s.tag.title}')
        except:
            print(file_path)

    def play_music(self,index):

        if self.song:
            self.song.stop()

            self.song_path = os.path.join(self.DIR_PATH, self.song_list[index])
            self.print_tag(song_path)
            # print(f'곡명: {song_list[index]}')
            self.song = mixer.Sound(song_path)
            self.song.play()

    def play_music(self, index):
        if self.song:
            self.song.stop()

        song_path = os.path.join(self.DIR_PATH, self.song_list[index])
        self.print_tag(song_path)
        self.song = mixer.Sound(song_path)  # mixer 모듈안의 정의된 Sound 클래스의 인스턴스를 생성, __init__(self, filepath)
        self.song.play()

    def stop(self):
       
        if self.song:
            self.song.stop()
        self.song = None
    
    def play_prev(self):

        self.current_index -= 1
        if self.current_index == -1:  # 첫번째 곡에서 이전이면, 마지막 곡으로
            self.current_index = len(self.song_list) - 1
        
        self.play_music(self.current_index)
    
    def play_next(self):

        self.stopcurrent_index += 1
        if self.current_index == len(self.song_list):
                self.current_index = 0

            # curent_index =  (curent_index+1) % len(song_list)
        self.play_music(self.current_index)
  
    


def main():
    
    app = MP3Player()
    app.run()
   
main()

baseapp.py

#애플리케이션 : Application
#   데이터 : 앱 이름, 메뉴
#   기능 : 초기화, 메뉴 구성, 종료, 운영
import sys
from menu import Menu

class Application:
    def __init__(self, title):
        self.title = title
        self.menu = Menu()

    def create_menu(self):
        pass

    def init(self):
        self.create_menu()

    def exit(self):
        answer = input('종료할까요? (y/n)').lower()
        if answer == 'y':
            sys.exit()

    def run(self):
        self.init()
        while True:
            print(f'[{self.title}]')
            self.menu.print()
            item = self.menu.select()

            if item:
                item.run()
            else:
                print("잘못된 메뉴입니다.")
            
            print()

file_util.py

import pickle
import json
import os

def save(file_name, data):
  try:
    with open(file_name, "wb") as file:
      pickle.dump(data, file)
  except Exception as e:
    print(e)


def save_json(file_name, data):
  try:
    with open(file_name, "wt") as file:
      json.dump(data, file)
  except Exception as e:
    print(e)


def load(file_name):
  try:
    with open(file_name, "rb") as file:
      data = pickle.load(file)
      return data
  except Exception as e:
    print(e)


def load_json(file_name):
  try:
    with open(file_name, "rt") as file:
      data = json.load(file)
      return data
  except Exception as e:
    print(e)


def get_file_list(dir_path, ext):
  files = os.listdir(dir_path)
  files = list(filter(lambda name: name.endswith(ext), files))
  return files

menu.py

#메뉴 개념  --> 클래스로 표현

#메뉴 하나
#   MenuItem
#       데이터 : 타이틀, 메뉴 함수에 대한 참조
#       기능 : 메뉴 함수 실행

class MenuItem:
    def __init__(self, title, func):
        self.title = title
        self.func = func

    def run(self):
        self.func()


# def print_list():
#     print('print_list 실행')

# def main():
#     item = MenuItem("목록", print_list)
#     item.run()
# main()

#메뉴 만들기
#   데이터 : MenuItem의 콜렉션 --> 사전
#   기능 : 선택, 메뉴 보여주기, 메뉴 추가

class Menu:
    def __init__(self):
        self.menus = {}

    def add_menu(self, title, func):
        item = MenuItem(title, func)
        self.menus[title] = item

    def print(self):
        titles = self.menus.keys()
        print("="*30)
        print(' '.join(titles))
        print("="*30)
    
    def select(self):
        choice = input('선택> ')
        item = self.menus.get(choice)
        return item

# def print_list():
#     print('print_list 실행')

# def play():
#     print('play 실행')

# def exit():
#     print('종료')

# menu = Menu()
# menu.add_menu('목록',print_list)
# menu.add_menu('재생', play)
# menu.add_menu('종료',exit)

# menu.print()
# item = menu.select()
# item.run()

'파이썬 > 프로젝트' 카테고리의 다른 글

맥북 파이썬 python conda interpreter 가상화면 설치하기  (0) 2022.06.01
프로젝트 정리  (0) 2022.04.04
mp3 프로그램  (0) 2022.01.12
명함관리프로그램  (0) 2022.01.10