player.py
import os
import sys
from pygame import mixer
import eyed3
from file_util import get_file_list
DIR_PATH = "c:/temp/music" # 음악 파일 디렉토리
song_list = [] # 재생 목록
song = None # 현재 재생중인 파일
current_index = -1 # 현재 재생 파일의 인덱스
# 메뉴
# 목록 재생 정지 이전 다음 종료
def init():
global song_list
mixer.init()
song_list = get_file_list(DIR_PATH, '.mp3')
# 목록 보여주기
def print_list():
# 0] song1.mp3
for ix, song in enumerate(song_list):
print(f'{ix}] {song}')
print()
# 선곡해서 재생하기
def play():
# 선곡: 2
global current_index, song
current_index = int(input('선곡: '))
play_music(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(index):
global song
# 이전에 재생중이면 먼저 정지
if song:
song.stop()
song_path = os.path.join(DIR_PATH, song_list[index])
print_tag(song_path)
# print(f'곡명: {song_list[index]}')
song = mixer.Sound(song_path)
song.play()
def stop():
global song
if song:
song.stop()
song = None
def play_prev():
global song, current_index
current_index -= 1
if current_index == -1: # 첫번째 곡에서 이전이면, 마지막 곡으로
current_index = len(song_list) - 1
play_music(current_index)
# 다음 곡 재생
def play_next():
global song, current_index
current_index += 1
if current_index == len(song_list):
current_index = 0
# curent_index = (curent_index+1) % len(song_list)
play_music(current_index)
def exit():
sys.exit(0)
def print_menu():
print('-'*40)
print('목록 재생 정지 이전 다음 종료')
print('-'*40)
def main():
init()
while True:
print_menu()
select = input('선택>')
if select == '목록':
print_list()
elif select == '재생':
play()
elif select == '정지':
stop()
elif select == '이전':
play_prev()
elif select == '다음':
play_next()
elif select == '종료':
exit()
else:
print('잘못된 명령입니다.')
main()
|
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
|