0.2.4 • Published 10 months ago

mstf-kit v0.2.4

Weekly downloads
-
License
MIT
Repository
-
Last release
10 months ago

mstf-kit

English | 简体中文

一个现代化的 JavaScript/TypeScript 工具库,提供了丰富的常用工具函数。

✨ 特性

  • 📦 支持 Tree Shaking
  • 🔧 TypeScript 支持
  • 📚 完整的类型定义
  • 🎯 模块化设计
  • 💪 全面的测试覆盖
  • 📝 详细的文档
  • 🔒 代码混淆保护

📦 安装

npm install mstf-kit
# 或
yarn add mstf-kit
# 或
pnpm add mstf-kit

🚀 使用方法

// 导入所需的工具函数
import { formatDate, isEmail } from 'mstf-kit';

// 使用日期格式化
const date = formatDate(new Date(), 'YYYY-MM-DD');
console.log(date); // 2024-03-10

// 验证邮箱
const isValidEmail = isEmail('example@email.com');
console.log(isValidEmail); // true

按需导入

为了减小打包体积,推荐使用 tree-shaking 按需导入具体的工具函数:

// 只导入需要的函数
import { capitalize, truncate } from 'mstf-kit';
import { formatDate } from 'mstf-kit';
import { createLottiePlayer } from 'mstf-kit';

// 不要这样导入整个库
// import * as mstfKit from 'mstf-kit'; // ❌ 不推荐

现代打包工具(如 webpack、rollup、vite)会自动进行 tree-shaking,只打包您实际使用的代码。

📚 API 文档

🔤 字符串工具 (String Utils)

字符串处理相关的工具函数。

  • capitalize(str: string): string - 首字母大写
  • camelCase(str: string): string - 转换为驼峰命名
  • truncate(str: string, length: number): string - 截断字符串

🔢 数字工具 (Number Utils)

数字处理和计算相关的工具函数。

  • formatNumber(num: number, locale?: string): string - 数字格式化
  • round(num: number, decimals?: number): number - 四舍五入
  • clamp(num: number, min: number, max: number): number - 限制数字范围
  • random(min: number, max: number, isInteger?: boolean): number - 生成随机数
  • percentage(value: number, total: number, decimals?: number): number - 计算百分比

📋 数组工具 (Array Utils)

数组操作和处理的工具函数。

  • unique<T>(arr: T[]): T[] - 数组去重
  • groupBy<T>(arr: T[], key: string | ((item: T) => string)): Record<string, T[]> - 数组分组
  • flatten<T>(arr: any[], depth?: number): T[] - 数组扁平化
  • sample<T>(arr: T[], count?: number): T | T[] - 随机采样
  • shuffle<T>(arr: T[]): T[] - 数组乱序
  • closest(arr: number[], target: number): number - 查找最接近的值

📦 对象工具 (Object Utils)

对象操作和处理的工具函数。

  • deepClone<T>(obj: T): T - 深拷贝
  • get(obj: any, path: string | string[], defaultValue?: any): any - 获取嵌套属性
  • set(obj: any, path: string | string[], value: any): void - 设置嵌套属性
  • pick<T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> - 选择属性
  • omit<T, K extends keyof T>(obj: T, keys: K[]): Omit<T, K> - 排除属性
  • merge<T>(...objects: T[]): T - 对象合并

📅 日期工具 (Date Utils)

日期和时间处理的工具函数。

  • formatDate(date: Date | number | string, format?: string): string - 日期格式化
  • getRelativeTime(date: Date | number | string, now?: Date): string - 相对时间
  • getDateRange(start: Date | number | string, end: Date | number | string): Date[] - 日期范围
  • addTime(date: Date | number | string, amount: number, unit: string): Date - 添加时间
  • isSameDay(date1: Date | number | string, date2: Date | number | string): boolean - 判断同一天

✅ 验证工具 (Validation Utils)

数据验证相关的工具函数。

  • isEmail(email: string): boolean - 验证邮箱
  • isChinesePhone(phone: string): boolean - 验证手机号(中国大陆)
  • isChineseIdCard(idCard: string): boolean - 验证身份证号(中国大陆)
  • isUrl(url: string): boolean - 验证URL
  • isIPv4(ip: string): boolean - 验证IPv4地址
  • validatePassword(password: string, options?: object): boolean - 验证密码强度
  • isSafeString(str: string): boolean - 验证XSS安全

🎵 音频工具 (Audio Utils)

音频处理相关的工具函数。

  • createRecorder(options?: RecorderOptions): Promise<Recorder> - 创建录音器
  • blobToAudioBuffer(blob: Blob, context?: AudioContext): Promise<AudioBuffer> - 将音频Blob转换为AudioBuffer
  • playAudioBlob(blob: Blob): HTMLAudioElement - 播放音频Blob
  • base64ToAudioBlob(base64: string, mimeType: string): Blob - 将Base64音频数据转换为Blob
  • audioBlobToBase64(blob: Blob): Promise<string> - 将音频Blob转换为Base64

录音器 API

录音器对象 (Recorder) 提供以下方法:

  • start() - 开始录音
  • pause() - 暂停录音
  • resume() - 恢复录音
  • stop() - 停止录音并获取完整音频数据
  • cancel() - 取消录音
  • getState() - 获取当前录音状态
  • getDuration() - 获取当前录音时长(秒)
  • getAudioData() - 获取实时音频分析数据
  • getCurrentAudio() - 获取当前已采集的音频数据(不停止录音)
  • release() - 释放资源

录音模式选择

录音器支持两种工作模式:

  • 流式模式:边录制边获取数据片段,适用于实时语音识别、音频可视化等场景
  • 非流式模式:只在录音结束后获取完整数据,适用于普通录音场景

通过以下参数控制录音模式:

  • isStreaming: 显式指定是否使用流式模式(默认基于是否提供了onDataAvailable或timeslice自动判断)
  • timeslice: 流式模式下数据块间隔时间(毫秒)
  • onDataAvailable: 流式数据回调函数

基本录音示例

import { createRecorder } from 'mstf-kit';

async function startRecording() {
  try {
    // 创建录音器(非流式模式)
    const recorder = await createRecorder({
      format: 'wav',       // 音频格式: 'wav', 'mp3', 'webm', 'ogg'
      sampleRate: 44100,   // 采样率 (Hz)
      channelCount: 1,     // 通道数量
      bitRate: 128,        // 比特率 (kbps)
      echoCancellation: true,  // 回声消除
      noiseSuppression: true,  // 噪声抑制
      autoGainControl: true,   // 自动增益
      isStreaming: false   // 非流式模式,只在 stop() 后获取完整录音
    });
    
    // 开始录音
    await recorder.start();
    
    // 5秒后停止录音
    setTimeout(async () => {
      // 停止录音并获取录音数据
      const audioBlob = await recorder.stop();
      
      // 创建音频URL
      const audioUrl = URL.createObjectURL(audioBlob);
      console.log('录音完成,音频URL:', audioUrl);
      
      // 播放录音
      const audio = new Audio(audioUrl);
      audio.play();
      
      // 释放资源
      recorder.release();
    }, 5000);
  } catch (error) {
    console.error('录音失败:', error);
  }
}

流式录音示例

使用流式获取音频数据,适用于实时语音识别、音频可视化等场景:

import { createRecorder } from 'mstf-kit';

async function streamRecording() {
  try {
    // 创建带流式回调的录音器(显式指定流式模式)
    const recorder = await createRecorder({
      format: 'wav',
      sampleRate: 16000,  // 16kHz 采样率,适合语音识别
      isStreaming: true,  // 启用流式模式
      
      // 每300毫秒获取一次数据块
      timeslice: 300,
      
      // 流式数据回调
      onDataAvailable: async (blob) => {
        // 实时处理数据,例如发送到语音识别API
        console.log(`收到音频数据: ${blob.size} 字节`);
        
        // 可以发送到后端进行实时处理
        // await sendToSpeechRecognition(blob);
      },
      
      // 音频可视化处理
      onAudioProcess: (audioData) => {
        // 音频分析数据,可用于绘制波形图等
        drawAudioVisualization(audioData);
      }
    });
    
    // 开始录音
    await recorder.start();
    
    // 中途获取当前录音数据(不停止录音)
    setTimeout(async () => {
      const currentAudio = await recorder.getCurrentAudio();
      console.log(`当前已录制 ${recorder.getDuration()} 秒,数据大小: ${currentAudio.size} 字节`);
    }, 3000);
    
    // 10秒后停止录音
    setTimeout(() => {
      recorder.stop().then(finalBlob => {
        console.log(`录音完成,总大小: ${finalBlob.size} 字节`);
        recorder.release();
      });
    }, 10000);
  } catch (error) {
    console.error('录音失败:', error);
  }
}

// 示例:绘制音频可视化
function drawAudioVisualization(audioData) {
  // 使用Canvas或其他方式可视化音频数据
  const canvas = document.getElementById('audio-canvas');
  const ctx = canvas.getContext('2d');
  
  // 清空画布
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  
  // 绘制频谱
  const barWidth = (canvas.width / audioData.length) * 2.5;
  let x = 0;
  
  for (let i = 0; i < audioData.length; i++) {
    const barHeight = audioData[i] / 255 * canvas.height;
    
    // 使用渐变色
    const gradient = ctx.createLinearGradient(0, 0, 0, canvas.height);
    gradient.addColorStop(0, '#5cf');
    gradient.addColorStop(1, '#06c');
    ctx.fillStyle = gradient;
    
    ctx.fillRect(x, canvas.height - barHeight, barWidth, barHeight);
    x += barWidth + 1;
  }
}

服务器集成示例

将录音功能与服务器集成,可实现实时语音识别、音频处理等高级功能。

我们提供了详细的服务器集成指南,包括基于REST API和WebSocket的不同实现方式,以及Node.js和Python的服务器端示例代码:

👉 查看详细服务器集成指南

主要集成方式:

  • REST API模式:使用HTTP请求定期发送音频数据块,适合已有RESTful架构的系统
  • WebSocket模式:使用WebSocket实现真正的实时音频流传输,适合需要低延迟的应用场景

服务器端实现支持:

  • Node.js实现(基于Express)
  • Python实现(基于FastAPI)

服务器集成指南中包含完整的客户端和服务器端代码示例,以及最佳实践和常见问题解决方案。

🔊 音频播放器

mstf-kit 提供了功能强大的音频播放工具,支持背景播放和页面渲染两种模式:

背景播放模式

import { createAudioPlayer, playAudio } from 'mstf-kit';

// 简易播放方式
const audioBlob = new Blob([...]); // 音频数据
const player = await playAudio(audioBlob, {
  volume: 0.8,
  loop: true
});

// 或使用完整API
const backgroundPlayer = createAudioPlayer();
await backgroundPlayer.load('https://example.com/audio.mp3');
await backgroundPlayer.play();

// 控制播放
backgroundPlayer.pause();
backgroundPlayer.setVolume(0.5);
backgroundPlayer.seek(30); // 跳转到30秒位置

页面渲染模式

import { createAudioPlayer, AUDIO_FORMATS } from 'mstf-kit';

// 创建一个带UI界面的播放器
const uiPlayer = createAudioPlayer({
  renderUI: true,           // 启用UI渲染
  container: '#player-box', // 指定容器元素
  theme: 'dark',            // 使用暗色主题
  showVisualization: true,  // 显示音频可视化
  visualizationType: 'bars' // 使用柱状频谱图
});

// 加载音频
await uiPlayer.load(audioBlob);
await uiPlayer.play();

// 播放结束后的回调
uiPlayer.onEnded = () => {
  console.log('播放完成');
};

// 不需要时释放资源
uiPlayer.destroy();

Vue 集成

与 Vue3 框架无缝集成,支持直接使用 ref 作为容器:

import { ref, onMounted, onUnmounted } from 'vue';
import { createAudioPlayer } from 'mstf-kit';

export default {
  setup() {
    // 创建容器引用
    const playerContainer = ref(null);
    let audioPlayer = null;
    
    onMounted(async () => {
      // 创建播放器并使用ref作为容器
      audioPlayer = createAudioPlayer({
        renderUI: true,
        container: playerContainer, // 直接传入ref
        theme: 'dark',
        showVisualization: true
      });
      
      // 加载并播放音频
      await audioPlayer.load('/audio/example.mp3');
      await audioPlayer.play();
    });
    
    // 组件卸载时清理资源
    onUnmounted(() => {
      if (audioPlayer) {
        audioPlayer.destroy();
      }
    });
    
    return { playerContainer };
  }
}

可视化类型

播放器支持三种可视化类型:

  • waveform: 波形图显示
  • bars: 频谱柱状图
  • circle: 圆形频谱图

支持的主题

  • default: 默认主题(浅色)
  • dark: 暗色主题
  • minimal: 简约主题(透明背景)

🎭 Lottie动画

mstf-kit 支持 Lottie 动画的加载、渲染和控制,可以轻松地在您的应用中展示高质量的矢量动画。

基本使用

import { createLottiePlayer, playLottie } from 'mstf-kit';

// 快速加载并播放Lottie动画
const player = await playLottie(
  'https://assets.lottiefiles.com/packages/lf20_UJNc2t.json',
  '#animation-container',
  { loop: true, speed: 1.5 }
);

// 或使用完整API
const lottiePlayer = await createLottiePlayer({
  container: '#animation-container',
  renderer: 'canvas', // dotlottie-web 使用 canvas 渲染
  loop: true,
  autoplay: true
});

// 加载动画
await lottiePlayer.load('https://assets.lottiefiles.com/packages/lf20_UJNc2t.json');

// 控制动画
lottiePlayer.pause();
lottiePlayer.setSpeed(2.0);
lottiePlayer.play();

Vue 集成

与 Vue3 框架无缝集成,支持直接使用 ref 作为容器:

import { ref } from 'vue';
import { playLottie } from 'mstf-kit';

export default {
  setup() {
    // 创建容器引用
    const animationContainer = ref(null);
    
    // 加载动画(在onMounted中)
    onMounted(async () => {
      const player = await playLottie(
        'https://assets.lottiefiles.com/packages/lf20_UJNc2t.json',
        animationContainer,
        { loop: true }
      );
    });
    
    return { animationContainer };
  }
}

多种库加载模式

支持多种加载方式:

// 默认使用内置的 dotlottie-web
const player1 = await createLottiePlayer({
  container: '#animation-container',
  loop: true
});

// 使用自定义外部库
import customLottieLib from 'custom-lottie-lib';
const player2 = await createLottiePlayer({
  container: '#animation-container',
  libOptions: {
    source: 'external',
    externalLib: customLottieLib
  }
});

// 从CDN加载
const player3 = await createLottiePlayer({
  container: '#animation-container',
  libOptions: {
    source: 'cdn',
    cdnURL: 'https://cdn.jsdelivr.net/npm/@lottiefiles/dotlottie-web/+esm'
  }
});

渲染模式

Lottie播放器默认使用Canvas渲染模式,提供高性能的动画播放体验。

动画控制

播放器支持丰富的控制方法:

// 播放控制
player.play();
player.pause();
player.stop();

// 播放速度和方向
player.setSpeed(1.5);  // 1.5倍速
player.setDirection(-1); // 反向播放

// 跳转控制
player.goToFrame(24);  // 跳转到第24帧
player.goToAndPlay(24); // 跳转并播放
player.setSegment(10, 50); // 只播放10-50帧

// 循环控制
player.setLoop(true);  // 无限循环
player.setLoop(3);     // 循环3次

// 动画信息
console.log(`总帧数: ${player.getTotalFrames()}`);
console.log(`当前帧: ${player.getCurrentFrame()}`);
console.log(`时长: ${player.getDuration()}ms`);
console.log(`是否播放中: ${player.isPlaying()}`);

// 资源释放
player.destroy();

高级特性

  • 小巧高效: 使用 dotlottie-web 库,体积更小,性能更好
  • 多种库来源: 支持内置库(默认)、CDN加载或外部提供的自定义库
  • Vue框架支持: 无缝支持Vue3的ref作为容器引用
  • 多种来源: 支持从URL、JSON字符串或对象加载动画
  • 动画事件: 提供丰富的回调函数,可监听动画状态变化
  • 响应式: 通过resize()方法支持自适应容器大小

📄 许可证

MIT © mustafa

0.2.4

10 months ago

0.2.3

10 months ago

0.2.2

10 months ago

0.2.1

10 months ago

0.2.0

10 months ago

0.1.9

10 months ago

0.1.8

10 months ago

0.1.7

10 months ago

0.1.6

10 months ago

0.1.5

10 months ago

0.1.4

10 months ago

0.1.3

10 months ago

0.1.2

10 months ago

0.1.1

10 months ago

0.1.0

10 months ago