代码: 全选
#!/usr/bin/env python3
# fileencoding=utf-8
'''随机播放的 mocp'''
import os
import random
mocdir = os.path.expanduser('~/.moc/')
def getlist():
'''从默认播放列表获取文件列表'''
def getit(f):
l = []
for i in f:
i = i.strip()
if i.startswith('#'):
continue
l.append(i)
return l
file = os.path.join(mocdir, 'playlist.m3u')
try:
with open(file) as f:
l = getit(f)
except IOError as e:
if e.errno == 21:
print('错误:%s 是目录。' % e.filename, file=sys.stderr)
else:
print('未知错误:错误号', e.errno, ';错误信息', e.strerror, file=sys.stderr)
sys.exit(FileError)
return l
def playafile(l):
'''随机播放一个文件'''
file = random.choice(l)
file = os.path.abspath(file)
status = os.system("mocp --playit '%s'" % file)
print('播放文件 %s。' % file)
if status:
print('错误:子进程 mocp 返回了错误号 %d。' % status, file=sys.stderr)
def main():
playafile(getlist())
def usage():
print('''rmocp --- 让 mocp 随机播放音乐
说明:
运行此程序即可让 mocp 随机播放它的播放列表中的音乐。
在 mocp 中作如下设置可让其自动随机播放:
取消 AutoNext;
设置 OnStop 为本程序的绝对路径。
作者:
lilydjwg <lilydjwg@gmail.com>
版本:
1.0''')
if __name__ == '__main__':
main()
我对 mocp 使用的 socket 通信特别感兴趣,就自己做了个 rmocp 程序(见附件,程序自身有使用说明)。后来才注意到 mocp 的 --playit 选项,发现要实现随机播放根本不用那么复杂(就上面不到 100 行的代码)。不过对于 socket 通信倒是学了不少,也算没白忙一场。而且,rmocp 是可以使用任意的播放列表的(包括从管道读取)。