下载时替换文件名mp3

时间:2014-09-13 17:06:25

标签: soundcloud

下载时如何获取自动文件名?因此,当我下载文件时,文件名本身会自动保存,名称为歌曲/艺术​​家,例如:从名称(amgdgapwgd.mp3)到(艺术家 - 歌曲title.mp3)。

1 个答案:

答案 0 :(得分:0)

您尝试使用哪种语言?此外,如果文件返回downloadable等于true,则文件应具有正确的名称。

示例:

https://soundcloud.com/msmrsounds/ms-mr-hurricane-chvrches-remix

来自JSON:

"download_url": "https://api.soundcloud.com/tracks/90787841/download"

指向此文件的链接:Hurricane (CHVRCHES remix).wav

stream_url mp3不会返回正确命名的文件。这是我刚刚编写的一个小Python脚本,用于从API获取轨道名称并下载带有该文件名的流文件。只需将URL变量替换为您要下载的曲目的soundcloud.com网址即可。

import json, requests

url = 'https://api.soundcloud.com/resolve.json'

your_client_id = '[PUT YOUR client_id HERE]'

params = dict(
    url='https://soundcloud.com/msmrsounds/ms-mr-hurricane-chvrches-remix',
    client_id=your_client_id,
)

# resolve
resp = requests.get(url=url, params=params)
data = json.loads(resp.text)

# get api url
track_url = data.get('location')

track_resp = requests.get(url=url, params=params)
track_data = json.loads(resp.text)

# get stream_url

track_title = track_data.get('title')

stream_url = track_data.get('stream_url')

print track_title
print stream_url

stream_params = dict(
    client_id=your_client_id,
)

stream_resp = requests.get(url=url, params=params)

# pass in title + '.mp3' for filename
with open(track_title + '.mp3', 'wb') as handle:
    response = requests.get(url=stream_url, params=stream_params, stream=True)

    if not response.ok:
        # Something went wrong
        print 'Error downloading mp3'

    for block in response.iter_content(1024):
        if not block:
            break

        handle.write(block)