556 words
3 minutes
通过 freesound api 下载音频数据

Cover Image Source:Source

详细内容请参考 https://freesound.org/docs/api/client_libs.html

MTG
/
freesound-python
Waiting for api.github.com...
00K
0K
0K
Waiting...

准备工作#

  • 在 freesound.org 官网上请求 APIv2 凭证(https://freesound.org/apiv2/apply)。需要注意,APIv2 的使用仅限于一定的使用率。标准使用费率设置为每分钟 60 个请求和每天 2000 个请求。包括上传、描述、评论、评分和书签声音在内的资源具有更严格的速率,即每分钟 30 个请求和每天 500 个请求。

  • 安装相关的 python 包:

    Terminal window
    pip install freesound-python
    pip install requests-oauthlib

获取音频元信息#

搜索#

import freesound
client = freesound.FreesoundClient()
client.set_token("<your_api_key>","token")
results = client.text_search(
query="violoncello",
filter="tag:tenuto duration:[1.0 TO 15.0]",
sort="rating_desc",
fields="id,name,previews,username",
)
for sound in results:
print(sound.name)

query 为查询,fields 为需要获取的元信息,filter 为过滤器,sort 为排序方式。text_search 返回的是一个 Pager 对象,结构如下:

{
"count": <total number of results>,
"next": <link to the next page of results (null if none)>,
"results": [
<sound result #1 info>,
<sound result #2 info>,
...
<sound result #page_size info>
],
"previous": <link to the previous page of results (null if none)>
}

可以通过设置 text_searchpagepage_size 参数设置需要返回哪一页以及每页有多少结果。

获取随机音频#

通过 https://freesound.org/browse/random/ 可以获取随机的音频 id,接着通过 api 搜索即可获取音频

import freesound
import request
import re
response = requests.get("https://freesound.org/browse/random/")
sound_id = re.search(r'/sounds/(\d+)/', reponse.text).group(1)
sound = client.get_sound(sound_id)
print(sound.name)

下载音频#

下载预览音频的代码如下:

# sound 为 client 获取到的音频,例如 sound = client.get_sound(<sound_id>)
sound.retrieve_preivew(file_path, name=f"{sound['id']}.mp3", quality="hq", file_format="mp3")

quality 为预览音频的质量,有 "lq""hq" 两个选项,分别代表低质量和高质量。默认下载的是低质量音频。低质量音频的下载速度会比高质量音频快很多。音频文件格式可以选择 mp3 和 ogg 两种。

下载原始音频需要 OAuth2 认证,OAuth2 认证需要以下步骤:

from requests_oauthlib import OAuth2Session
import freesound
client_id = "<your_client_id>"
client_secret = "<your_client_secret>"
# do the OAuth dance
oauth = OAuth2Session(client_id)
authorization_url, state = oauth.authorization_url(
"https://freesound.org/apiv2/oauth2/authorize/"
)
print(f"Please go to {authorization_url} and authorize access.")
authorization_code = input("Please enter the authorization code:")
oauth_token = oauth.fetch_token(
"https://freesound.org/apiv2/oauth2/access_token/",
authorization_code,
client_secret=client_secret,
)
client = freesound.FreesoundClient()
client.set_token(oauth_token["access_token"], "oauth")

这段代码会生成一个网址,用户通过访问该网址获得认证码进行认证。

下载原始音频代码为:

sound.retrieve(file_path, name=None)

默认会使用音频的原始名称,保留音频的原始上传格式。

通过 freesound api 下载音频数据
https://etherwindy.github.io/AstroBlog/posts/freesound-api/
Author
etherwindy
Published at
2024-11-27
License
CC BY-NC-SA 4.0