萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Lua 爬取喜馬拉雅音頻真實 MP3 連結:luacurl + luajson 實作

依賴套件

# Linux
luarocks install luacurl
luarocks install luajson  # 或 dkjson

核心邏輯

  1. 喜馬拉雅音頻頁面 ID → API https://www.ximalaya.com/tracks/{id}.json。
  2. 回傳 JSON 含 play_path_64(64kbps MP3 相對路徑)。
  3. 拼接 CDN 前綴 https://fdfs.xmcdn.com/ 得到完整 MP3 連結。

完整腳本 ximalaya.lua

#!/usr/bin/env lua5.1
-- 需求:luacurl, luajson
require("luacurl")
require("json")

local function fetch(url, curl_obj)
    local buffer = {}
    local c = curl_obj or require("luacurl").new()
    c:setopt(curl.OPT_URL, url)
    c:setopt(curl.OPT_WRITEFUNCTION, function(buf, data)
        table.insert(buf, data)
        return #data
    end, buffer)
    local ok = c:perform()
    return ok, table.concat(buffer)
end

local function get_mp3_url(track_id)
    local api = "https://www.ximalaya.com/tracks/" .. track_id .. ".json"
    local ok, body = fetch(api)
    if not ok then return nil, "HTTP 請求失敗" end
    
    local data = json.decode(body)
    if not data or not data.play_path_64 then
        return nil, "JSON 解析失敗或欄位缺失"
    end
    return "https://fdfs.xmcdn.com/" .. data.play_path_64
end

-- CLI 入口
local id = tonumber(arg[1])
if not id then
    print("用法: lua ximalaya.lua ")
    os.exit(1)
end

local url, err = get_mp3_url(id)
if url then
    print(url)
else
    print("錯誤: " .. err)
end

使用方式

lua ximalaya.lua 12345678
# 輸出: https://fdfs.xmcdn.com/xxx/xxx.mp3

注意事項

  • 官方 API 可能變更、加簽名驗證、限流;請遵守 robots.txt 與服務條款。
  • 僅供個人學習研究,勿大量爬取或商業用途。
  • 若需下載,配合 curl -O 或 aria2c 多線程下載。

結語

短短幾十行 Lua,串接 HTTP + JSON 解析,即可獲取音頻真實連結。展示了 Lua 輕量腳本語言在「膠水腳本」場景的極致效率。

copyright © 萬盛學電腦網 all rights reserved