使用Ruby SDK从Soundcloud下载曲目

use*_*575 2 ruby file download soundcloud

我试图使用应用程序使用ruby sdk(soundcloud 0.2.0 gem)从Soundcloud下载一首曲目.我在soundcloud上注册了应用程序,client_secret是正确的.我知道这一点,因为我可以使用该应用查看我的个人资料信息和曲目.现在,当我尝试使用以下代码下载曲目时

@track = current_user.soundcloud_client.get(params[:track_uri])
data = current_user.soundcloud_client.get(@track.download_url)
File.open("something.mp3","wb"){|f|f.write(data)}
Run Code Online (Sandbox Code Playgroud)

当我打开文件时,它没有任何内容.我尝试了很多方法,包括以下方法,

data = current_user.soundcloud_client.get(@track.download_url)
file = File.read(data)
Run Code Online (Sandbox Code Playgroud)

这个给了我一个错误

can't convert nil into String 
Run Code Online (Sandbox Code Playgroud)

在13号线上

app/controllers/store_controller.rb:13:in `read' 
Run Code Online (Sandbox Code Playgroud)

这就是File.read功能.

我已经仔细检查过我试图下载的曲目是公开的和可下载的.我尝试通过从控制台复制并使用Postman发送请求来测试正在明确使用的download_url并且它有效.我不确定为什么当其他东西工作得那么好时它不能与应用程序一起工作.

我想要做的是成功地能够下载或至少获取我可以存储在某处的数据.

版本细节: -
ruby 1.9.3p194(2012-04-20修订版35410)[x86_64-linux]
Rails 3.2.18
soundcloud 0.2.0

Oto*_*lez 6

在做这件事之前,你必须要了解一些假设.

  • 并非SoundClound上的每个曲目都可以下载!只能下载标记为可下载的曲目- 您的代码必须考虑该选项!
  • 在进入download_url之前,您的跟踪网址必须"已解决",在获得download_url之后,您必须使用client_id获取最终下载网址.
  • 曲目可能很大,下滑需要时间!您不应该直接从控制器或模型中的Rails应用程序执行此类任务.如果任务运行的时间更长,你总是使用一些后台工作者或其他一些后台处理"东西" - 例如Sidekiq.

命令行客户端示例

这是工作客户端的示例,您可以使用它从SoundClound下载曲目.它使用适用于Ruby的官方官方SoundCloud API Wrapper,假设您使用的是Ruby 1.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}"
Run Code Online (Sandbox Code Playgroud)

另请注意,文件采用AIFF(音频交换文件格式).要将它们转换为mp3,您可以使用ffmpeg执行此类操作.

ffmpeg -i 293.aif final-293.mp3
Run Code Online (Sandbox Code Playgroud)