所以我一直在为Discordapp开发音乐播放器。问题是我想要显示歌曲标题和歌曲艺术家。我该怎么做呢
player = voice_stream.create_ffmpeg_player('./audio_library/1.mp3')
# FFProbing for info
p = sp.Popen(['ffprobe', '-v', 'quiet', '-print_format', 'json=compact=1', '-show_format',
'./audio_library/1.mp3'], stdout=sp.PIPE, stderr=sp.PIPE)
op = p.communicate()
# a = dict(op)
# tit = a['title']
# art = a['artist']
# print(tit + '\n' + art)
ops = str(op)
print('op :- ' + ops)
opsn = re.sub("\r\n", "", ops)
print('opsn :- ' + opsn)
谢谢。如果可能,我也可以知道如何将此数据转换为json格式。我尝试使用 json.loads(op),但我收到错误,说这是一个元组。
我目前的输出是这样的: -
op :- (b'{\r\n "format": { "filename": "./audio_library/1.mp3", "nb_streams": 1, "nb_programs": 0, "format_name": "mp3", "format_long_name": "MP2/3 (MPEG audio layer 2/3)", "start_time": "0.000000", "duration": "351.190200", "size": "14062151", "bit_rate": "320331", "probe_score": 50,\r\n "tags": { "title": "Rescue Me (Sigma Remix)", "artist": "Skepta", "encoded_by": "Lavf52.31.0" } }\r\n}\r\n', b'')
opsn :- (b'{\r\n "format": { "filename": "./audio_library/1.mp3", "nb_streams": 1, "nb_programs": 0, "format_name": "mp3", "format_long_name": "MP2/3 (MPEG audio layer 2/3)", "start_time": "0.000000", "duration": "351.190200", "size": "14062151", "bit_rate": "320331", "probe_score": 50,\r\n "tags": { "title": "Rescue Me (Sigma Remix)", "artist": "Skepta", "encoded_by": "Lavf52.31.0" } }\r\n}\r\n', b'')
答案 0 :(得分:1)
你需要获取元组中的第一个条目,解码字节,并解析json:
import json
import pprint
op_json = json.loads(op[0].decode('utf-8'))
title = op_json['format']['tags']['title']
artist = op_json['format']['tags']['artist']
print('title:', title)
print('artist:', artist)
print()
pprint.pprint(op_json)
打印:
title: Rescue Me (Sigma Remix)
artist: Skepta
{'format': {'bit_rate': '320331',
'duration': '351.190200',
'filename': './audio_library/1.mp3',
'format_long_name': 'MP2/3 (MPEG audio layer 2/3)',
'format_name': 'mp3',
'nb_programs': 0,
'nb_streams': 1,
'probe_score': 50,
'size': '14062151',
'start_time': '0.000000',
'tags': {'artist': 'Skepta',
'encoded_by': 'Lavf52.31.0',
'title': 'Rescue Me (Sigma Remix)'}}}