music下载脚本python

music下载脚本

application.py

import read_music_name_file
import music_home
import asyncio

if __name__ == '__main__':
    #音乐名称
    names=read_music_name_file.read_music_name_file()
    print('需要下载的音乐名称有:'+str(names))
    #创建房间
    homeId=music_home.create_home()
    if homeId==None:
        print('创建房间失败,请稍后尝试。')
        retrun
    # 可以指定已有房间id
    # homeId='lJyi3PfJ'
    # password=''
    asyncio.run(music_home.do_websocket_task(homeId,password,names))

music_home.py

import requests
import json
import websockets
import asyncio
import time
import os
import urllib.request
#创建房间,并返回房间id
def create_home():
    false=False
    param_json={'name':'www`','desc':'','needPwd':false,'password':'','enableStatus':false,'retainKey':''}
    headers = {'Content-type': 'application/json'}
    response=requests.post('https://tx.alang.run/api/house/add',headers=headers,json=param_json)
    print('创建房间结果:'+str(json.loads(response.text)))
    return json.loads(response.text)['data']
#建立链接,并保持通信
async def do_websocket_task(hoseId,password,names):
    remote = 'wss://tx.alang.run/api/server/036/yd3vlqz1/websocket?houseId=' + hoseId + '&housePwd='+password+'&connectType=enter'
    async with websockets.connect(uri=remote) as websocket:
        print(f"创建socket链接结果:{websockets}")

        for nameAndArtist in names:
            name=nameAndArtist
            artist=None
            if ',' in str(nameAndArtist):
                name=str(nameAndArtist).split(',')[0]
                artist=str(nameAndArtist).split(',')[1]
            timestamp = str(int(time.time()) * 1000)
            sclength = str(78 + len(name) * 3)
            search = '["SEND\\ndestination:/music/search\\ncontent-length:' + sclength + '\\n\\n{\\"name\\":\\"param01\\",\\"sendTime\\":' + timestamp + ',\\"source\\":\\"wy\\",\\"pageIndex\\":1,\\"pageSize\\":10}\\u0000"]'
            sendSearch = search.replace('param01', name)
            print(f"搜索请求参数:{sendSearch}")
            await websocket.send(sendSearch)
            global responseSearch
            i=0
            break_for=False
            while True:
                i=i+1
                if i>10:
                    break_for=True
                    break
                responseSearch= await websocket.recv()
                print(f"搜索请求结果:{responseSearch}")
                if "a[\"SEARCH" in responseSearch:
                    print(f"搜索请求结果1:{responseSearch}")
                    break
            if break_for:
                continue
            searchMsgArray = responseSearch.split('\\n')
            json_str_searchMsg = searchMsgArray[len(searchMsgArray) - 1].replace('\\', '').replace('\"]', '')
            try:
                json_obj_searchMsg = json.loads(json_str_searchMsg)
            except Exception as e:
                print(f"Exception 搜索异常: {name} An error occurred: {e}")
                continue
            obj_first_searchMsg=None
            for obj_searchMsg in json_obj_searchMsg['data']['data']:
                if artist in str(obj_searchMsg['artist']):
                    obj_first_searchMsg=obj_searchMsg
                    break
            if obj_first_searchMsg ==None:
                continue
            timestamp = str(int(time.time()) * 1000)
            pclength = str(58 + len(obj_first_searchMsg['name'].encode('utf-8')) + len(obj_first_searchMsg['id'].encode('utf-8')))
            pick = '["SEND\\ndestination:/music/pick\\ncontent-length:' + pclength + '\\n\\n{\\"name\\":\\"param01\\",\\"id\\":\\"param02\\",\\"source\\":\\"wy\\",\\"sendTime\\":' + timestamp + '}\\u0000"]'
            sendPick = pick.replace('param01', obj_first_searchMsg['name']).replace('param02', obj_first_searchMsg['id'])
            print(f"点歌请求参数:{sendPick}")
            await websocket.send(sendPick)
            global responsePick
            while True:
                responsePick = await websocket.recv()
                if "a[\"PICK" in responsePick:
                    print(f"点歌请求结果:{responsePick}")
                    break
            pickMsgarray = responsePick.split('\\n')
            json_str_pickMsg = pickMsgarray[len(pickMsgarray) - 1].replace('\\', '').replace('\"]', '')
            json_obj_pickMsg = json.loads(json_str_pickMsg)
            obj_last_pickMsg = json_obj_pickMsg['data'][len(json_obj_pickMsg['data']) - 1]
            await download_music(obj_last_pickMsg['url'], obj_last_pickMsg['name'] + '-' + obj_last_pickMsg['artist'])

async def download_music(url,name):
    print(f'开始下载 {name}')
    response = urllib.request.urlopen(url)
    if not os.path.exists('./music'):
        os.mkdir('./music')
    content = response.read()
    with open('./music/'+name+'.mp3', 'wb') as f:
        f.write(content)
        f.close()
    print(f'下载完成 {name}')

music_names.txt

反间计,滕志刚
易中天品三国01大江东去,易中天
易中天品三国02真假曹操,易中天
易中天品三国03奸雄之迷,易中天
易中天品三国05何去何从,易中天
易中天品三国04能臣之路,易中天

read_music_name_file.py

#读取文件,返回文件内容list
music_file_names=[]
def read_music_name_file():
    with open('./music_names.txt', 'r') as file:
        for f in file:
            music_file_names.append(f.replace('\n',''))
    return music_file_names
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值