Skip to content

一分钟搭建影视站,支持Docker等部署方式

Dev (#18)

Zwei3464dbd0cf49
diff --git a/js/app.js b/js/app.js
index a41ddd0..c30f2d8 100644
--- a/js/app.js
+++ b/js/app.js
@@ -7,6 +7,8 @@ let currentEpisodeIndex = 0;
let currentEpisodes = [];
// 添加当前视频的标题
let currentVideoTitle = '';
+// 新增全局变量用于倒序状态
+let episodesReversed = false;
// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
@@ -282,21 +284,20 @@ async function showDetails(id, vod_name) {
// 保存当前视频的所有集数
currentEpisodes = safeEpisodes;
-
- if (safeEpisodes.length === 0) {
- modalContent.innerHTML = '<p class="text-center text-gray-400 py-8">没有找到可用的播放链接</p>';
- } else {
- modalContent.innerHTML = `
- <div class="grid grid-cols-2 sm:grid-cols-4 md:grid-cols-6 lg:grid-cols-8 gap-2">
- ${safeEpisodes.map((episode, index) => `
- <button id="episode-${index}" onclick="playVideo('${episode}','${vod_name.replace(/"/g, '&quot;')}', ${index})"
- class="px-4 py-2 bg-[#222] hover:bg-[#333] border border-[#333] hover:border-white rounded-lg transition-colors text-center episode-btn">
- 第${index + 1}集
- </button>
- `).join('')}
- </div>
- `;
- }
+ episodesReversed = false; // 默认正序
+ modalContent.innerHTML = `
+ <div class="flex justify-end mb-2">
+ <button onclick="toggleEpisodeOrder()" class="px-4 py-2 bg-gradient-to-r from-indigo-500 via-purple-500 to-pink-500 text-white font-semibold rounded-full shadow-lg hover:shadow-xl transition-all duration-300 transform hover:-translate-y-1 flex items-center justify-center space-x-2">
+ <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
+ <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-11a1 1 0 10-2 0v3.586L7.707 9.293a1 1 0 00-1.414 1.414l3 3a1 1 0 001.414 0l3-3a1 1 0 00-1.414-1.414L11 10.586V7z" clip-rule="evenodd" />
+ </svg>
+ <span>倒序排列</span>
+ </button>
+ </div>
+ <div id="episodesGrid" class="grid grid-cols-2 sm:grid-cols-4 md:grid-cols-6 lg:grid-cols-8 gap-2">
+ ${renderEpisodes(vod_name)}
+ </div>
+ `;
} else {
modalContent.innerHTML = '<p class="text-center text-gray-400 py-8">没有找到可播放的视频</p>';
}
@@ -314,135 +315,24 @@ async function showDetails(id, vod_name) {
}
}
-// 更新播放视频函数,添加集数索引参数并使用自定义播放器
+// 更新播放视频函数,修改为在新标签页中打开播放页面
function playVideo(url, vod_name, episodeIndex = 0) {
if (!url) {
showToast('无效的视频链接', 'error');
return;
}
- showLoading();
- const modalContent = document.getElementById('modalContent');
- const modalTitle = document.getElementById('modalTitle');
+ // 保存当前状态到localStorage,让播放页面可以获取
+ localStorage.setItem('currentVideoTitle', currentVideoTitle);
+ localStorage.setItem('currentEpisodeIndex', episodeIndex);
+ localStorage.setItem('currentEpisodes', JSON.stringify(currentEpisodes));
+ localStorage.setItem('episodesReversed', episodesReversed);
- // 更新当前播放集数索引
- currentEpisodeIndex = episodeIndex;
+ // 构建播放页面URL,传递必要参数
+ const playerUrl = `player.html?url=${encodeURIComponent(url)}&title=${encodeURIComponent(vod_name)}&index=${episodeIndex}`;
- try {
- // 安全处理URL和标题
- const safeUrl = url;
- const safeTitle = vod_name ? vod_name.replace(/</g, '&lt;').replace(/>/g, '&gt;') : '未知视频';
-
- // 更新标题显示
- modalTitle.textContent = safeTitle + " - 第" + (currentEpisodeIndex + 1) + "集";
-
- // 更新当前播放的集数按钮样式
- const episodeButtons = document.querySelectorAll('.episode-btn');
- episodeButtons.forEach((btn, index) => {
- if (index === currentEpisodeIndex) {
- btn.classList.add('playing');
- btn.classList.add('bg-blue-700');
- btn.classList.remove('bg-[#222]');
- btn.classList.add('border-blue-500');
- btn.classList.remove('border-[#333]');
- } else {
- btn.classList.remove('playing');
- btn.classList.remove('bg-blue-700');
- btn.classList.add('bg-[#222]');
- btn.classList.remove('border-blue-500');
- btn.classList.add('border-[#333]');
- }
- });
-
- // 创建导航控制按钮
- const hasPrevious = currentEpisodeIndex > 0;
- const hasNext = currentEpisodeIndex < currentEpisodes.length - 1;
-
- const navigationControls = `
- <div class="flex justify-between items-center my-4">
- <button onclick="playPreviousEpisode()"
- class="px-4 py-2 ${hasPrevious ? 'bg-[#222] hover:bg-[#333]' : 'bg-gray-700 cursor-not-allowed'}
- border border-[#333] rounded-lg transition-colors"
- ${!hasPrevious ? 'disabled' : ''}>
- <svg class="w-5 h-5 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
- </svg>
- 上一集
- </button>
- <span class="text-gray-400">第 ${currentEpisodeIndex + 1}/${currentEpisodes.length} 集</span>
- <button onclick="playNextEpisode()"
- class="px-4 py-2 ${hasNext ? 'bg-[#222] hover:bg-[#333]' : 'bg-gray-700 cursor-not-allowed'}
- border border-[#333] rounded-lg transition-colors"
- ${!hasNext ? 'disabled' : ''}>
- 下一集
- <svg class="w-5 h-5 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
- </svg>
- </button>
- </div>
- `;
-
- // 先移除现有的视频播放器(如果存在)
- const existingPlayer = modalContent.querySelector('.video-player');
- if (existingPlayer) {
- existingPlayer.remove();
- }
-
- // 获取当前HTML内容并查找剧集列表
- const episodesList = modalContent.querySelector('.grid');
-
- if (episodesList) {
- // 保留剧集列表
- const episodesHtml = episodesList.outerHTML;
-
- // 使用我们的自定义播放器而不是hoplayer
- modalContent.innerHTML = `
- <div class="space-y-4">
- <div class="video-player">
- <iframe
- id="videoIframe"
- src="${CUSTOM_PLAYER_URL}?url=${encodeURIComponent(safeUrl)}"
- width="100%"
- height="600"
- frameborder="0"
- scrolling="no"
- allow="autoplay; encrypted-media; fullscreen"
- onload="hideLoading()"
- onerror="handlePlayerError()">
- </iframe>
- </div>
- ${navigationControls}
- <div class="episodes-list mt-4">
- ${episodesHtml}
- </div>
- </div>
- `;
- } else {
- // 没有找到剧集列表,重新创建完整内容
- modalContent.innerHTML = `
- <div class="space-y-4">
- <div class="video-player">
- <iframe
- id="videoIframe"
- src="${CUSTOM_PLAYER_URL}?url=${encodeURIComponent(safeUrl)}"
- width="100%"
- height="600"
- frameborder="0"
- scrolling="no"
- allow="autoplay; encrypted-media; fullscreen"
- onload="hideLoading()"
- onerror="handlePlayerError()">
- </iframe>
- </div>
- ${navigationControls}
- </div>
- `;
- }
- } catch (error) {
- console.error('播放器加载错误:', error);
- hideLoading();
- showToast('视频播放加载失败,请检查链接或稍后重试', 'error');
- }
+ // 在新标签页中打开播放页面
+ window.open(playerUrl, '_blank');
}
// 播放上一集
@@ -468,3 +358,38 @@ function handlePlayerError() {
hideLoading();
showToast('视频播放加载失败,请尝试其他视频源', 'error');
}
+
+// 新增辅助函数用于渲染剧集按钮(使用当前的排序状态)
+function renderEpisodes(vodName) {
+ const episodes = episodesReversed ? [...currentEpisodes].reverse() : currentEpisodes;
+ return episodes.map((episode, index) => {
+ // 根据倒序状态计算真实的剧集索引
+ const realIndex = episodesReversed ? currentEpisodes.length - 1 - index : index;
+ return `
+ <button id="episode-${realIndex}" onclick="playVideo('${episode}','${vodName.replace(/"/g, '&quot;')}', ${realIndex})"
+ class="px-4 py-2 bg-[#222] hover:bg-[#333] border border-[#333] rounded-lg transition-colors text-center episode-btn">
+ 第${realIndex + 1}集
+ </button>
+ `;
+ }).join('');
+}
+
+// 新增切换排序状态的函数
+function toggleEpisodeOrder() {
+ episodesReversed = !episodesReversed;
+ // 重新渲染剧集区域,使用 currentVideoTitle 作为视频标题
+ const episodesGrid = document.getElementById('episodesGrid');
+ if (episodesGrid) {
+ episodesGrid.innerHTML = renderEpisodes(currentVideoTitle);
+ }
+
+ // 更新按钮文本和箭头方向
+ const toggleBtn = document.querySelector('button[onclick="toggleEpisodeOrder()"]');
+ if (toggleBtn) {
+ toggleBtn.querySelector('span').textContent = episodesReversed ? '正序排列' : '倒序排列';
+ const arrowIcon = toggleBtn.querySelector('svg');
+ if (arrowIcon) {
+ arrowIcon.style.transform = episodesReversed ? 'rotate(180deg)' : 'rotate(0deg)';
+ }
+ }
+}
diff --git a/player.html b/player.html
index d67b2a6..2d5a2e8 100644
--- a/player.html
+++ b/player.html
@@ -5,18 +5,25 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LibreTV 播放器</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/DPlayer.min.css">
+ <script src="https://cdn.tailwindcss.com"></script>
+ <link rel="stylesheet" href="css/styles.css">
<style>
body, html {
margin: 0;
padding: 0;
width: 100%;
- height: 100vh; /* 修改:使用100vh代替100%确保iPad mini适配 */
- overflow: hidden;
- background-color: #000;
+ height: 100%;
+ background-color: #0f1622;
+ color: white;
+ }
+ .player-container {
+ width: 100%;
+ max-width: 1200px;
+ margin: 0 auto;
}
#player {
width: 100%;
- height: 100vh; /* 修改:同上 */
+ height: 60vh; /* 视频播放器高度 */
}
.loading-container {
position: absolute;
@@ -64,168 +71,551 @@
font-size: 48px;
margin-bottom: 10px;
}
+ .episode-active {
+ background-color: #3b82f6 !important;
+ border-color: #60a5fa !important;
+ }
+ .episode-grid {
+ max-height: 30vh;
+ overflow-y: auto;
+ padding: 1rem 0;
+ }
</style>
</head>
<body>
- <div id="player"></div>
- <div class="loading-container" id="loading">
- <div class="loading-spinner"></div>
- <div>正在加载视频...</div>
- </div>
- <div class="error-container" id="error">
- <div class="error-icon">⚠️</div>
- <div id="error-message">视频加载失败</div>
- <div style="margin-top: 10px; font-size: 14px; color: #aaa;">请尝试其他视频源或稍后重试</div>
- </div>
+ <header class="bg-[#111] p-4 flex justify-between items-center border-b border-[#333]">
+ <div class="flex items-center">
+ <a href="index.html" class="flex items-center">
+ <svg class="w-8 h-8 mr-2 text-[#00ccff]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"></path>
+ </svg>
+ <h1 class="text-xl font-bold gradient-text">LibreTV</h1>
+ </a>
+ </div>
+ <h2 id="videoTitle" class="text-xl font-semibold truncate flex-1 text-center"></h2>
+ <a href="index.html" class="px-4 py-2 bg-[#222] hover:bg-[#333] border border-[#333] rounded-lg transition-colors">
+ 返回首页
+ </a>
+ </header>
+
+ <main class="container mx-auto px-4 py-4">
+ <!-- 视频播放区 -->
+ <div class="player-container">
+ <div class="relative">
+ <div id="player"></div>
+ <div class="loading-container" id="loading">
+ <div class="loading-spinner"></div>
+ <div>正在加载视频...</div>
+ </div>
+ <div class="error-container" id="error">
+ <div class="error-icon">⚠️</div>
+ <div id="error-message">视频加载失败</div>
+ <div style="margin-top: 10px; font-size: 14px; color: #aaa;">请尝试其他视频源或稍后重试</div>
+ </div>
+ </div>
+ </div>
+
+ <!-- 集数导航 -->
+ <div class="player-container">
+ <div class="flex justify-between items-center my-4">
+ <button onclick="playPreviousEpisode()" id="prevButton" class="px-4 py-2 bg-[#222] hover:bg-[#333] border border-[#333] rounded-lg transition-colors">
+ <svg class="w-5 h-5 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
+ </svg>
+ 上一集
+ </button>
+ <span class="text-gray-400" id="episodeInfo">加载中...</span>
+ <button onclick="playNextEpisode()" id="nextButton" class="px-4 py-2 bg-[#222] hover:bg-[#333] border border-[#333] rounded-lg transition-colors">
+ 下一集
+ <svg class="w-5 h-5 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
+ </svg>
+ </button>
+ </div>
+ </div>
+
+ <!-- 排序和选集 -->
+ <div class="player-container">
+ <div class="mb-4 flex justify-end">
+ <button onclick="toggleEpisodeOrder()" class="px-4 py-2 bg-gradient-to-r from-indigo-500 via-purple-500 to-pink-500 text-white font-semibold rounded-full shadow-lg hover:shadow-xl transition-all duration-300 flex items-center justify-center space-x-2">
+ <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" id="orderIcon" viewBox="0 0 20 20" fill="currentColor">
+ <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-11a1 1 0 10-2 0v3.586L7.707 9.293a1 1 0 00-1.414 1.414l3 3a1 1 0 001.414 0l3-3a1 1 0 00-1.414-1.414L11 10.586V7z" clip-rule="evenodd" />
+ </svg>
+ <span id="orderText">倒序排列</span>
+ </button>
+ </div>
+ </div>
+
+ <!-- 集数网格 -->
+ <div class="player-container">
+ <div class="episode-grid" id="episodesGrid">
+ <div class="grid grid-cols-2 sm:grid-cols-4 md:grid-cols-6 lg:grid-cols-8 gap-2" id="episodesList">
+ <!-- 集数将在这里动态加载 -->
+ <div class="col-span-full text-center text-gray-400 py-8">加载中...</div>
+ </div>
+ </div>
+ </div>
+ </main>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/hls.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/DPlayer.min.js"></script>
+ <script src="js/config.js"></script>
<script>
- // 解析URL参数
- function getUrlParameter(name) {
- name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
- var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
- var results = regex.exec(location.search);
- return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
- }
+ // 全局变量
+ let currentVideoTitle = '';
+ let currentEpisodeIndex = 0;
+ let currentEpisodes = [];
+ let episodesReversed = false;
+ let dp = null;
+ let currentHls = null; // 跟踪当前HLS实例
- // 获取视频URL
- const videoUrl = getUrlParameter('url');
- if (!videoUrl) {
- document.getElementById('loading').style.display = 'none';
- document.getElementById('error').style.display = 'flex';
- document.getElementById('error-message').textContent = '无效的视频链接';
- } else {
- // 初始化自定义M3U8 Loader
- class CustomHlsJsLoader extends Hls.DefaultConfig.loader {
- constructor(config) {
- super(config);
- const load = this.load.bind(this);
- this.load = function(context, config, callbacks) {
- // 拦截manifest和level请求
- if (context.type === 'manifest' || context.type === 'level') {
- const onSuccess = callbacks.onSuccess;
- callbacks.onSuccess = function(response, stats, context) {
- // 如果是m3u8文件,处理内容以移除广告分段
- if (response.data && typeof response.data === 'string') {
- // 过滤掉广告段 - 实现更精确的广告过滤逻辑
- response.data = filterAdsFromM3U8(response.data, true);
- }
- return onSuccess(response, stats, context);
- };
- }
- // 执行原始load方法
- load(context, config, callbacks);
- };
- }
+ // 页面加载
+ document.addEventListener('DOMContentLoaded', function() {
+ // 解析URL参数
+ const urlParams = new URLSearchParams(window.location.search);
+ const videoUrl = urlParams.get('url');
+ const title = urlParams.get('title');
+ const index = parseInt(urlParams.get('index') || '0');
+
+ // 从localStorage获取数据
+ currentVideoTitle = title || localStorage.getItem('currentVideoTitle') || '未知视频';
+ currentEpisodeIndex = index;
+
+ try {
+ currentEpisodes = JSON.parse(localStorage.getItem('currentEpisodes') || '[]');
+ episodesReversed = localStorage.getItem('episodesReversed') === 'true';
+ } catch (e) {
+ console.error('获取集数信息失败:', e);
+ currentEpisodes = [];
+ episodesReversed = false;
}
- // M3U8清单广告过滤函数
- function filterAdsFromM3U8(m3u8Content, strictMode = false) {
- if (!m3u8Content) return '';
-
- // 按行分割M3U8内容
- const lines = m3u8Content.split('\n');
- const filteredLines = [];
-
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
-
- // 只过滤#EXT-X-DISCONTINUITY标识
- if (!line.includes('#EXT-X-DISCONTINUITY')) {
- filteredLines.push(line);
- }
- }
-
- return filteredLines.join('\n');
+ // 设置页面标题
+ document.title = currentVideoTitle + ' - LibreTV播放器';
+ document.getElementById('videoTitle').textContent = currentVideoTitle;
+
+ // 初始化播放器
+ if (videoUrl) {
+ initPlayer(videoUrl);
+ } else {
+ showError('无效的视频链接');
}
+ // 更新集数信息
+ updateEpisodeInfo();
+
+ // 渲染集数列表
+ renderEpisodes();
+
+ // 更新按钮状态
+ updateButtonStates();
+
+ // 更新排序按钮状态
+ updateOrderButton();
+ });
+
+ // 初始化播放器
+ function initPlayer(videoUrl) {
+ if (!videoUrl) return;
+
+ // 配置HLS.js选项
+ const hlsConfig = {
+ debug: false,
+ loader: CustomHlsJsLoader,
+ enableWorker: true,
+ lowLatencyMode: false,
+ backBufferLength: 90,
+ maxBufferLength: 30,
+ maxMaxBufferLength: 60,
+ maxBufferSize: 30 * 1000 * 1000,
+ maxBufferHole: 0.5,
+ fragLoadingMaxRetry: 6,
+ fragLoadingMaxRetryTimeout: 64000,
+ fragLoadingRetryDelay: 1000,
+ manifestLoadingMaxRetry: 3,
+ manifestLoadingRetryDelay: 1000,
+ levelLoadingMaxRetry: 4,
+ levelLoadingRetryDelay: 1000,
+ startLevel: -1,
+ abrEwmaDefaultEstimate: 500000,
+ abrBandWidthFactor: 0.95,
+ abrBandWidthUpFactor: 0.7,
+ abrMaxWithRealBitrate: true,
+ stretchShortVideoTrack: true,
+ appendErrorMaxRetry: 5, // 增加尝试次数
+ liveSyncDurationCount: 3,
+ liveDurationInfinity: false
+ };
+
// 创建DPlayer实例
- document.addEventListener('DOMContentLoaded', function() {
- // 配置HLS.js选项
- const hlsConfig = {
- debug: false,
- // 使用自定义的loader以过滤广告
- loader: CustomHlsJsLoader,
- enableWorker: true,
- lowLatencyMode: false,
- backBufferLength: 90,
- maxBufferLength: 30,
- maxMaxBufferLength: 60,
- maxBufferSize: 30 * 1000 * 1000,
- maxBufferHole: 0.5,
- fragLoadingMaxRetry: 6,
- fragLoadingMaxRetryTimeout: 64000,
- fragLoadingRetryDelay: 1000,
- manifestLoadingMaxRetry: 3,
- manifestLoadingRetryDelay: 1000,
- levelLoadingMaxRetry: 4,
- levelLoadingRetryDelay: 1000,
- startLevel: -1,
- abrEwmaDefaultEstimate: 500000,
- abrBandWidthFactor: 0.95,
- abrBandWidthUpFactor: 0.7,
- abrMaxWithRealBitrate: true,
- stretchShortVideoTrack: true
- };
-
- const dp = new DPlayer({
- container: document.getElementById('player'),
- autoplay: true,
- theme: '#00ccff',
- preload: 'auto',
- loop: false,
- lang: 'zh-cn',
- hotkey: true,
- mutex: true,
- volume: 0.7,
- video: {
- url: videoUrl,
- type: 'hls',
- pic: '',
- customType: {
- hls: function(video, player) {
- const hls = new Hls(hlsConfig);
- hls.loadSource(video.src);
- hls.attachMedia(video);
- hls.on(Hls.Events.MANIFEST_PARSED, function() {
- video.play();
+ dp = new DPlayer({
+ container: document.getElementById('player'),
+ autoplay: true,
+ theme: '#00ccff',
+ preload: 'auto',
+ loop: false,
+ lang: 'zh-cn',
+ hotkey: true,
+ mutex: true,
+ volume: 0.7,
+ video: {
+ url: videoUrl,
+ type: 'hls',
+ pic: '',
+ customType: {
+ hls: function(video, player) {
+ // 清理之前的HLS实例
+ if (currentHls && currentHls.destroy) {
+ try {
+ currentHls.destroy();
+ } catch (e) {
+ console.warn('销毁旧HLS实例出错:', e);
+ }
+ }
+
+ // 创建新的HLS实例
+ const hls = new Hls(hlsConfig);
+ currentHls = hls;
+
+ // 跟踪是否已经显示错误
+ let errorDisplayed = false;
+ // 跟踪是否有错误发生
+ let errorCount = 0;
+ // 跟踪视频是否开始播放
+ let playbackStarted = false;
+ // 跟踪视频是否出现bufferAppendError
+ let bufferAppendErrorCount = 0;
+
+ // 监听视频播放事件
+ video.addEventListener('playing', function() {
+ playbackStarted = true;
+ document.getElementById('loading').style.display = 'none';
+ document.getElementById('error').style.display = 'none';
+ });
+
+ // 监听视频进度事件
+ video.addEventListener('timeupdate', function() {
+ if (video.currentTime > 1) {
+ // 视频进度超过1秒,隐藏错误(如果存在)
+ document.getElementById('error').style.display = 'none';
+ }
+ });
+
+ hls.loadSource(video.src);
+ hls.attachMedia(video);
+
+ hls.on(Hls.Events.MANIFEST_PARSED, function() {
+ video.play().catch(e => {
+ console.warn('自动播放被阻止:', e);
});
- hls.on(Hls.Events.ERROR, function(event, data) {
- if (data.fatal) {
- console.error('HLS错误:', data);
- showError('视频加载失败,可能是格式不兼容或源不可用');
+ });
+
+ hls.on(Hls.Events.ERROR, function(event, data) {
+ console.log('HLS事件:', event, '数据:', data);
+
+ // 增加错误计数
+ errorCount++;
+
+ // 处理bufferAppendError
+ if (data.details === 'bufferAppendError') {
+ bufferAppendErrorCount++;
+ console.warn(`bufferAppendError 发生 ${bufferAppendErrorCount} 次`);
+
+ // 如果视频已经开始播放,则忽略这个错误
+ if (playbackStarted) {
+ console.log('视频已在播放中,忽略bufferAppendError');
+ return;
}
- });
- // 监听加载完成事件
- hls.on(Hls.Events.LEVEL_LOADED, function() {
- document.getElementById('loading').style.display = 'none';
- });
- }
+
+ // 如果出现多次bufferAppendError但视频未播放,尝试恢复
+ if (bufferAppendErrorCount >= 3) {
+ hls.recoverMediaError();
+ }
+ }
+
+ // 如果是致命错误,且视频未播放
+ if (data.fatal && !playbackStarted) {
+ console.error('致命HLS错误:', data);
+
+ // 尝试恢复错误
+ switch(data.type) {
+ case Hls.ErrorTypes.NETWORK_ERROR:
+ console.log("尝试恢复网络错误");
+ hls.startLoad();
+ break;
+ case Hls.ErrorTypes.MEDIA_ERROR:
+ console.log("尝试恢复媒体错误");
+ hls.recoverMediaError();
+ break;
+ default:
+ // 仅在多次恢复尝试后显示错误
+ if (errorCount > 3 && !errorDisplayed) {
+ errorDisplayed = true;
+ showError('视频加载失败,可能是格式不兼容或源不可用');
+ }
+ break;
+ }
+ }
+ });
+
+ // 监听分段加载事件
+ hls.on(Hls.Events.FRAG_LOADED, function() {
+ document.getElementById('loading').style.display = 'none';
+ });
+
+ // 监听级别加载事件
+ hls.on(Hls.Events.LEVEL_LOADED, function() {
+ document.getElementById('loading').style.display = 'none';
+ });
}
}
- });
+ }
+ });
- dp.on('loadedmetadata', function() {
- document.getElementById('loading').style.display = 'none';
- });
+ dp.on('loadedmetadata', function() {
+ document.getElementById('loading').style.display = 'none';
+ });
- dp.on('error', function() {
- showError('视频播放失败,请检查视频源或网络连接');
- });
+ dp.on('error', function() {
+ // 检查视频是否已经在播放
+ if (dp.video && dp.video.currentTime > 1) {
+ console.log('发生错误,但视频已在播放中,忽略');
+ return;
+ }
+ showError('视频播放失败,请检查视频源或网络连接');
+ });
+
+ // 10秒后如果仍在加载,但不立即显示错误
+ setTimeout(function() {
+ // 如果视频已经播放开始,则不显示错误
+ if (dp && dp.video && dp.video.currentTime > 0) {
+ return;
+ }
- // 10秒后如果仍在加载,显示超时错误
- setTimeout(function() {
- if (document.getElementById('loading').style.display !== 'none') {
- showError('视频加载超时,请检查网络连接或尝试其他视频源');
+ if (document.getElementById('loading').style.display !== 'none') {
+ document.getElementById('loading').innerHTML = `
+ <div class="loading-spinner"></div>
+ <div>视频加载时间较长,请耐心等待...</div>
+ <div style="font-size: 12px; color: #aaa; margin-top: 10px;">如长时间无响应,请尝试其他视频源</div>
+ `;
+ }
+ }, 10000);
+ }
+
+ // 自定义M3U8 Loader用于过滤广告
+ class CustomHlsJsLoader extends Hls.DefaultConfig.loader {
+ constructor(config) {
+ super(config);
+ const load = this.load.bind(this);
+ this.load = function(context, config, callbacks) {
+ // 拦截manifest和level请求
+ if (context.type === 'manifest' || context.type === 'level') {
+ const onSuccess = callbacks.onSuccess;
+ callbacks.onSuccess = function(response, stats, context) {
+ // 如果是m3u8文件,处理内容以移除广告分段
+ if (response.data && typeof response.data === 'string') {
+ // 过滤掉广告段 - 实现更精确的广告过滤逻辑
+ response.data = filterAdsFromM3U8(response.data, true);
+ }
+ return onSuccess(response, stats, context);
+ };
}
- }, 10000);
+ // 执行原始load方法
+ load(context, config, callbacks);
+ };
+ }
+ }
+
+ // M3U8清单广告过滤函数
+ function filterAdsFromM3U8(m3u8Content, strictMode = false) {
+ if (!m3u8Content) return '';
+
+ // 按行分割M3U8内容
+ const lines = m3u8Content.split('\n');
+ const filteredLines = [];
+
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+
+ // 只过滤#EXT-X-DISCONTINUITY标识
+ if (!line.includes('#EXT-X-DISCONTINUITY')) {
+ filteredLines.push(line);
+ }
+ }
+
+ return filteredLines.join('\n');
+ }
+
+ // 显示错误
+ function showError(message) {
+ // 在视频已经播放的情况下不显示错误
+ if (dp && dp.video && dp.video.currentTime > 1) {
+ console.log('忽略错误:', message);
+ return;
+ }
+
+ document.getElementById('loading').style.display = 'none';
+ document.getElementById('error').style.display = 'flex';
+ document.getElementById('error-message').textContent = message;
+ }
+
+ // 更新集数信息
+ function updateEpisodeInfo() {
+ if (currentEpisodes.length > 0) {
+ document.getElementById('episodeInfo').textContent = `第 ${currentEpisodeIndex + 1}/${currentEpisodes.length} 集`;
+ } else {
+ document.getElementById('episodeInfo').textContent = '无集数信息';
+ }
+ }
+
+ // 更新按钮状态
+ function updateButtonStates() {
+ const prevButton = document.getElementById('prevButton');
+ const nextButton = document.getElementById('nextButton');
+
+ // 处理上一集按钮
+ if (currentEpisodeIndex > 0) {
+ prevButton.classList.remove('bg-gray-700', 'cursor-not-allowed');
+ prevButton.classList.add('bg-[#222]', 'hover:bg-[#333]');
+ prevButton.removeAttribute('disabled');
+ } else {
+ prevButton.classList.add('bg-gray-700', 'cursor-not-allowed');
+ prevButton.classList.remove('bg-[#222]', 'hover:bg-[#333]');
+ prevButton.setAttribute('disabled', '');
+ }
+
+ // 处理下一集按钮
+ if (currentEpisodeIndex < currentEpisodes.length - 1) {
+ nextButton.classList.remove('bg-gray-700', 'cursor-not-allowed');
+ nextButton.classList.add('bg-[#222]', 'hover:bg-[#333]');
+ nextButton.removeAttribute('disabled');
+ } else {
+ nextButton.classList.add('bg-gray-700', 'cursor-not-allowed');
+ nextButton.classList.remove('bg-[#222]', 'hover:bg-[#333]');
+ nextButton.setAttribute('disabled', '');
+ }
+ }
+
+ // 渲染集数按钮
+ function renderEpisodes() {
+ const episodesList = document.getElementById('episodesList');
+ if (!episodesList) return;
+
+ if (!currentEpisodes || currentEpisodes.length === 0) {
+ episodesList.innerHTML = '<div class="col-span-full text-center text-gray-400 py-8">没有可用的集数</div>';
+ return;
+ }
+
+ const episodes = episodesReversed ? [...currentEpisodes].reverse() : currentEpisodes;
+ let html = '';
+
+ episodes.forEach((episode, index) => {
+ // 根据倒序状态计算真实的剧集索引
+ const realIndex = episodesReversed ? currentEpisodes.length - 1 - index : index;
+ const isActive = realIndex === currentEpisodeIndex;
+
+ html += `
+ <button id="episode-${realIndex}"
+ onclick="playEpisode(${realIndex})"
+ class="px-4 py-2 ${isActive ? 'episode-active' : 'bg-[#222] hover:bg-[#333]'} border ${isActive ? 'border-blue-500' : 'border-[#333]'} rounded-lg transition-colors text-center episode-btn">
+ 第${realIndex + 1}集
+ </button>
+ `;
});
+
+ episodesList.innerHTML = html;
+ }
- function showError(message) {
- document.getElementById('loading').style.display = 'none';
- document.getElementById('error').style.display = 'flex';
- document.getElementById('error-message').textContent = message;
+ // 播放指定集数
+ function playEpisode(index) {
+ if (index < 0 || index >= currentEpisodes.length) return;
+
+ // 首先隐藏之前可能显示的错误
+ document.getElementById('error').style.display = 'none';
+ // 显示加载指示器
+ document.getElementById('loading').style.display = 'flex';
+ document.getElementById('loading').innerHTML = `
+ <div class="loading-spinner"></div>
+ <div>正在加载视频...</div>
+ `;
+
+ const url = currentEpisodes[index];
+ currentEpisodeIndex = index;
+
+ // 更新URL,不刷新页面
+ const newUrl = new URL(window.location.href);
+ newUrl.searchParams.set('index', index);
+ newUrl.searchParams.set('url', url);
+ window.history.pushState({}, '', newUrl);
+
+ // 更新播放器
+ if (dp) {
+ try {
+ dp.switchVideo({
+ url: url,
+ type: 'hls'
+ });
+
+ // 确保播放开始
+ const playPromise = dp.play();
+ if (playPromise !== undefined) {
+ playPromise.catch(error => {
+ console.warn('播放失败,尝试重新初始化:', error);
+ // 如果切换视频失败,重新初始化播放器
+ initPlayer(url);
+ });
+ }
+ } catch (e) {
+ console.error('切换视频出错,尝试重新初始化:', e);
+ // 如果出错,重新初始化播放器
+ initPlayer(url);
+ }
+ } else {
+ initPlayer(url);
+ }
+
+ // 更新UI
+ updateEpisodeInfo();
+ updateButtonStates();
+ renderEpisodes();
+ }
+
+ // 播放上一集
+ function playPreviousEpisode() {
+ if (currentEpisodeIndex > 0) {
+ playEpisode(currentEpisodeIndex - 1);
+ }
+ }
+
+ // 播放下一集
+ function playNextEpisode() {
+ if (currentEpisodeIndex < currentEpisodes.length - 1) {
+ playEpisode(currentEpisodeIndex + 1);
+ }
+ }
+
+ // 切换集数排序
+ function toggleEpisodeOrder() {
+ episodesReversed = !episodesReversed;
+
+ // 保存到localStorage
+ localStorage.setItem('episodesReversed', episodesReversed);
+
+ // 重新渲染集数列表
+ renderEpisodes();
+
+ // 更新排序按钮
+ updateOrderButton();
+ }
+
+ // 更新排序按钮状态
+ function updateOrderButton() {
+ const orderText = document.getElementById('orderText');
+ const orderIcon = document.getElementById('orderIcon');
+
+ if (orderText && orderIcon) {
+ orderText.textContent = episodesReversed ? '正序排列' : '倒序排列';
+ orderIcon.style.transform = episodesReversed ? 'rotate(180deg)' : '';
}
}
</script>
diff --git a/watch.html b/watch.html
new file mode 100644
index 0000000..a96c091
--- /dev/null
+++ b/watch.html
@@ -0,0 +1,11 @@
+<!DOCTYPE html>
+<html lang="zh">
+<head>
+ <meta charset="UTF-8">
+ <meta http-equiv="refresh" content="0; url=player.html">
+ <title>重定向到播放器</title>
+</head>
+<body>
+ <p>如果您没有被自动重定向,请<a href="player.html">点击这里</a>前往播放页面。</p>
+</body>
+</html>