在做这件事之前,你需要了解的假设很少。
-
不是每个曲目
SoundClound
可以下载!仅标记为
可下载的
可以下载-您的代码必须考虑该选项!
-
在您获得download_URL之前,必须“解析”您的曲目URL,在获得download_URL之后,您必须使用client_id获得最终的下载URL。
-
曲目可能很大,下载曲目需要时间!您不应该直接从控制器或模型中的Rails应用程序执行这样的任务。如果任务运行的时间更长,您总是使用一些后台工作程序或其他类型的后台处理“东西”-
Sidekiq
例如
命令行客户端示例
这是一个工作客户端的示例,您可以使用它从
声音克隆
.其使用官方
Official SoundCloud API Wrapper for Ruby
,假设您使用的是Ruby1.9.x,并且它在任何方面都不依赖Rails。
# We use Bundler to manage our dependencies
require 'bundler/setup'
# We store SC_CLIENT_ID and SC_CLIENT_SECRET in .env
# and dotenv gem loads that for us
require 'dotenv'; Dotenv.load
require 'soundcloud'
require 'open-uri'
# Ruby 1.9.x has a problem with following redirects so we use this
# "monkey-patch" gem to fix that. Not needed in Ruby >= 2.x
require 'open_uri_redirections'
# First there is the authentication part.
client = SoundCloud.new(
client_id: ENV.fetch("SC_CLIENT_ID"),
client_secret: ENV.fetch("SC_CLIENT_SECRET")
)
# Track URL, publicly visible...
track_url = "http://soundcloud.com/forss/flickermood"
# We call SoundCloud API to resolve track url
track = client.get('/resolve', url: track_url)
# If track is not downloadable, abort the process
unless track["downloadable"]
puts "You can't download this track!"
exit 1
end
# We take track id, and we use that to name our local file
track_id = track.id
track_filename = "%s.aif" % track_id.to_s
download_url = "%s?client_id=%s" % [track.download_url, ENV.fetch("SC_CLIENT_ID")]
File.open(track_filename, "wb") do |saved_file|
open(download_url, allow_redirections: :all) do |read_file|
saved_file.write(read_file.read)
end
end
puts "Your track was saved to: #{track_filename}"
还请注意,文件位于
AIFF (Audio Interchange File Format)
。要将它们转换为mp3,请使用
ffmpeg
.
ffmpeg -i 293.aif final-293.mp3