npm package: @skatteguru/music-player
Description: A comprehensive React-based music player library with advanced audio processing, visualization, and playlist management capabilities.
Latest version: 0.1.2

# @skatteguru/music-player

A comprehensive React-based music player library with advanced audio processing, visualization, and playlist management capabilities.

## ✨ Features

### 🎵 Core Audio
- **Advanced Audio Context**: Web Audio API-based processing with `AudioContextManager` and `AudioNodesManager`
- **Cross-fade Support**: Dual audio sources with gain node controls for seamless transitions
- **Multiple Audio Formats**: Support for MP3, WAV, and other web-compatible audio formats
- **Audio Error Handling**: Robust error boundaries and fallback mechanisms

### 🎨 UI Components
- **PlaylistPlayerButton**: Easy-to-use playlist launcher component
- **PlayingView**: Full-featured player interface with controls and visualization
- **FrequencyVisualizer**: Real-time audio frequency analysis and visualization
- **MiniFrequencyVisualizer**: Compact visualization for minimized player
- **LyricsOverlay**: ASS/SSA subtitle format support with synchronized lyrics
- **AudioErrorBoundary**: Error handling wrapper for audio components

### 🎛️ Player Features
- **Playlist Management**: Full playlist support with track navigation
- **Real-time Controls**: Play, pause, skip, seek, volume, and mute controls
- **Progress Tracking**: Visual progress bars with drag-to-seek functionality
- **Context Provider**: React Context-based state management with `MusicProvider`
- **Minimizable Interface**: Collapsible player that can be minimized to a small widget

### 🔧 Developer Tools
- **TypeScript Support**: Full TypeScript definitions and type safety
- **Testing Suite**: Comprehensive test coverage with Vitest and React Testing Library
- **Development Server**: Live testing environment with sample tracks
- **Automatic Publishing**: GitHub Actions workflow for npm publishing

## 📦 Installation

```bash
npm install @skatteguru/music-player
```

## 🚀 Quick Start

### Basic Playlist Player

```tsx
import React from 'react';
import { MusicProvider, PlaylistPlayerButton } from '@skatteguru/music-player';

const tracks = [
  {
    src: '/audio/song1.mp3',
    title: 'Song One',
    artist: 'Artist Name',
    canvas: undefined,
    cover: undefined,
    lyricsURL: undefined,
  },
  {
    src: '/audio/song2.mp3',
    title: 'Song Two',
    artist: 'Artist Name',
    canvas: undefined,
    cover: undefined,
    lyricsURL: undefined,
  },
];

function App() {
  return (
    <MusicProvider>
      <PlaylistPlayerButton playlist={tracks}>
        <button>🎵 Play Playlist</button>
      </PlaylistPlayerButton>
    </MusicProvider>
  );
}
```

### Advanced Usage with Context

```tsx
import React from 'react';
import {
  MusicProvider,
  PlaylistPlayerButton,
  useMusicContext,
  AudioErrorBoundary
} from '@skatteguru/music-player';

function PlayerStatus() {
  const { isPlaying, currentTrack, currentTime } = useMusicContext();

  return (
    <div>
      <p>Now Playing: {currentTrack?.title || 'Nothing'}</p>
      <p>Status: {isPlaying ? 'Playing' : 'Paused'}</p>
      <p>Time: {currentTime.toFixed(1)}s</p>
    </div>
  );
}

function App() {
  return (
    <MusicProvider>
      <AudioErrorBoundary>
        <PlaylistPlayerButton playlist={tracks} />
        <PlayerStatus />
      </AudioErrorBoundary>
    </MusicProvider>
  );
}
```

### Low-Level Audio API

```tsx
import { AudioContextManager, AudioNodesManager } from '@skatteguru/music-player';

async function setupAudio() {
  const contextManager = new AudioContextManager();
  await contextManager.initialize();

  const context = contextManager.getContext();
  if (context) {
    const nodesManager = new AudioNodesManager(context);
    nodesManager.initializeNodes();
    nodesManager.loadTrack('/audio/track.mp3', 0);
  }
}
```

## 🧪 Development Server

We provide a comprehensive development server for testing the library:

```bash
npm run dev:server
```

This starts a React development server at `http://localhost:3000` with:

### Testing Interface
- **Playlist Player Test**: Test the main `PlaylistPlayerButton` component
- **Individual Track Test**: Test single track playback
- **Audio Context Test**: Test low-level audio components
- **Player State Display**: Monitor the `MusicContext` state in real-time

### Sample Audio
- Pre-configured sample tracks for immediate testing
- Browser console logging for debugging
- Interactive controls to test all functionality

## 🛠️ Development

```bash
# Install dependencies
npm install

# Run tests
npm test

# Watch tests during development
npm test:watch

# TypeScript type checking
npm run typecheck

# Build the library
npm run build

# Start development server for testing
npm run dev:server

# Watch build during development
npm run dev
```

## 🧪 Testing

The library includes comprehensive tests:

```bash
# Run all tests
npm test

# Run tests in watch mode
npm test:watch

# Run specific test file
npm test src/lib/__tests__/nodes.test.ts
```

Tests cover:
- Audio context management
- Node initialization and connections
- Playlist management
- Component rendering
- Error handling
- Mock audio environment

## 📚 API Reference

### Components

#### `MusicProvider`
Context provider that manages global music player state.

#### `PlaylistPlayerButton`
```tsx
interface PlaylistPlayerButtonProps {
  playlist: Track[];
  children?: React.ReactNode;
  playbackRate?: number;
  onTrackChange?: (track: { title: string; src: string }) => void;
  active?: boolean;
  forceEnableExperimentalFeatures?: boolean;
}
```

#### `PlayingView`
Full player interface with controls and visualization.

#### `FrequencyVisualizer`
Real-time audio frequency visualization component.

### Hooks

#### `useMusicContext()`
Access the music player context state and controls.

```tsx
const {
  playlist,
  isPlaying,
  currentTrack,
  currentTime,
  startPlaying,
  stopPlaying,
  setPlaylist,
} = useMusicContext();
```

### Types

```tsx
interface Track {
  src: string;
  title: string;
  artist: string;
  canvas?: { src: string };
  cover?: string;
  lyricsURL?: string;
}
```

## 🚀 Publishing

The library is automatically published to npm when code is pushed to the `master` branch via GitHub Actions.

### Setup Required:
1. Add `NPM_TOKEN` to GitHub repository secrets
2. Token should have automation permissions for CI/CD

The workflow will:
- Install dependencies
- Run tests
- Build the package
- Publish to npmjs.org

## 📁 Project Structure

```
src/
├── components/          # React UI components
│   ├── PlaylistPlayer.tsx
│   ├── PlayingView.tsx
│   ├── FrequencyVisualizer.tsx
│   └── ...
├── contexts/           # React Context providers
│   └── MusicContext.tsx
├── lib/               # Core audio logic
│   ├── musicplayer.ts
│   ├── nodes.ts
│   ├── context.ts
│   └── __tests__/
└── index.ts           # Main exports

dev/                   # Development server
├── src/
│   ├── App.tsx       # Test interface
│   └── main.tsx
└── index.html

.github/workflows/     # CI/CD
└── publish.yml       # Auto-publish to npm
```

## 🤝 Contributing

1. Clone the repository
2. Install dependencies: `npm install`
3. Start the dev server: `npm run dev:server`
4. Make changes and test with the development interface
5. Run tests: `npm test`
6. Build: `npm run build`

## 📄 License

Private - All rights reserved