利用Pythoncurses实现终端音乐播放器
发布时间:2024-01-14 08:47:41
Python curses是一个在终端中创建文本界面的库,它可以用来创建终端音乐播放器。下面是一个使用Python curses实现的简单终端音乐播放器的例子:
import curses
import os
import time
# 定义播放器类
class MusicPlayer:
def __init__(self, stdscr):
self.stdscr = stdscr
self.music_dir = '/path/to/music/directory' # 音乐文件夹的路径
self.music_files = [] # 音乐文件列表
self.current_music = None # 当前播放的音乐文件
self.playing = False # 播放状态,True表示正在播放,False表示停止
# 初始化音乐文件列表
def init_music_files(self):
self.music_files = []
for root, dirs, files in os.walk(self.music_dir):
for file in files:
if file.endswith('.mp3'): # 只保留mp3文件
self.music_files.append(os.path.join(root, file))
# 播放音乐
def play_music(self, music_file):
self.current_music = music_file
# 编写你的播放音乐的代码,这里只是一个示例
print('正在播放音乐:', music_file)
self.playing = True
# 停止播放音乐
def stop_music(self):
if self.playing:
# 编写你的停止播放音乐的代码
print('停止播放音乐:', self.current_music)
self.playing = False
# 显示音乐列表
def show_music_list(self):
self.stdscr.clear()
self.stdscr.addstr('音乐列表:
')
for i, file in enumerate(self.music_files):
if file == self.current_music:
self.stdscr.addstr('>> ')
self.stdscr.addstr(file + '
')
self.stdscr.refresh()
# 运行播放器
def run(self):
# 初始化音乐文件列表
self.init_music_files()
# 显示音乐列表
self.show_music_list()
while True:
key = self.stdscr.getch()
if key == ord('q'): # 按下q键退出
break
elif key == ord('p'): # 按下p键播放当前选中的音乐
if self.current_music:
self.play_music(self.current_music)
elif key == ord('s'): # 按下s键停止播放音乐
self.stop_music()
elif key == curses.KEY_UP: # 按下上箭头键,选择上一首音乐
if self.current_music:
index = self.music_files.index(self.current_music)
if index > 0:
self.current_music = self.music_files[index - 1]
self.show_music_list()
elif key == curses.KEY_DOWN: # 按下下箭头键,选择下一首音乐
if self.current_music:
index = self.music_files.index(self.current_music)
if index < len(self.music_files) - 1:
self.current_music = self.music_files[index + 1]
self.show_music_list()
# 主函数
def main(stdscr):
player = MusicPlayer(stdscr)
player.run()
# 运行主函数
if __name__ == '__main__':
curses.wrapper(main)
上面的代码实现了一个简单的终端音乐播放器。音乐播放器会读取指定路径下的音乐文件,并提供功能:显示音乐列表、选择音乐、播放音乐、停止播放音乐。用户可以使用上下箭头键选择音乐,按下p键播放当前选中的音乐,按下s键停止播放音乐。
在你的电脑上执行上面的代码后,你可以根据实际情况修改self.music_dir为你本地音乐文件夹的路径。执行后,终端会显示音乐列表,选择音乐并按下p键即可播放音乐,按下s键停止播放音乐。当按下上下箭头键切换音乐时,音乐列表中当前选中的音乐会显示>>表示。
这只是一个简单的示例,你可以根据实际需求在play_music方法中编写你的播放音乐的代码。此外,你还可以扩展这个终端音乐播放器,添加一些其他的功能,比如暂停、快进、音量调整等。
