在Lua中从URL加载音频文件

我需要在Lua中从URL加载mp3文件。

我尝试了这个方法,但它不起作用。

require "socket.http"

local resp, stat, hdr = socket.http.request{
  url     = "https://www.dropbox.com/s/hfrdbncfgbsarou/hello.mp3?dl=1",
}

local audioFile = audio.loadSound(resp)
audio.play(audioFile)

有任何想法吗?

点赞
用户2226988
用户2226988

request函数是“重载”的(在其他语言的术语中)。如文档所述,它有三种形式:

local responsebodystring, statusnumber, headertable, statusstring
  = request( urlstring ) -- GET

local responsebodystring, statusnumber, headertable, statusstring
  = request( urlstring, requestbodystring ) -- POST

local success, statusnumber, headertable, statusstring
  = request( requestparametertable) -- 取决于参数

有关详细信息,请参见文档,特别是有关错误结果的部分。

对于最后一种形式,Lua语法允许使用表构造函数调用函数,而不是使用括号中的单个表参数。这是你正在使用的形式和语法。但你错误地期望第一个返回值是响应主体。响应正文是传递给请求参数表中随意表示的“sink”函数的,而你没有这个函数。

尝试使用第一种形式:

local resp, stat, hdr
  = socket.http.request("https://www.dropbox.com/s/hfrdbncfgbsarou/hello.mp3?dl=1")
2013-08-10 14:17:06