APlayer 中文文档 下载 App

npm 安装 APlayer 融入前端工程

适用场景

npm 安装适合有构建工具的前端项目:

安装

# npm
npm install aplayer --save

# yarn
yarn add aplayer

# pnpm
pnpm add aplayer

安装完成后,node_modules/aplayer/dist/ 下会有 APlayer.min.js 和 APlayer.min.css。

ES Module 引入

import 'APlayer/dist/APlayer.min.css';
import APlayer from 'APlayer';

const ap = new APlayer({
    container: document.getElementById('aplayer'),
    audio: [{
        name: '歌曲名称',
        artist: '艺术家',
        url: 'audio.mp3',
        cover: 'cover.jpg'
    }]
});

Vite 项目示例

// src/components/MusicPlayer.vue 或 .jsx
import { onMounted, ref } from 'vue';
// 或 React: import { useEffect } from 'react';
import 'APlayer/dist/APlayer.min.css';
import APlayer from 'APlayer';

export function useAPlayer(containerRef, options) {
    let ap = null;
    
    function init() {
        ap = new APlayer({
            container: containerRef.value,
            ...options
        });
    }
    
    function destroy() {
        if (ap) {
            ap.destroy();
            ap = null;
        }
    }
    
    return { init, destroy };
}

与 HLS 配合

import 'APlayer/dist/APlayer.min.css';
import APlayer from 'APlayer';
import Hls from 'hls.js';

// 注意:需要在全局挂载 Hls,让 APlayer 能检测到
window.Hls = Hls;

const ap = new APlayer({
    container: document.getElementById('aplayer'),
    audio: [{
        name: '直播流',
        artist: '来源',
        url: 'live.m3u8',
        cover: 'cover.jpg',
        type: 'hls'
    }]
});

TypeScript 类型声明

APlayer 官方没有提供 TypeScript 类型,但有社区维护的类型包:

npm install @types/aplayer --save-dev

或者你可以自己声明一个最简单的:

declare class APlayer {
    constructor(options: any);
    play(): void;
    pause(): void;
    seek(time: number): void;
    destroy(): void;
    list: any;
    audio: HTMLAudioElement;
    on(event: string, handler: Function): void;
    theme(color: string, index?: number): void;
    notice(text: string, time?: number, opacity?: number): void;
    toggle(): void;
    volume(percentage: number, nostorage?: boolean): void;
    setMode(mode: 'mini' | 'normal'): void;
    version: string;
}

构建产物体积

npm 安装后,Webpack / Vite / Rollup 等构建工具可以自动把 APlayer 打包进项目的 vendor chunk。压缩后体积大约:

CDN vs npm 怎么选

对比项CDN 引入npm 安装
上手速度30 秒几分钟
需要构建工具不需要需要
与 Vue/React 配合比较麻烦自然
版本管理URL 里写版本号package.json 管理
Tree-shaking不支持支持
离线可用不行可以
适合场景静态页面 / 快速验证前端工程化项目