Files
BYW-VoiceHub/server/api/music/kg/playurl.get.ts
T
Henry_Du 4ce4649aaf
Build VoiceHub FPK / build-fpk (push) Failing after 56m5s
Build and Push Docker Image / build-and-push (push) Canceled after 1h9m35s
初次提交
2026-09-06 08:19:02 +08:00

73 lines
2.2 KiB
TypeScript

import { getQuery, createError } from 'h3'
import axios from 'axios'
export default defineEventHandler(async (event) => {
const query = getQuery(event)
const hash = query.hash as string
if (!hash) {
throw createError({
statusCode: 400,
message: 'Hash is required'
})
}
try {
// 首先尝试通过移动端API获取播放链接
const infoUrl = `http://m.kugou.com/app/i/getSongInfo.php?cmd=playInfo&hash=${hash}`
const infoRes = await axios.get(infoUrl, { validateStatus: () => true })
if (infoRes.data && infoRes.data.url) {
return {
data: {
play_url: infoRes.data.url
}
}
}
// 如果失败或者需要付费(VIP),通过标题和歌手名从网易云匹配一个试听链接
if (infoRes.data && infoRes.data.songName) {
const keyword = `${infoRes.data.songName} ${infoRes.data.singerName || ''}`.trim()
try {
// 搜索网易云音乐
const searchUrl = `https://music.163.com/api/search/get/web?s=${encodeURIComponent(keyword)}&type=1&offset=0&total=true&limit=1`
const searchRes = await axios.get(searchUrl, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
})
if (searchRes.data?.result?.songs?.length > 0) {
const songId = searchRes.data.result.songs[0].id
// 获取网易云播放链接
const neteaseUrl = `https://music.163.com/song/media/outer/url?id=${songId}.mp3`
return {
data: {
play_url: neteaseUrl
}
}
}
} catch (e) {
console.error('Fallback to Netease failed:', e)
}
}
// 如果都没有,尝试使用原本的 API
const url = `http://www.kugou.com/yy/index.php?r=play/getdata&hash=${hash}`
const response = await axios.get(url, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Cookie': 'kg_mid=1234567890'
},
validateStatus: () => true
})
return response.data
} catch (error) {
throw createError({
statusCode: 500,
message: 'Music service unavailable'
})
}
})