[Python]简易terminal歌词滚动播放器
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Python]简易terminal歌词滚动播放器相关的知识,希望对你有一定的参考价值。
整合了网易云的一些API,想写一个terminal版的音乐播放器,但是还没有想好写成什么样子。
暂时写了一个必须又的功能:带歌词滚动的播放器,用了pygame里的mixer来播放音乐。
准备有时间的时候实现一下其他的功能。
1 # -*- coding:utf-8 -*- 2 import re 3 import os 4 import time 5 import copy 6 import threading 7 import pygame 8 from pygame import mixer 9 10 11 def read_file(path): 12 if not os.path.exists(path): 13 print ‘path : \\‘‘ + path + ‘\\‘ not find.‘ 14 return [] 15 content = ‘‘ 16 try: 17 with open(path, ‘r‘) as fp: 18 content += reduce(lambda x, y: x + y, fp) 19 finally: 20 fp.close() 21 return content.split(‘\\n‘) 22 23 class Lyrics: 24 TIME_AXIS_REGEXP = re.compile(‘\\[(\\d+)\\:(\\d+)\\.(\\d+)\\]‘) 25 DEL_TIME_AXIS_REGEXP = re.compile(‘\\[\\d+\\:\\d+\\.\\d+\\](.*)‘) 26 27 def __init__(self, path): 28 self.path = path 29 30 def _get_time_diff(self, line): 31 tm = map(lambda each: map(int, each), self.TIME_AXIS_REGEXP.findall(line)) 32 tm = map(lambda each: each[0] * 60 * 1000 + each[1] * 1000 + each[2], tm) 33 return (tm[0], line) 34 35 def _show_lyric(self, line): 36 print line 37 38 def static_lyric(self, lyrics): 39 for line in lyrics: 40 self._show_lyric(line) 41 42 def dynamic_lyric(self, lyrics): 43 for line in lyrics: 44 try: 45 time.sleep(float(line[0]) / 1000.0) 46 self._show_lyric(line[1]) 47 except: 48 pass 49 50 def get_lyric(self): 51 lyrics = read_file(self.path) 52 tmp_lyric = lyrics 53 lyrics = filter(lambda line: len(self.TIME_AXIS_REGEXP.findall(line))!=0, lyrics) 54 if len(lyrics) == 0: 55 return False, tmp_lyric 56 lyrics = map(self._get_time_diff, lyrics) 57 tmp_lyric = copy.deepcopy(lyrics[:-1]) 58 tmp_lyric.insert(0, (0, ‘‘)) 59 lyrics = map(lambda x:(x[0][0]-x[1][0], x[0][1]), zip(lyrics, tmp_lyric)) 60 lyrics = map(lambda x: (x[0], self.DEL_TIME_AXIS_REGEXP.findall(x[1])[0]), lyrics) 61 return True, lyrics 62 63 def show_lyric(self): 64 play_option, lyrics = self.get_lyric() 65 if play_option == True: 66 self.dynamic_lyric(lyrics) 67 else: 68 self.static_lyric(lyrics) 69 70 def play_mp3(path): 71 mixer.init() 72 track = mixer.music.load(path) 73 mixer.music.play(1) 74 75 def play(mp3_path, lrc_path): 76 t_mp3 = threading.Thread(target=play_mp3(mp3_path)) 77 lyrics = Lyrics(lrc_path) 78 t_lyric = threading.Thread(target=lyrics.show_lyric()) 79 80 t_mp3.start() 81 t_lyric.start() 82 t_mp3.join() 83 t_lyric.join() 84 85 86 def __main__(): 87 play(‘./test1.mp3‘, ‘./test1.lrc‘) 88 89 if __name__ == ‘__main__‘: 90 __main__()
以上是关于[Python]简易terminal歌词滚动播放器的主要内容,如果未能解决你的问题,请参考以下文章