API Reference
This document provides comprehensive API reference for the M3U8 Online Player, including JavaScript APIs, events, and integration methods.
JavaScript API
Player Instance
Creating a Player Instance
// Get the video player element
const videoPlayer = document.getElementById('video-player') as HTMLVideoElement;
// Access player methods and properties
const player = {
element: videoPlayer,
currentUrl: ref(''),
isPlaying: ref(false),
volume: ref(100),
// ... other properties
};
Player Properties
interface PlayerState {
currentUrl: string; // Current stream URL
isLoading: boolean; // Loading state
error: string; // Error message
isPlaying: boolean; // Playback state
isMuted: boolean; // Mute state
volume: number; // Volume level (0-100)
currentTime: number; // Current playback time
duration: number; // Total stream duration
streamInfo: StreamInfo; // Stream metadata
}
Core Methods
loadStream(url: string)
Loads a new M3U8 stream into the player.
const loadStream = async (url: string): Promise<void> => {
if (!isValidUrl(url)) {
throw new Error('Invalid URL format');
}
isLoading.value = true;
error.value = '';
try {
currentUrl.value = url;
addToHistory();
toast.success('Stream loaded successfully');
} catch (err: any) {
error.value = err.message || 'Failed to load stream';
toast.error(error.value);
} finally {
isLoading.value = false;
}
};
// Usage
await loadStream('https://example.com/stream.m3u8');
togglePlayPause()
Toggles between play and pause states.
const togglePlayPause = (): void => {
if (!videoPlayer.value) return;
if (isPlaying.value) {
videoPlayer.value.pause();
} else {
videoPlayer.value.play();
}
};
updateVolume(volume: number)
Updates the player volume.
const updateVolume = (newVolume: number): void => {
if (!videoPlayer.value) return;
videoPlayer.value.volume = newVolume / 100;
volume.value = newVolume;
isMuted.value = newVolume === 0;
};
// Usage
updateVolume(75); // Set volume to 75%
Utility Functions
URL Validation
const isValidUrl = (url: string): boolean => {
try {
new URL(url);
return url.includes('.m3u8') || url.includes('m3u8');
} catch {
return false;
}
};
Title Extraction
const extractTitleFromUrl = (url: string): string => {
try {
const urlObj = new URL(url);
const pathname = urlObj.pathname;
const filename = pathname.split('/').pop() || '';
return filename.replace('.m3u8', '') || 'M3U8 Stream';
} catch {
return 'M3U8 Stream';
}
};
Time Formatting
const formatTime = (seconds: number): string => {
if (!seconds || isNaN(seconds)) return '00:00';
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const secs = Math.floor(seconds % 60);
if (hours > 0) {
return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}
return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
};
Event System
Video Events
Load Events
// Stream loading started
videoPlayer.addEventListener('loadstart', () => {
isLoading.value = true;
error.value = '';
});
// Stream metadata loaded
videoPlayer.addEventListener('loadedmetadata', () => {
isLoading.value = false;
if (videoPlayer.value) {
duration.value = videoPlayer.value.duration;
volume.value = Math.round(videoPlayer.value.volume * 100);
isMuted.value = videoPlayer.value.muted;
}
});
Playback Events
// Playback started
videoPlayer.addEventListener('play', () => {
isPlaying.value = true;
});
// Playback paused
videoPlayer.addEventListener('pause', () => {
isPlaying.value = false;
});
// Volume changed
videoPlayer.addEventListener('volumechange', () => {
if (videoPlayer.value) {
volume.value = Math.round(videoPlayer.value.volume * 100);
isMuted.value = videoPlayer.value.muted;
}
});
Error Events
// Stream error occurred
videoPlayer.addEventListener('error', (event: Event) => {
isLoading.value = false;
const target = event.target as HTMLVideoElement;
error.value = target.error?.message || 'Playback error occurred';
toast.error(error.value);
});
Custom Events
Stream Events
// Custom event for stream loaded
const dispatchStreamLoaded = (url: string) => {
const event = new CustomEvent('streamLoaded', {
detail: { url, timestamp: Date.now() },
});
window.dispatchEvent(event);
};
// Custom event for stream error
const dispatchStreamError = (error: string) => {
const event = new CustomEvent('streamError', {
detail: { error, timestamp: Date.now() },
});
window.dispatchEvent(event);
};
History Management API
History Operations
Add to History
const addToHistory = (): void => {
const record = {
id: Date.now().toString(),
url: m3u8Url.value,
title: extractTitleFromUrl(m3u8Url.value),
timestamp: Date.now(),
};
toolsStore.addM3u8PlayerHistory(record);
};
Load from History
const loadFromHistory = (record: HistoryRecord): void => {
m3u8Url.value = record.url;
loadStream();
};
Remove from History
const removeFromHistory = (id: string): void => {
toolsStore.removeM3u8PlayerHistory(id);
toast.success('Removed from history');
};
Clear History
const clearHistory = (): void => {
toolsStore.clearM3u8PlayerHistory();
toast.success('History cleared');
};
History Data Structure
interface HistoryRecord {
id: string; // Unique identifier
url: string; // Stream URL
title: string; // Stream title
timestamp: number; // Last accessed timestamp
}
Store Integration
Pinia Store Methods
State Management
// Access store
const toolsStore = useToolsStore();
// Get history records
const historyRecords = computed(() => {
return [...toolsStore.m3u8Player.history].sort((a, b) => b.timestamp - a.timestamp);
});
Store Actions
// Add history record
toolsStore.addM3u8PlayerHistory({
id: 'unique-id',
url: 'https://example.com/stream.m3u8',
title: 'Stream Title',
timestamp: Date.now(),
});
// Remove history record
toolsStore.removeM3u8PlayerHistory('record-id');
// Clear all history
toolsStore.clearM3u8PlayerHistory();
Integration Examples
Embedding in Other Applications
Basic Integration
<!-- HTML -->
<div id="m3u8-player-container">
<video id="video-player" controls preload="metadata">
<p>Your browser does not support the video tag.</p>
</video>
</div>
// JavaScript
const player = {
element: document.getElementById('video-player'),
loadStream: async (url: string) => {
// Implementation
},
// ... other methods
};
React Integration
import { useEffect, useRef, useState } from 'react';
const M3U8Player: React.FC = () => {
const videoRef = useRef<HTMLVideoElement>(null);
const [currentUrl, setCurrentUrl] = useState('');
const [isPlaying, setIsPlaying] = useState(false);
const loadStream = async (url: string) => {
if (videoRef.current) {
videoRef.current.src = url;
setCurrentUrl(url);
}
};
return (
<div>
<video
ref={videoRef}
controls
onPlay={() => setIsPlaying(true)}
onPause={() => setIsPlaying(false)}
/>
</div>
);
};
Vue Integration
<template>
<div>
<video ref="videoPlayer" :src="currentUrl" controls @play="onPlay" @pause="onPause" />
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue';
const videoPlayer = ref<HTMLVideoElement>();
const currentUrl = ref('');
const isPlaying = ref(false);
const loadStream = async (url: string) => {
currentUrl.value = url;
};
const onPlay = () => {
isPlaying.value = true;
};
const onPause = () => {
isPlaying.value = false;
};
</script>
URL Parameters
Direct Stream Loading
// Load stream from URL parameter
const loadFromUrlParam = () => {
const urlParams = new URLSearchParams(window.location.search);
const streamUrl = urlParams.get('stream');
if (streamUrl && isValidUrl(streamUrl)) {
loadStream(streamUrl);
}
};
// Usage: /m3u8-player?stream=https://example.com/stream.m3u8
Configuration Parameters
// Load configuration from URL parameters
const loadConfigFromUrl = () => {
const urlParams = new URLSearchParams(window.location.search);
const config = {
autoplay: urlParams.get('autoplay') === 'true',
volume: parseInt(urlParams.get('volume') || '100'),
muted: urlParams.get('muted') === 'true',
};
return config;
};
Error Handling
Error Types
enum StreamError {
INVALID_URL = 'INVALID_URL',
NETWORK_ERROR = 'NETWORK_ERROR',
FORMAT_ERROR = 'FORMAT_ERROR',
CODEC_ERROR = 'CODEC_ERROR',
PERMISSION_ERROR = 'PERMISSION_ERROR',
}
Error Handling Functions
const handleStreamError = (error: Error): void => {
let errorMessage = 'Unknown error occurred';
switch (error.name) {
case 'NotSupportedError':
errorMessage = 'Stream format not supported';
break;
case 'NetworkError':
errorMessage = 'Network connection failed';
break;
case 'AbortError':
errorMessage = 'Stream loading aborted';
break;
default:
errorMessage = error.message;
}
error.value = errorMessage;
toast.error(errorMessage);
};
Performance Monitoring
Performance Metrics
interface PerformanceMetrics {
loadTime: number; // Time to load stream
bufferHealth: number; // Buffer health percentage
droppedFrames: number; // Number of dropped frames
networkLatency: number; // Network latency in ms
}
const trackPerformance = (): PerformanceMetrics => {
return {
loadTime: performance.now() - startTime,
bufferHealth: calculateBufferHealth(),
droppedFrames: getDroppedFrames(),
networkLatency: measureLatency(),
};
};
This API reference provides comprehensive documentation for integrating and extending the M3U8 Online Player functionality.