Добавлена поддержка потоковой передачи видео с сервера и синхронизация текущего времени воспроизведения
This commit is contained in:
1 parent
d931cd50da
commit
0b6b6e23da
3 files changed
+71
-16
No files matched your search
+1
-1
@@ -29,7 +29,7 @@
|
||||
|
||||
<div class="video-container">
|
||||
<div class="video-frame">
|
||||
<video id="video" src="https://www.w3schools.com/html/mov_bbb.mp4">
|
||||
<video id="video" src="/video" controls>
|
||||
Your browser does not support the video tag.
|
||||
</video>
|
||||
|
||||
|
||||
@@ -1,19 +1,48 @@
|
||||
const express = require('express');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const app = express();
|
||||
const PORT = 3000;
|
||||
|
||||
// Middleware для обслуживания статических файлов из папки "src" и корня приложения
|
||||
app.use('/src', express.static(path.join(__dirname, 'src')));
|
||||
// Путь к видеофайлу
|
||||
const videoPath = path.join(__dirname, 'movie.mp4'); // Замените 'movie.mp4' на ваш фильм
|
||||
const serverStartTime = Date.now(); // Время запуска сервера
|
||||
|
||||
// Маршрут для главной страницы
|
||||
app.use('/', express.static(path.join(__dirname, '')));
|
||||
|
||||
// Главная страница
|
||||
app.get('/', (req, res) => {
|
||||
res.sendFile(path.join(__dirname, 'index.html'));
|
||||
// Маршрут для видео
|
||||
app.get('/video', (req, res) => {
|
||||
const range = req.headers.range;
|
||||
if (!range) {
|
||||
return res.status(400).send('Requires Range header');
|
||||
}
|
||||
|
||||
const videoSize = fs.statSync(videoPath).size;
|
||||
const CHUNK_SIZE = 10 ** 6; // 1MB
|
||||
const start = Number(range.replace(/\D/g, ''));
|
||||
const end = Math.min(start + CHUNK_SIZE, videoSize - 1);
|
||||
|
||||
const videoStream = fs.createReadStream(videoPath, { start, end });
|
||||
|
||||
res.writeHead(206, {
|
||||
'Content-Range': `bytes ${start}-${end}/${videoSize}`,
|
||||
'Accept-Ranges': 'bytes',
|
||||
'Content-Length': end - start + 1,
|
||||
'Content-Type': 'video/mp4',
|
||||
});
|
||||
|
||||
videoStream.pipe(res);
|
||||
});
|
||||
|
||||
// API для получения текущего времени воспроизведения
|
||||
app.get('/current-time', (req, res) => {
|
||||
const elapsedTime = (Date.now() - serverStartTime) / 1000; // Время с момента запуска сервера в секундах
|
||||
res.json({ currentTime: elapsedTime });
|
||||
});
|
||||
|
||||
// Запуск сервера
|
||||
app.listen(PORT, '0.0.0.0', () => {
|
||||
console.log(`Server is running on http://0.0.0.0:${PORT}`);
|
||||
console.log(`Server is running on http://localhost:${PORT}`);
|
||||
});
|
||||
+35
-9
@@ -1,4 +1,4 @@
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
document.addEventListener('DOMContentLoaded', async () => {
|
||||
const video = document.getElementById('video');
|
||||
const playPauseBtn = document.getElementById('playPauseBtn');
|
||||
const muteBtn = document.getElementById('muteBtn');
|
||||
@@ -7,6 +7,33 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
const volumeSlider = document.querySelector('.volume-slider');
|
||||
const videoContainer = document.querySelector('.video-frame');
|
||||
|
||||
// Получение текущего времени воспроизведения с сервера
|
||||
async function fetchCurrentTime() {
|
||||
try {
|
||||
const response = await fetch('/current-time');
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch current time');
|
||||
}
|
||||
const data = await response.json();
|
||||
return data.currentTime; // Сервер возвращает время в секундах
|
||||
} catch (error) {
|
||||
console.error('Error fetching current time:', error);
|
||||
return 0; // Если ошибка, начать воспроизведение с начала
|
||||
}
|
||||
}
|
||||
|
||||
// Синхронизация времени видео с сервером
|
||||
async function syncVideo() {
|
||||
const currentTime = await fetchCurrentTime(); // Получаем время от сервера
|
||||
video.currentTime = currentTime; // Устанавливаем текущее время видео
|
||||
}
|
||||
|
||||
// Событие, когда метаданные видео загружены
|
||||
video.addEventListener('loadedmetadata', async () => {
|
||||
await syncVideo(); // Синхронизация видео с сервера
|
||||
video.play(); // Запускаем видео
|
||||
});
|
||||
|
||||
// Play/Pause
|
||||
function togglePlay() {
|
||||
if (video.paused) {
|
||||
@@ -18,18 +45,18 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
}
|
||||
}
|
||||
|
||||
// Update progress bar
|
||||
// Обновление прогресса
|
||||
function updateProgress() {
|
||||
const progress = (video.currentTime / video.duration) * 100;
|
||||
progressBar.value = progress;
|
||||
}
|
||||
|
||||
// Set video time based on progress bar
|
||||
// Установка времени видео через прогресс-бар
|
||||
function setVideoProgress() {
|
||||
video.currentTime = (progressBar.value * video.duration) / 100;
|
||||
}
|
||||
|
||||
// Volume controls
|
||||
// Громкость
|
||||
function updateVolume() {
|
||||
video.volume = volumeSlider.value;
|
||||
updateVolumeIcon();
|
||||
@@ -62,7 +89,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
}
|
||||
}
|
||||
|
||||
// Event listeners
|
||||
// Слушатели событий
|
||||
playPauseBtn.addEventListener('click', togglePlay);
|
||||
video.addEventListener('click', togglePlay);
|
||||
video.addEventListener('timeupdate', updateProgress);
|
||||
@@ -71,7 +98,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
volumeSlider.addEventListener('input', updateVolume);
|
||||
fullscreenBtn.addEventListener('click', toggleFullscreen);
|
||||
|
||||
// Keyboard controls
|
||||
// Поддержка клавиш на клавиатуре
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (e.code === 'Space') {
|
||||
e.preventDefault();
|
||||
@@ -79,6 +106,5 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
}
|
||||
});
|
||||
|
||||
// Log ready state
|
||||
console.log('Video player initialized');
|
||||
});
|
||||
console.log('Video player initialized and synced with the server.');
|
||||
});
|
||||
Reference in new issue
Block a user