让小爱同学播放本地/远程歌曲的方案 | 您所在的位置:网站首页 › 怎么用苹果音乐播放本地音乐歌曲 › 让小爱同学播放本地/远程歌曲的方案 |
环境:HACS+Python 问题:小爱同学不能播放本地歌曲或者群晖中的歌曲 解决办法:HACS + Http Server 背景:冲绿砖是不可能的,DLNA也被阉割了,只能曲线救国了 解决思路:通过HACS监控小爱事件,推送媒体链接并随机播放,具体看下面的流程图 步骤略,自行解决,我是在群晖上拉的官方容器 homeassistant/home-assistant:latest 2.安装HACS 小米集成:步骤略,自行解决,我是在集成中搜索添加的,参考下图,确保音箱出现: 参考下图,准备一个mp3的url链接,最好是直连,重定向的我测试也可以 步骤:开发者工具-服务器-play media-选择实体-ID为链接地址,选择播放 如果一切顺利的话,你会听到小爱音箱直接播放音乐,你已经成功90%了 我们的目的是让小爱播放我们服务器中的所有音乐,只推送一个MP3链接是不行的 这一块我尝试了很多方法,最后的思路是用python 写一个http的服务器: 1.当用户请求/playlist时立即扫描本地音频文件 2.打乱文件顺序,生成一个m3u8的播放列 3.小爱读取播放列表的音频地址,向服务器请求 3.服务器将不是WAV格式的音频转码给小爱播放,这样flac格式或者大容量MP3文件播放不会卡顿 直接上代码: # coding=utf-8 # http随机音乐播放器 # 给小爱音箱用于播放nas的音乐 import os, random, urllib, posixpath, shutil, subprocess from http.server import HTTPServer, BaseHTTPRequestHandler # 端口号 port = 8080 # 存音乐的目录 fileDir = '/volume1/music/' # 实时转码需要依赖ffmpeg的路径 如果为空就不转码 ffmpeg = '/usr/bin/ffmpeg' fileList = None fileIndex = 0 def updateFileList(): global fileList global fileIndex try: os.chdir(fileDir) except Exception as e: print(e) print('ERROR: 请检查目录是否存在或是否有权限访问') exit() fileIndex = 0 fileList = list(filter(lambda x: x.lower().split('.')[-1] in ['flac','mp3','wav','aac','m4a'], os.listdir('.'))) fileList.sort(key=lambda x: os.path.getmtime(x)) fileList.reverse() print(str(len(fileList)) + ' files') # 在类的顶部添加一个计数器变量 playlist_request_count = 0 class meHandler(BaseHTTPRequestHandler): def translate_path(self, path): path = path.split('?',1)[0] path = path.split('#',1)[0] trailing_slash = path.rstrip().endswith('/') try: path = urllib.parse.unquote(path, errors='surrogatepass') except UnicodeDecodeError: path = urllib.parse.unquote(path) path = posixpath.normpath(path) words = path.split('/') words = filter(None, words) path = fileDir for word in words: if os.path.dirname(word) or word in (os.curdir, os.pardir): continue path = os.path.join(path, word) if trailing_slash: path += '/' return path def return302(self, filename): self.send_response(302) self.send_header('Location', '/' + urllib.parse.quote(filename)) self.end_headers() def do_GET(self): global fileList global fileIndex global playlist_request_count print(self.path) if self.path == '/': self.return302(fileList[fileIndex]) fileIndex += 1 if fileIndex >= len(fileList): fileIndex = 0 elif self.path == '/random': updateFileList() random.shuffle(fileList) self.return302(fileList[0]) fileIndex = 1 elif self.path == '/first': updateFileList() self.return302(fileList[0]) fileIndex = 1 elif self.path == '/playlist': playlist_request_count += 0 if playlist_request_count |
CopyRight 2018-2019 实验室设备网 版权所有 |