MusicFree插件示例代码:常见功能实现参考
2026-02-04 04:45:55作者:苗圣禹Peter
还在为MusicFree插件开发而烦恼吗?本文为你提供全面的插件开发示例代码,涵盖搜索、播放、歌单导入等核心功能,助你快速上手插件开发!
插件基础结构
每个MusicFree插件都是一个CommonJS模块,必须返回一个符合IPluginDefine接口的对象:
module.exports = {
// 平台名称(必填)
platform: "示例音乐平台",
// 插件版本
version: "1.0.0",
// 支持的MusicFree版本
appVersion: ">=0.6.0",
// 插件描述
description: "示例音乐平台插件,支持搜索、播放等功能",
// 支持的搜索类型
supportedSearchType: ["music", "album", "artist"],
// 默认搜索类型
defaultSearchType: "music",
// 缓存控制
cacheControl: "cache",
// 用户自定义变量
userVariables: [
{
key: "apiKey",
name: "API密钥",
hint: "请输入音乐平台的API密钥"
}
],
// 搜索功能
search: async function(query, page, type) {
// 搜索实现
},
// 获取媒体源
getMediaSource: async function(musicItem, quality) {
// 播放源获取实现
},
// 其他功能方法...
};
核心功能实现示例
1. 搜索功能实现
// 音乐搜索示例
search: async function(query, page, type) {
try {
const pageSize = 20;
const response = await axios.get('https://api.example.com/search', {
params: {
keyword: query,
type: type,
page: page,
pageSize: pageSize
},
headers: {
'User-Agent': 'Mozilla/5.0 (compatible; MusicFree)'
}
});
const data = response.data;
// 处理音乐搜索结果
if (type === 'music') {
return {
isEnd: data.isEnd || (data.list && data.list.length < pageSize),
data: data.list.map(item => ({
id: item.id,
platform: "示例音乐平台",
title: item.name,
artist: item.artists.map(a => a.name).join('/'),
duration: item.duration / 1000, // 转换为秒
artwork: item.album.picUrl,
album: item.album.name
}))
};
}
// 处理专辑搜索结果
if (type === 'album') {
return {
isEnd: data.isEnd,
data: data.list.map(item => ({
id: item.id,
platform: "示例音乐平台",
title: item.name,
artist: item.artist.name,
artwork: item.picUrl,
description: item.description
}))
};
}
// 处理歌手搜索结果
if (type === 'artist') {
return {
isEnd: data.isEnd,
data: data.list.map(item => ({
id: item.id,
platform: "示例音乐平台",
name: item.name,
avatar: item.picUrl,
worksNum: item.musicSize
}))
};
}
} catch (error) {
console.error('搜索失败:', error);
return {
isEnd: true,
data: []
};
}
}
2. 播放源获取实现
getMediaSource: async function(musicItem, quality = 'standard') {
try {
// 根据音质选择对应的URL
const qualityMap = {
'low': '128kbps',
'standard': '320kbps',
'high': 'flac',
'super': 'hires'
};
const response = await axios.get('https://api.example.com/song/url', {
params: {
id: musicItem.id,
quality: qualityMap[quality]
}
});
const urlInfo = response.data.data[0];
if (!urlInfo.url) {
throw new Error('无法获取播放地址');
}
return {
url: urlInfo.url,
headers: {
'Referer': 'https://example.com/',
'User-Agent': 'Mozilla/5.0 (compatible; MusicFree)'
},
quality: quality,
userAgent: 'Mozilla/5.0 (compatible; MusicFree)'
};
} catch (error) {
console.error('获取播放源失败:', error);
return null;
}
}
3. 歌词获取实现
getLyric: async function(musicItem) {
try {
const response = await axios.get('https://api.example.com/lyric', {
params: { id: musicItem.id }
});
const lyricData = response.data;
return {
rawLrc: lyricData.lrc?.lyric || '',
translation: lyricData.tlyric?.lyric || ''
};
} catch (error) {
console.error('获取歌词失败:', error);
return null;
}
}
4. 歌单导入实现
importMusicSheet: async function(urlLike) {
try {
// 解析歌单ID
const match = urlLike.match(/playlist\/(\d+)/);
if (!match) {
throw new Error('无效的歌单链接');
}
const playlistId = match[1];
const response = await axios.get(`https://api.example.com/playlist/detail`, {
params: { id: playlistId }
});
const playlist = response.data.playlist;
// 获取歌单所有歌曲
const allSongs = [];
let offset = 0;
const limit = 500;
while (true) {
const trackResponse = await axios.get('https://api.example.com/playlist/track/all', {
params: {
id: playlistId,
limit: limit,
offset: offset
}
});
const tracks = trackResponse.data.songs;
allSongs.push(...tracks);
if (tracks.length < limit) {
break;
}
offset += limit;
}
return allSongs.map(song => ({
id: song.id,
platform: "示例音乐平台",
title: song.name,
artist: song.ar.map(a => a.name).join('/'),
duration: song.dt / 1000,
artwork: song.al.picUrl,
album: song.al.name
}));
} catch (error) {
console.error('导入歌单失败:', error);
return null;
}
}
5. 专辑信息获取
getAlbumInfo: async function(albumItem, page = 1) {
try {
const pageSize = 50;
const response = await axios.get('https://api.example.com/album', {
params: {
id: albumItem.id,
limit: pageSize,
offset: (page - 1) * pageSize
}
});
const albumData = response.data;
const songs = albumData.songs || [];
return {
albumItem: {
...albumItem,
description: albumData.album.description,
publishTime: albumData.album.publishTime
},
musicList: songs.map(song => ({
id: song.id,
platform: "示例音乐平台",
title: song.name,
artist: song.ar.map(a => a.name).join('/'),
duration: song.dt / 1000,
artwork: song.al.picUrl,
album: song.al.name
})),
isEnd: songs.length < pageSize
};
} catch (error) {
console.error('获取专辑信息失败:', error);
return null;
}
}
高级功能示例
6. 用户变量使用
// 在插件中使用用户配置的变量
search: async function(query, page, type) {
const apiKey = env.userVariables?.apiKey;
if (!apiKey) {
throw new Error('请先配置API密钥');
}
const response = await axios.get('https://api.example.com/search', {
params: {
keyword: query,
type: type,
page: page,
api_key: apiKey
}
});
// 处理结果...
}
7. 错误处理和重试机制
getMediaSource: async function(musicItem, quality, retryCount = 3) {
for (let attempt = 1; attempt <= retryCount; attempt++) {
try {
const response = await axios.get('https://api.example.com/song/url', {
params: { id: musicItem.id, quality: quality },
timeout: 5000
});
if (response.data.code === 200) {
return {
url: response.data.data[0].url,
headers: { 'User-Agent': 'MusicFree' }
};
}
} catch (error) {
if (attempt === retryCount) {
console.error(`获取播放源失败(尝试${attempt}次):`, error);
return null;
}
await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
}
}
}
8. 缓存策略实现
// 使用内存缓存提高性能
const searchCache = new Map();
search: async function(query, page, type) {
const cacheKey = `${query}-${type}-${page}`;
// 检查缓存
if (searchCache.has(cacheKey)) {
return searchCache.get(cacheKey);
}
try {
const result = await actualSearchImplementation(query, page, type);
// 缓存结果(5分钟有效期)
searchCache.set(cacheKey, result);
setTimeout(() => searchCache.delete(cacheKey), 5 * 60 * 1000);
return result;
} catch (error) {
console.error('搜索失败:', error);
return { isEnd: true, data: [] };
}
}
最佳实践和注意事项
代码质量规范
// 1. 统一的错误处理
function withErrorHandling(fn, defaultReturn) {
return async function(...args) {
try {
return await fn(...args);
} catch (error) {
console.error('操作失败:', error.message);
return defaultReturn;
}
};
}
// 2. 参数验证
function validateMusicItem(musicItem) {
if (!musicItem || !musicItem.id || !musicItem.platform) {
throw new Error('无效的音乐项目');
}
}
// 3. 使用安全的HTTP请求
async function safeRequest(url, options = {}) {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 10000);
try {
const response = await fetch(url, {
...options,
signal: controller.signal,
headers: {
'User-Agent': 'MusicFree/1.0',
...options.headers
}
});
clearTimeout(timeoutId);
return response;
} catch (error) {
clearTimeout(timeoutId);
throw error;
}
}
性能优化建议
// 1. 批量请求优化
async function batchGetMediaSources(musicItems, quality) {
const ids = musicItems.map(item => item.id).join(',');
const response = await axios.get('https://api.example.com/song/url/batch', {
params: { ids, quality }
});
return musicItems.map(item => {
const urlInfo = response.data.find(d => d.id === item.id);
return {
url: urlInfo?.url,
headers: { 'User-Agent': 'MusicFree' }
};
});
}
// 2. 请求去重
const pendingRequests = new Map();
async function deduplicatedRequest(key, requestFn) {
if (pendingRequests.has(key)) {
return pendingRequests.get(key);
}
const promise = requestFn();
pendingRequests.set(key, promise);
try {
return await promise;
} finally {
pendingRequests.delete(key);
}
}
完整插件示例
module.exports = {
platform: "ExampleMusic",
version: "1.0.0",
appVersion: ">=0.6.0",
description: "示例音乐平台插件",
supportedSearchType: ["music", "album", "artist"],
defaultSearchType: "music",
cacheControl: "cache",
userVariables: [
{
key: "apiKey",
name: "API密钥",
hint: "请输入ExampleMusic的API密钥"
}
],
search: async function(query, page, type) {
const apiKey = env.userVariables?.apiKey;
if (!apiKey) throw new Error("请配置API密钥");
const response = await axios.get('https://api.example.com/search', {
params: { q: query, type, page, limit: 20, api_key: apiKey }
});
return processSearchResult(response.data, type);
},
getMediaSource: async function(musicItem, quality) {
const response = await axios.get('https://api.example.com/song/url', {
params: { id: musicItem.id, quality }
});
return {
url: response.data.url,
headers: { 'User-Agent': 'MusicFree' },
quality: quality
};
},
getLyric: async function(musicItem) {
const response = await axios.get('https://api.example.com/lyric', {
params: { id: musicItem.id }
});
return {
rawLrc: response.data.lrc,
translation: response.data.tlyrc
};
}
};
function processSearchResult(data, type) {
// 统一的搜索结果处理逻辑
switch (type) {
case 'music':
return processMusicResults(data);
case 'album':
return processAlbumResults(data);
case 'artist':
return processArtistResults(data);
default:
return { isEnd: true, data: [] };
}
}
总结
通过本文的示例代码,你应该已经掌握了MusicFree插件开发的核心技能。记住以下关键点:
- 遵循接口规范:严格实现
IPluginDefine接口定义的方法 - 错误处理:完善的错误处理机制确保插件稳定性
- 性能优化:合理使用缓存和批量请求提升用户体验
- 用户友好:清晰的错误提示和配置指引
现在就开始你的插件开发之旅吧!如有问题,欢迎在MusicFree社区交流讨论。
登录后查看全文
热门项目推荐
相关项目推荐
atomcodeClaude Code 的开源替代方案。连接任意大模型,编辑代码,运行命令,自动验证 — 全自动执行。用 Rust 构建,极致性能。 | An open-source alternative to Claude Code. Connect any LLM, edit code, run commands, and verify changes — autonomously. Built in Rust for speed. Get StartedRust0448
源启盛夏_AtomGit暑期开发者成长计划「源启盛夏」暑期校园开发者成长计划旨在激活校园开源力量,通过积分激励、认证扶持、资源倾斜等形式,引导高校组织和开发者完成「入驻 — 建项目 — 做贡献 — 获认证 — 得资源」的完整闭环。无论你是想带领社团入驻平台的组织者,还是希望用代码贡献证明自己的开发者,都能在这里找到属于你的成长路径。Markdown00
jiuwenswarmJiuwenSwarm 是一款基于openJiuwen开发的智能AI Agent,它能够将大语言模型的强大能力,通过你日常使用的各类通讯应用,直接延伸至你的指尖。Python0769
Hy3Hy3 是由腾讯混元团队研发的快慢思考融合的混合专家模型,总参数量 295B,激活参数 21B,MTP 层参数 3.8B。4 月底发布 Hy3 Preview 后,我们在 50 多个业务中获得了广泛的反馈,修复了各种体验问题,进一步提升了后训练的质量和规模。今天,我们发布 Hy3。它展现出显著强于同尺寸并比肩旗舰(参数规模往往是 Hy3 的 2~5 倍)开源模型的智能水平,显著提升了在各类产品和生产力任务中的实用价值。Python00
AscendNPU-IRAscendNPU-IR是基于MLIR(Multi-Level Intermediate Representation)构建的,面向昇腾亲和算子编译时使用的中间表示,提供昇腾完备表达能力,通过编译优化提升昇腾AI处理器计算效率,支持通过生态框架使能昇腾AI处理器与深度调优C++0313
DragonOSDragonOS is an operating system developed from scratch using Rust, with Linux compatibility. It is designed for **Serverless** scenarios. 使用Rust从0自研内核,具有Linux兼容性的操作系统,面向云计算Serverless场景而设计。Rust00
项目优选
收起
暂无描述
Markdown
827
5.49 K
openEuler内核是openEuler操作系统的核心,既是系统性能与稳定性的基石,也是连接处理器、设备与服务的桥梁。
C
494
518
本项目是CANN提供的神经网络类计算算子库,实现网络在NPU上加速计算。
C++
786
1.58 K
作为 Ascend for PyTorch 社区的核心组件,TorchNPU 是昇腾专为 PyTorch 打造的深度学习适配插件,使 PyTorch 框架能够直接调用昇腾 NPU,为开发者提供昇腾 AI 处理器的超强算力。
Python
803
1.14 K
本项目是CANN提供的transformer类大模型算子库,实现网络在NPU上加速计算。
C++
973
2.29 K
deepin linux kernel
C
32
16
AscendNPU-IR是基于MLIR(Multi-Level Intermediate Representation)构建的,面向昇腾亲和算子编译时使用的中间表示,提供昇腾完备表达能力,通过编译优化提升昇腾AI处理器计算效率,支持通过生态框架使能昇腾AI处理器与深度调优
C++
482
312
JiuwenSwarm 是一款基于openJiuwen开发的智能AI Agent,它能够将大语言模型的强大能力,通过你日常使用的各类通讯应用,直接延伸至你的指尖。
Python
3.02 K
769
CANNBot 是面向 CANN 开发的用于提升开发效率的系列智能体,本仓库为其提供可复用的 Skills 模块。
Markdown
1.26 K
811
CANN 学习中心仓,支持在线互动运行、边学边练,提供教程、示例与优化方案,一站式助力昇腾开发者快速上手。
Jupyter Notebook
648
287