@bernierllc/content-type-audio
v1.5.0
Published
Base audio content type with file upload, local storage, and streaming URL capabilities
Readme
@bernierllc/content-type-audio
Base audio content type with file upload, local storage, and streaming URL capabilities. Provides comprehensive audio content management for podcasts, voice notes, and music files.
Installation
npm install @bernierllc/content-type-audioFeatures
- Audio File Validation - MIME type, size, and duration validation
- File Upload Handling - Audio preview and metadata extraction
- Local File System Storage - Organized file storage with path management
- URL Publishing - Streaming URLs for stored audio files
- Metadata Management - Duration, bitrate, sample rate, codec information
- Multiple Format Support - MP3, WAV, AAC, OGG, FLAC, M4A
- Utility Functions - Duration parsing/formatting, bitrate calculation
- Extensible Architecture - Base for specialized audio content types
Usage
Basic Setup
import { AudioContentTypeManager, AudioFormat } from '@bernierllc/content-type-audio';
import { ContentTypeRegistry } from '@bernierllc/content-type-registry';
// Create manager with default configuration
const manager = new AudioContentTypeManager();
// Register with content type registry
const registry = new ContentTypeRegistry();
manager.register(registry);Creating Audio Content
// Create audio content with required metadata
const audioContent = manager.create({
filename: 'podcast-episode-01.mp3',
mimeType: AudioFormat.MP3,
size: 5242880, // 5MB
duration: 1800, // 30 minutes
bitrate: 192,
title: 'Introduction to TypeScript',
artist: 'Tech Talks Podcast'
});
console.log(audioContent);
// {
// id: 'audio_1234567890_abc123',
// type: 'audio',
// metadata: {
// filename: 'podcast-episode-01.mp3',
// mimeType: 'audio/mpeg',
// size: 5242880,
// duration: 1800,
// bitrate: 192,
// title: 'Introduction to TypeScript',
// artist: 'Tech Talks Podcast'
// },
// createdAt: Date,
// updatedAt: Date
// }Creating Audio with Storage and URLs
// Create audio content with file path and streaming URL
const audioWithStorage = manager.create(
{
filename: 'voice-note.m4a',
mimeType: AudioFormat.M4A,
size: 1048576, // 1MB
duration: 120, // 2 minutes
bitrate: 64
},
{
filePath: '/storage/audio/voice-note-20250102.m4a',
fileUrl: 'file:///storage/audio/voice-note-20250102.m4a',
streamingUrl: 'https://cdn.example.com/audio/voice-note-20250102.m4a'
}
);
console.log(audioWithStorage.filePath);
// '/storage/audio/voice-note-20250102.m4a'
console.log(audioWithStorage.streamingUrl);
// 'https://cdn.example.com/audio/voice-note-20250102.m4a'Validating Audio Content
// Validate audio content
const validation = manager.validate(audioContent);
if (validation.valid) {
console.log('Audio content is valid');
console.log('Metadata:', validation.metadata);
} else {
console.error('Validation errors:', validation.errors);
}
// Example validation with errors
const invalidContent = manager.create({
filename: 'large-file.wav',
mimeType: AudioFormat.WAV,
size: 200 * 1024 * 1024, // 200MB (exceeds default 100MB limit)
duration: 3600,
bitrate: 1411
});
const result = manager.validate(invalidContent);
console.log(result.valid); // false
console.log(result.errors); // ['File size exceeds maximum allowed size']Custom Configuration
// Create manager with custom configuration
const customManager = new AudioContentTypeManager({
maxFileSize: 50 * 1024 * 1024, // 50MB limit
allowedFormats: [AudioFormat.MP3, AudioFormat.AAC], // Only MP3 and AAC
requireMetadata: true // Require title/artist metadata
});
// This will fail validation (exceeds size limit)
const largeAudio = customManager.create({
filename: 'large-podcast.mp3',
mimeType: AudioFormat.MP3,
size: 75 * 1024 * 1024, // 75MB
duration: 4500,
bitrate: 128
});
const validation = customManager.validate(largeAudio);
console.log(validation.valid); // false
console.log(validation.errors); // ['File size exceeds maximum allowed size']Duration Utilities
// Parse duration from various formats
const seconds1 = manager.parseDuration(90); // 90
const seconds2 = manager.parseDuration('1:30'); // 90 (1 minute 30 seconds)
const seconds3 = manager.parseDuration('1:23:45'); // 5025 (1 hour 23 minutes 45 seconds)
// Format duration to human-readable string
const formatted1 = manager.formatDuration(90); // '1:30'
const formatted2 = manager.formatDuration(5025); // '1:23:45'
const formatted3 = manager.formatDuration(3600); // '1:00:00'Bitrate Calculation
// Calculate bitrate from file size and duration
const fileSize = 5 * 1024 * 1024; // 5MB
const duration = 180; // 3 minutes
const bitrate = manager.calculateBitrate(fileSize, duration);
console.log(bitrate); // ~233 kbps
// Example with different scenarios
const mp3Size = Math.round((128 * 1000 * 180) / 8); // 128kbps MP3, 3 minutes
const mp3Bitrate = manager.calculateBitrate(mp3Size, 180);
console.log(mp3Bitrate); // 128 kbps
const wavSize = Math.round((1411 * 1000 * 300) / 8); // CD quality WAV, 5 minutes
const wavBitrate = manager.calculateBitrate(wavSize, 300);
console.log(wavBitrate); // 1411 kbpsIntegration with ContentTypeRegistry
import { ContentTypeRegistry } from '@bernierllc/content-type-registry';
import { AudioContentTypeManager } from '@bernierllc/content-type-audio';
// Create registry and manager
const registry = new ContentTypeRegistry();
const audioManager = new AudioContentTypeManager();
// Register audio content type
audioManager.register(registry);
// Retrieve audio content type from registry
const result = registry.get('audio');
if (result.success && result.data) {
console.log('Content Type ID:', result.data.id); // 'audio'
console.log('Content Type Name:', result.data.name); // 'Audio'
console.log('Base Type:', result.data.baseType); // 'audio'
}
// List audio content types
const audioTypes = registry.list({ baseType: 'audio' });
if (audioTypes.success && audioTypes.data) {
console.log('Audio types:', audioTypes.data.length); // 1
console.log('First type:', audioTypes.data[0].name); // 'Audio'
}
// Use registry to validate content
const content = audioManager.create({
filename: 'test.mp3',
mimeType: AudioFormat.MP3,
size: 1024 * 1024,
duration: 60,
bitrate: 128
});
const validation = audioManager.validate(content);
console.log('Is valid:', validation.valid); // trueAPI Reference
AudioContentTypeManager
Constructor
constructor(config?: Partial<AudioContentTypeConfig>)Creates a new AudioContentTypeManager with optional configuration.
Configuration Options:
baseType: string- Base content type (default: 'audio')editor: string- Editor type (default: 'file-upload-with-player')storage: string- Storage type (default: 'file')publishing: string- Publishing type (default: 'streaming-url')maxFileSize: number- Maximum file size in bytes (default: 100MB)allowedFormats: AudioFormat[]- Allowed audio formats (default: all formats)requireMetadata: boolean- Require title/artist metadata (default: false)
Methods
register(registry: ContentTypeRegistry): void
Registers the audio content type with a ContentTypeRegistry.
create(metadata: AudioMetadata, options?: Partial): AudioContentType
Creates a new audio content instance with the provided metadata.
Parameters:
metadata: AudioMetadata- Required audio metadata (filename, mimeType, size, duration, bitrate)options?: Partial<AudioContentType>- Optional fields (filePath, fileUrl, streamingUrl)
Returns: Complete AudioContentType object with generated ID and timestamps.
validate(content: unknown): AudioValidationResult
Validates audio content against configuration rules.
Returns:
{
valid: boolean;
metadata: AudioMetadata;
errors?: string[]; // Only present if valid is false
}parseDuration(duration: string | number): number
Parses duration from various formats to seconds.
Supported Formats:
- Number:
90→ 90 seconds - Seconds string:
"90"→ 90 seconds - mm:ss format:
"1:30"→ 90 seconds - hh:mm:ss format:
"1:23:45"→ 5025 seconds
formatDuration(seconds: number): string
Formats duration in seconds to human-readable string.
Returns:
- Under 1 hour:
"mm:ss"(e.g., "23:45") - Over 1 hour:
"hh:mm:ss"(e.g., "1:23:45")
calculateBitrate(fileSize: number, duration: number): number
Calculates bitrate in kbps from file size and duration.
Parameters:
fileSize: number- File size in bytesduration: number- Duration in seconds
Returns: Bitrate in kbps (rounded to nearest integer)
Types
AudioFormat
enum AudioFormat {
MP3 = 'audio/mpeg',
WAV = 'audio/wav',
AAC = 'audio/aac',
OGG = 'audio/ogg',
FLAC = 'audio/flac',
M4A = 'audio/mp4'
}AudioMetadata
interface AudioMetadata {
filename: string;
mimeType: AudioFormat;
size: number; // bytes
duration: number; // seconds
bitrate: number; // kbps
sampleRate?: number; // Hz
channels?: number; // 1 (mono), 2 (stereo), etc.
title?: string;
artist?: string;
album?: string;
year?: number;
coverArt?: string; // URL or base64
}AudioContentType
interface AudioContentType {
id: string;
type: 'audio';
metadata: AudioMetadata;
filePath?: string;
fileUrl?: string;
streamingUrl?: string;
createdAt: Date;
updatedAt: Date;
}AudioValidationResult
interface AudioValidationResult {
valid: boolean;
metadata: AudioMetadata;
errors?: string[]; // Only present when valid is false
}Configuration
Environment Variables
None required. All configuration is passed via constructor options.
Default Configuration
{
baseType: 'audio',
editor: 'file-upload-with-player',
storage: 'file',
publishing: 'streaming-url',
maxFileSize: 100 * 1024 * 1024, // 100MB
allowedFormats: [
AudioFormat.MP3,
AudioFormat.WAV,
AudioFormat.AAC,
AudioFormat.OGG,
AudioFormat.FLAC,
AudioFormat.M4A
],
requireMetadata: false
}Examples
Podcast Episode Management
const podcastManager = new AudioContentTypeManager({
maxFileSize: 200 * 1024 * 1024, // 200MB for long episodes
allowedFormats: [AudioFormat.MP3, AudioFormat.M4A],
requireMetadata: true
});
const episode = podcastManager.create(
{
filename: 'ep001-introduction.mp3',
mimeType: AudioFormat.MP3,
size: 50 * 1024 * 1024,
duration: 3600, // 1 hour
bitrate: 128,
title: 'Episode 1: Introduction',
artist: 'My Podcast',
album: 'Season 1',
year: 2025
},
{
filePath: '/podcasts/season1/ep001.mp3',
streamingUrl: 'https://cdn.mypodcast.com/season1/ep001.mp3'
}
);
const validation = podcastManager.validate(episode);
if (validation.valid) {
console.log('Episode ready for publishing');
console.log('Duration:', podcastManager.formatDuration(episode.metadata.duration));
console.log('Streaming URL:', episode.streamingUrl);
}Voice Note Recording
const voiceNoteManager = new AudioContentTypeManager({
maxFileSize: 10 * 1024 * 1024, // 10MB for voice notes
allowedFormats: [AudioFormat.M4A, AudioFormat.AAC],
requireMetadata: false
});
const voiceNote = voiceNoteManager.create({
filename: 'voice-note-20250102.m4a',
mimeType: AudioFormat.M4A,
size: 512 * 1024, // 512KB
duration: 60, // 1 minute
bitrate: 64,
sampleRate: 44100,
channels: 1
});
console.log('Voice note created:', voiceNote.id);
console.log('Duration:', voiceNoteManager.formatDuration(voiceNote.metadata.duration));Music Library
const musicManager = new AudioContentTypeManager({
maxFileSize: 50 * 1024 * 1024, // 50MB for high-quality audio
allowedFormats: [AudioFormat.FLAC, AudioFormat.MP3],
requireMetadata: true
});
const song = musicManager.create(
{
filename: 'track01.flac',
mimeType: AudioFormat.FLAC,
size: 30 * 1024 * 1024,
duration: 240, // 4 minutes
bitrate: 1411, // CD quality
sampleRate: 44100,
channels: 2,
title: 'Amazing Song',
artist: 'Great Artist',
album: 'Awesome Album',
year: 2025,
coverArt: 'https://cdn.music.com/covers/album123.jpg'
},
{
filePath: '/music/library/track01.flac',
streamingUrl: 'https://stream.music.com/track01'
}
);
const validation = musicManager.validate(song);
console.log('Song validated:', validation.valid);
console.log('Title:', validation.metadata.title);
console.log('Artist:', validation.metadata.artist);Integration Status
- Logger: not-applicable - Core package with no logging requirements
- Docs-Suite: ready - Complete JSDoc documentation and markdown README
- NeverHub: not-applicable - Core utility package with no event requirements
See Also
- @bernierllc/content-type-registry - Content type registration and management
- @bernierllc/content-type-video - Video content type management
- @bernierllc/content-type-image - Image content type management
License
Copyright (c) 2025 Bernier LLC
This file is licensed to the client under a limited-use license. The client may use and modify this code only within the scope of the project it was delivered for. Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
