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社区交流讨论。
登录后查看全文
热门项目推荐
相关项目推荐
Kimi-K2.5Kimi K2.5 是一款开源的原生多模态智能体模型,它在 Kimi-K2-Base 的基础上,通过对约 15 万亿混合视觉和文本 tokens 进行持续预训练构建而成。该模型将视觉与语言理解、高级智能体能力、即时模式与思考模式,以及对话式与智能体范式无缝融合。Python00
GLM-4.7-FlashGLM-4.7-Flash 是一款 30B-A3B MoE 模型。作为 30B 级别中的佼佼者,GLM-4.7-Flash 为追求性能与效率平衡的轻量化部署提供了全新选择。Jinja00
VLOOKVLOOK™ 是优雅好用的 Typora/Markdown 主题包和增强插件。 VLOOK™ is an elegant and practical THEME PACKAGE × ENHANCEMENT PLUGIN for Typora/Markdown.Less00
PaddleOCR-VL-1.5PaddleOCR-VL-1.5 是 PaddleOCR-VL 的新一代进阶模型,在 OmniDocBench v1.5 上实现了 94.5% 的全新 state-of-the-art 准确率。 为了严格评估模型在真实物理畸变下的鲁棒性——包括扫描伪影、倾斜、扭曲、屏幕拍摄和光照变化——我们提出了 Real5-OmniDocBench 基准测试集。实验结果表明,该增强模型在新构建的基准测试集上达到了 SOTA 性能。此外,我们通过整合印章识别和文本检测识别(text spotting)任务扩展了模型的能力,同时保持 0.9B 的超紧凑 VLM 规模,具备高效率特性。Python00
KuiklyUI基于KMP技术的高性能、全平台开发框架,具备统一代码库、极致易用性和动态灵活性。 Provide a high-performance, full-platform development framework with unified codebase, ultimate ease of use, and dynamic flexibility. 注意:本仓库为Github仓库镜像,PR或Issue请移步至Github发起,感谢支持!Kotlin07
compass-metrics-modelMetrics model project for the OSS CompassPython00
项目优选
收起
deepin linux kernel
C
27
11
OpenHarmony documentation | OpenHarmony开发者文档
Dockerfile
525
3.72 K
Ascend Extension for PyTorch
Python
329
391
本项目是CANN提供的数学类基础计算算子库,实现网络在NPU上加速计算。
C++
877
578
openEuler内核是openEuler操作系统的核心,既是系统性能与稳定性的基石,也是连接处理器、设备与服务的桥梁。
C
335
162
暂无简介
Dart
764
189
Nop Platform 2.0是基于可逆计算理论实现的采用面向语言编程范式的新一代低代码开发平台,包含基于全新原理从零开始研发的GraphQL引擎、ORM引擎、工作流引擎、报表引擎、规则引擎、批处理引引擎等完整设计。nop-entropy是它的后端部分,采用java语言实现,可选择集成Spring框架或者Quarkus框架。中小企业可以免费商用
Java
12
1
🎉 (RuoYi)官方仓库 基于SpringBoot,Spring Security,JWT,Vue3 & Vite、Element Plus 的前后端分离权限管理系统
Vue
1.33 K
746
🔥LeetCode solutions in any programming language | 多种编程语言实现 LeetCode、《剑指 Offer(第 2 版)》、《程序员面试金典(第 6 版)》题解
Java
67
20
React Native鸿蒙化仓库
JavaScript
302
350