Skip to content

Instantly share code, notes, and snippets.

@lilydjwg
Created Dec 6, 2021
Embed
What would you like to do?
#!/usr/bin/python3
import os
import sys
import random
from itertools import groupby
import subprocess
import pathlib
MUSIC_DIR = pathlib.Path('~/音乐').expanduser()
def sort_by_type(x):
# prefer opus
if x.endswith(('.opus', '.vorbis')):
return 1
elif x.endswith('.ogg'):
return 2
else:
return 3
def get_list(dir=MUSIC_DIR):
for dirpath, dirnames, filenames in os.walk(dir):
files = [
f for f in filenames
if not f.endswith(('~', '.lrc', '.txt', '.mid'))]
files.sort()
for k, g in groupby(files, key=lambda x: x.rsplit('.', 1)[0]):
g = sorted(g, key=sort_by_type)
p = pathlib.Path(os.path.join(dirpath, g[0]))
if not p.is_symlink():
yield p
def play(L, quiet: bool) -> None:
random.shuffle(L)
if quiet:
args = ['--really-quiet']
else:
args = []
subprocess.run(
['mpv', '--no-resume-playback', '--audio-display=no', '--playlist=-'] + args,
check=True, text=True,
input='\n'.join(str(x) for x in L),
)
if __name__ == '__main__':
try:
import setproctitle
setproctitle.setproctitle('playmusic')
del setproctitle
except ImportError:
pass
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-q', dest='quiet', action='store_true',
help='Be quiet')
parser.add_argument('search',
metavar='歌手或歌名', nargs='*',
help='过滤歌曲')
args = parser.parse_args()
if len(args.search) in [1, 2]:
artist = args.search[0]
if (dir := MUSIC_DIR / artist).is_dir():
L = list(get_list(dir))
if len(args.search) == 2:
name = args.search[1]
L = [x for x in L if x.stem == name]
else:
if len(args.search) == 2:
sys.exit(f'{artist} 不存在')
else:
name = artist
L = [x for x in get_list() if x.stem == name]
elif not args.search:
L = list(get_list())
else:
sys.exit('参数太多')
if args.search:
for song in L:
print(song)
print()
try:
play(L, args.quiet)
except KeyboardInterrupt:
print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment