
Recherche avancée
Autres articles (56)
-
Websites made with MediaSPIP
2 mai 2011, parThis page lists some websites based on MediaSPIP.
-
Creating farms of unique websites
13 avril 2011, parMediaSPIP platforms can be installed as a farm, with a single "core" hosted on a dedicated server and used by multiple websites.
This allows (among other things) : implementation costs to be shared between several different projects / individuals rapid deployment of multiple unique sites creation of groups of like-minded sites, making it possible to browse media in a more controlled and selective environment than the major "open" (...) -
Support audio et vidéo HTML5
10 avril 2011MediaSPIP utilise les balises HTML5 video et audio pour la lecture de documents multimedia en profitant des dernières innovations du W3C supportées par les navigateurs modernes.
Pour les navigateurs plus anciens, le lecteur flash Flowplayer est utilisé.
Le lecteur HTML5 utilisé a été spécifiquement créé pour MediaSPIP : il est complètement modifiable graphiquement pour correspondre à un thème choisi.
Ces technologies permettent de distribuer vidéo et son à la fois sur des ordinateurs conventionnels (...)
Sur d’autres sites (8696)
-
Error initializing FFmpegKit : "TypeError : Cannot read property 'getLogLevel' of null" in React Native
9 janvier, par Md Monirozzaman khanI'm developing a React Native application where I need to process videos using the ffmpeg-kit-react-native library. However, I'm encountering an issue during the initialization of FFmpegKitConfig. The error message is :


ERROR Error initializing FFmpegKit: [TypeError: Cannot read property 'getLogLevel' of null]



Here is my App.js code




import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, TouchableOpacity, Alert, Dimensions, ScrollView, LayoutAnimation, UIManager, Platform } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import * as FileSystem from 'expo-file-system';
import { Video } from 'expo-av';
import { MaterialIcons } from '@expo/vector-icons';
import { FFmpegKit, FFmpegKitConfig, ReturnCode } from 'ffmpeg-kit-react-native';

const windowWidth = Dimensions.get('window').width;

if (Platform.OS === 'android') {
 UIManager.setLayoutAnimationEnabledExperimental && UIManager.setLayoutAnimationEnabledExperimental(true);
}

export default function App() {
 const [videoFiles, setVideoFiles] = useState([]);
 const [isGridView, setIsGridView] = useState(false);
 const [isConverting, setIsConverting] = useState(false);

 useEffect(() => {
 FFmpegKitConfig.init()
 .then(() => {
 console.log('FFmpegKit initialized');
 })
 .catch((error) => {
 console.error('Error initializing FFmpegKit:', error);
 });
 }, []);

 const pickVideo = async () => {
 const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
 if (status !== 'granted') {
 alert('Sorry, we need media library permissions to make this work!');
 return;
 }

 let result = await ImagePicker.launchImageLibraryAsync({
 mediaTypes: ImagePicker.MediaTypeOptions.Videos,
 allowsMultipleSelection: true,
 });

 if (!result.canceled && result.assets.length > 0) {
 const newFiles = result.assets.filter(
 (newFile) => !videoFiles.some((existingFile) => existingFile.uri === newFile.uri)
 );

 if (newFiles.length < result.assets.length) {
 Alert.alert('Duplicate Files', 'Some files were already added.');
 }

 LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
 setVideoFiles([...videoFiles, ...newFiles]);
 }
 };

 const convertVideos = async () => {
 setIsConverting(true);
 const outputDir = `${FileSystem.documentDirectory}Output`;

 const dirInfo = await FileSystem.getInfoAsync(outputDir);
 if (!dirInfo.exists) {
 await FileSystem.makeDirectoryAsync(outputDir, { intermediates: true });
 }

 for (const video of videoFiles) {
 const { uri } = video;
 const filename = uri.split('/').pop();
 const outputFilePath = `${outputDir}/${filename.split('.').slice(0, -1).join('.')}_modified.mp4`;

 const ffmpegCommand = `-y -i "${uri}" -af "atempo=1.02, bass=g=4:f=80:w=3, treble=g=4:f=3200:w=3, firequalizer=gain_entry='entry(0,0);entry(62,2);entry(125,1.5);entry(250,1);entry(500,1);entry(1000,1);entry(2000,1.5);entry(4000,2.5);entry(8000,3);entry(16000,4)', compand=attacks=0.05:decays=0.25:points=-80/-80-50/-15-30/-10-10/-2:soft-knee=4:gain=2, deesser, highpass=f=35, lowpass=f=17000, loudnorm=I=-16:LRA=11:TP=-1.5, volume=3.9dB" -c:v copy -c:a aac -b:a 224k -ar 48000 -threads 0 "${outputFilePath}"`;

 try {
 const session = await FFmpegKit.execute(ffmpegCommand);
 const returnCode = await session.getReturnCode();

 if (ReturnCode.isSuccess(returnCode)) {
 console.log(`Video converted: ${outputFilePath}`);
 } else if (ReturnCode.isCancel(returnCode)) {
 console.log('Conversion cancelled');
 } else {
 console.error(`FFmpeg process failed: ${session.getFailStackTrace()}`);
 }
 } catch (error) {
 console.error(`Error converting video: ${error.message}`);
 }
 }

 setIsConverting(false);
 Alert.alert('Conversion Complete', 'All videos have been converted.');
 };

 const deleteVideo = (uri) => {
 LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
 setVideoFiles(videoFiles.filter((video) => video.uri !== uri));
 };

 const clearAllVideos = () => {
 LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
 setVideoFiles([]);
 };

 const toggleLayout = () => {
 LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
 setIsGridView(!isGridView);
 };

 return (
 <view style="{styles.container}">
 <text style="{styles.header}">Video Converter App</text>
 <touchableopacity style="{styles.addButton}">
 <text style="{styles.addButtonText}">Select or Browse Videos</text>
 </touchableopacity>
 <view style="{styles.headerContainer}">
 <text style="{styles.videoCount}">Total Videos: {videoFiles.length}</text>
 {videoFiles.length > 0 && (
 <>
 <touchableopacity style="{styles.clearButtonContainer}">
 <materialicons size="{24}" color="red" style="{styles.clearIcon}"></materialicons>
 <text style="{styles.clearAllText}">Clear All</text>
 </touchableopacity>
 <touchableopacity style="{styles.toggleLayoutButton}">
 <materialicons size="{24}" color="#fff"></materialicons>
 </touchableopacity>
 >
 )}
 </view>
 {isGridView ? (
 <scrollview contentcontainerstyle="{styles.gridContainer}">
 {videoFiles.map((item, index) => (
 <view key="{index}" style="{styles.videoItemGrid}">
 
 <touchableopacity>> deleteVideo(item.uri)} style={styles.deleteButtonGrid}>
 <materialicons size="{24}" color="red"></materialicons>
 </touchableopacity>
 </view>
 ))}
 </scrollview>
 ) : (
 <view style="{styles.list}">
 {videoFiles.map((item, index) => (
 <view key="{index}" style="{styles.videoItem}">
 
 <text style="{styles.fileName}">{decodeURI(item.fileName || item.uri.split('/').pop() || 'Unknown File')}</text>
 <touchableopacity>> deleteVideo(item.uri)} style={styles.deleteButton}>
 <materialicons size="{24}" color="red"></materialicons>
 </touchableopacity>
 </view>
 ))}
 </view>
 )}
 {videoFiles.length > 0 && (
 <touchableopacity style="{styles.convertButton}" disabled="{isConverting}">
 <text style="{styles.convertButtonText}">{isConverting ? 'Converting...' : 'Convert'}</text>
 </touchableopacity>
 )}
 </view>
 );
}

const styles = StyleSheet.create({
 container: {
 flex: 1,
 backgroundColor: '#fff',
 alignItems: 'center',
 padding: 10,
 },
 header: {
 fontSize: 24,
 fontWeight: 'bold',
 marginBottom: 5,
 },
 addButton: {
 backgroundColor: '#007BFF',
 padding: 15,
 borderRadius: 10,
 alignItems: 'center',
 marginBottom: 5,
 width: '100%',
 elevation: 2,
 shadowColor: '#000',
 shadowOffset: { width: 0, height: 5 },
 shadowOpacity: 0.8,
 shadowRadius: 2,
 },
 addButtonText: {
 color: '#fff',
 fontSize: 18,
 fontWeight: 'bold',
 },
 headerContainer: {
 flexDirection: 'row',
 alignItems: 'center',
 justifyContent: 'space-between',
 width: '100%',
 marginBottom: 10,
 },
 videoCount: {
 fontSize: 18,
 },
 clearButtonContainer: {
 flexDirection: 'row',
 alignItems: 'center',
 marginRight: 10,
 },
 clearIcon: {
 marginRight: 5,
 },
 clearAllText: {
 fontSize: 16,
 color: 'red',
 textDecorationLine: 'underline',
 },
 toggleLayoutButton: {
 backgroundColor: '#007BFF',
 padding: 1,
 borderRadius: 8,
 alignItems: 'center',
 justifyContent: 'center',
 },
 list: {
 flex: 1,
 width: '100%',
 },
 videoItem: {
 padding: 5,
 borderBottomColor: '#ccc',
 borderBottomWidth: 0.7,
 flexDirection: 'row',
 alignItems: 'center',
 },
 videoItemGrid: {
 flexDirection: 'column',
 alignItems: 'center',
 margin: 4,
 borderWidth: 1,
 borderColor: '#ccc',
 borderRadius: 8,
 padding: 2,
 position: 'relative',
 },
 thumbnail: {
 width: 70,
 height: 70,
 marginRight: 10,
 },
 thumbnailGrid: {
 width: 80,
 height: 80,
 marginBottom: 0,
 },
 fileName: {
 fontSize: 16,
 marginLeft: 10,
 flex: 1,
 },
 deleteButton: {
 marginLeft: 60,
 width: 20,
 height: 20,
 },
 deleteButtonGrid: {
 position: 'absolute',
 bottom: 5,
 right: 5,
 },
 convertButton: {
 backgroundColor: '#007BFF',
 padding: 15,
 borderRadius: 10,
 alignItems: 'center',
 marginTop: 20,
 width: '100%',
 },
 convertButtonText: {
 color: '#fff',
 fontSize: 18,
 fontWeight: 'bold',
 },
 gridContainer: {
 flexDirection: 'row',
 flexWrap: 'wrap',
 justifyContent: 'flex-start',
 paddingVertical: 5,
 paddingHorizontal: 5,
 width: '100%',
 },
});







App.json




{
 "expo": {
 "name": "VidoeConvert",
 "slug": "VidoeConvert",
 "version": "1.0.0",
 "orientation": "portrait",
 "icon": "./assets/icon.png",
 "userInterfaceStyle": "light",
 "splash": {
 "image": "./assets/splash.png",
 "resizeMode": "contain",
 "backgroundColor": "#ffffff"
 },
 "ios": {
 "supportsTablet": true
 },
 "android": {
 "adaptiveIcon": {
 "foregroundImage": "./assets/adaptive-icon.png",
 "backgroundColor": "#ffffff"
 },
 "package": "com.anonymous.VidoeConvert"
 },
 "web": {
 "favicon": "./assets/favicon.png"
 },
 "plugins": [
 "@config-plugins/ffmpeg-kit-react-native",
 "expo-build-properties"
 ]
 }
}







Package.json




{
 "name": "vidoeconvert",
 "version": "1.0.0",
 "main": "expo/AppEntry.js",
 "scripts": {
 "start": "expo start",
 "android": "expo run:android",
 "ios": "expo run:ios",
 "web": "expo start --web"
 },
 "dependencies": {
 "@config-plugins/ffmpeg-kit-react-native": "^8.0.0",
 "@expo/metro-runtime": "~3.2.1",
 "expo": "~51.0.17",
 "expo-asset": "~10.0.10",
 "expo-av": "^14.0.6",
 "expo-document-picker": "~12.0.2",
 "expo-file-system": "~17.0.1",
 "expo-image-picker": "~15.0.7",
 "expo-media-library": "~16.0.4",
 "expo-status-bar": "~1.12.1",
 "ffmpeg-kit-react-native": "^6.0.2",
 "react": "18.2.0",
 "react-dom": "18.2.0",
 "react-native": "^0.74.3",
 "react-native-document-picker": "^9.3.0",
 "react-native-ffmpeg": "^0.5.2",
 "react-native-vector-icons": "^10.1.0",
 "react-native-web": "~0.19.10",
 "expo-build-properties": "~0.12.3"
 },
 "devDependencies": {
 "@babel/core": "^7.20.0"
 },
 "private": true
}







Has anyone encountered a similar issue or can point me in the right direction to resolve this error ? Any help would be greatly appreciated !


How to remove the error ?


any configruation required for this project ?


-
How to Record Video of a Dynamic Div Containing Multiple Media Elements in React Konva ?
14 septembre 2024, par Humayoun SaeedI'm working on a React application where I need to record a video of a specific div with the class name "layout." This div contains multiple media elements (such as images and videos) that are dynamically rendered inside divisions. I've tried several approaches, including using MediaRecorder, canvas-based recording with html2canvas, RecordRTC, and even ffmpeg, but none seem to capture the entire div along with its dynamic content effectively.


What would be the best approach to achieve this ? How can I record a video of this dynamically rendered div including all its media elements, ensuring a smooth capture of the transitions ?


What I’ve Tried :
MediaRecorder API : Didn't work effectively for capturing the entire div and its elements.
html2canvas : Captures snapshots but struggles with smooth transitions between media elements.
RecordRTC HTML Element Recording : Attempts to capture the canvas, but the output video size is 0 bytes.
CanvasRecorder, FFmpeg, and various other libraries also didn't provide the desired result.


import React, { useEffect, useState, useRef } from "react";

const Preview = ({ layout, onClose }) => {
 const [currentContent, setCurrentContent] = useState([]);
 const totalDuration = useRef(0);
 const videoRefs = useRef([]); // Store refs to each video element
 const [totalTime, setTotalTime] = useState(0); // Add this line
 const [elapsedTime, setElapsedTime] = useState(0); // Track elapsed time in seconds

 // video recording variable and state declaration
 // video recorder end
 // for video record useffect
 // Function to capture the renderDivision content

 const handleDownload = async () => {
 console.log("video downlaod function in developing mode.");
 };

 // end video record useffect

 // to apply motion and swtich in media of division start
 useEffect(() => {
 if (layout && layout.divisions) {
 const content = layout.divisions.map((division) => {
 let divisionDuration = 0;

 division.imageSrcs.forEach((src, index) => {
 const mediaDuration = division.durations[index]
 ? division.durations[index] * 1000 // Convert to milliseconds
 : 5000; // Fallback to 5 seconds if duration is missing
 divisionDuration += mediaDuration;
 });

 return {
 division,
 contentIndex: 0,
 divisionDuration,
 };
 });

 // Find the maximum duration
 const maxDuration = Math.max(...content.map((c) => c.divisionDuration));

 // Filter divisions that have the max duration
 const maxDurationDivisions = content.filter(
 (c) => c.divisionDuration === maxDuration
 );

 // Select the first one if there are multiple with the same max duration
 const selectedMaxDurationDivision = maxDurationDivisions[0];

 totalDuration.current = selectedMaxDurationDivision.divisionDuration; // Update the total duration in milliseconds

 setTotalTime(Math.floor(totalDuration.current / 1000000)); // Convert to seconds and set in state

 // console.log(
 // "Division with max duration (including ties):",
 // selectedMaxDurationDivision
 // );

 setCurrentContent(content);
 }
 }, [layout]);

 useEffect(() => {
 if (currentContent.length > 0) {
 const timers = currentContent.map(({ division, contentIndex }, i) => {
 const duration = division.durations[contentIndex]
 ? division.durations[contentIndex] // Duration is already in ms
 : 5000; // Default to 5000ms if no duration is defined

 const mediaElement = videoRefs.current[i];
 if (mediaElement && mediaElement.pause) {
 mediaElement.pause();
 }

 // Set up a timeout for each division to move to the next media after duration
 const timeoutId = setTimeout(() => {
 // Update content for each division independently
 updateContent(i, division, contentIndex, duration); // Move to the next content after duration

 // Ensure proper cleanup
 if (contentIndex + 1 >= division.imageSrcs.length) {
 clearTimeout(timeoutId); // Clear timeout to stop looping
 }
 }, duration);

 // Cleanup timers on component unmount
 return timeoutId;
 });

 // Return cleanup function to clear all timeouts
 return () => timers.forEach((timer) => clearTimeout(timer));
 }
 }, [currentContent]);
 // to apply motion and swtich in media of division end

 // Handle video updates when the duration is changed or a new video starts
 const updateContent = (i, division, contentIndex, duration) => {
 const newContent = [...currentContent];

 // Check if we are on the last media item
 if (contentIndex + 1 < division.imageSrcs.length) {
 // Move to next media if not the last one
 newContent[i].contentIndex = contentIndex + 1;
 } else {
 // If this is the last media item, pause here
 newContent[i].contentIndex = contentIndex; // Keep it at the last item
 setCurrentContent(newContent);

 // Handle video pause if the last media is a video
 const mediaElement = videoRefs.current[i];
 if (mediaElement && mediaElement.tagName === "VIDEO") {
 mediaElement.pause();
 mediaElement.currentTime = mediaElement.duration; // Pause at the end of the video
 }
 return; // Exit the function as we don't want to loop anymore
 }

 // Update state to trigger rendering of the next media
 setCurrentContent(newContent);

 // Handle video playback for the next media item
 const mediaElement = videoRefs.current[i];
 if (mediaElement) {
 mediaElement.pause();
 mediaElement.currentTime = 0;
 mediaElement
 .play()
 .catch((error) => console.error("Error playing video:", error));
 }
 };

 const renderDivision = (division, contentIndex, index) => {
 const mediaSrc = division.imageSrcs[contentIndex];

 if (!division || !division.imageSrcs || division.imageSrcs.length === 0) {
 return (
 
 <p>No media available</p>
 
 );
 }

 if (!mediaSrc) {
 return (
 
 <p>No media available</p>
 
 );
 }

 if (mediaSrc.endsWith(".mp4")) {
 return (
 > (videoRefs.current[index] = el)}
 src={mediaSrc}
 autoPlay
 controls={false}
 style={{
 width: "100%",
 height: "100%",
 objectFit: "cover",
 pointerEvents: "none",
 }}
 onLoadedData={() => {
 // Ensure video is properly loaded
 const mediaElement = videoRefs.current[index];
 if (mediaElement && mediaElement.readyState >= 3) {
 mediaElement.play().catch((error) => {
 console.error("Error attempting to play the video:", error);
 });
 }
 }}
 />
 );
 } else {
 return (
 
 );
 }
 };

 // progress bar code start
 useEffect(() => {
 if (totalDuration.current > 0) {
 // Reset elapsed time at the start
 setElapsedTime(0);

 const interval = setInterval(() => {
 setElapsedTime((prevTime) => {
 // Increment the elapsed time by 1 second if it's less than the total time
 if (prevTime < totalTime) {
 return prevTime + 1;
 } else {
 clearInterval(interval); // Clear the interval when totalTime is reached
 return prevTime;
 }
 });
 }, 1000); // Update every second

 // Clean up the interval on component unmount
 return () => clearInterval(interval);
 }
 }, [totalTime]);

 // progress bar code end

 return (
 
 
 
 Close
 
 <h2>Preview Layout: {layout.name}</h2>
 
 {currentContent.map(({ division, contentIndex }, i) => (
 
 {renderDivision(division, contentIndex, i)}
 
 ))}
 {/* canvas code for video start */}
 {/* canvas code for video end */}
 {/* Progress Bar and Time */}
 / Background color for progress bar track
 display: "flex",
 justifyContent: "space-between",
 alignItems: "center",
 }}
 >
 totalTime) * 100}%)`,
 backgroundColor: "#28a745", // Green color for progress bar
 transition: "width 0.5s linear", // Smooth transition
 }}
 >

 {/* Time display */}
 {/* / Fixed right margin
 zIndex: 1, // Ensure it's above the progress bar
 padding: "5px",
 fontSize: "18px",
 fontWeight: "600",
 color: "#333",
 // backgroundColor: "rgba(255, 255, 255, 0.8)", // Add a subtle background for readability
 }}
 >
 {elapsedTime} / {totalTime}s
 */}
 
 

 {/* Download button */}
 > (e.target.style.backgroundColor = "#218838")}
 onMouseOut={(e) => (e.target.style.backgroundColor = "#28a745")}
 >
 Download Video
 
 {/* {recording && <p>Recording in progress...</p>} */}
 
 
 );
};

export default Preview;




I tried several methods to record the content of the div with the class "layout," which contains dynamic media elements such as images and videos. The approaches I attempted include :


MediaRecorder API : I expected this API to capture the entire div and its contents, but it didn't handle the rendering of all dynamic media elements properly.


html2canvas : I used this to capture the layout as a canvas and then attempted to convert it into a video stream. However, it could not capture smooth transitions between media elements, leading to a choppy or incomplete video output.


RecordRTC : I integrated RecordRTC to capture the canvas stream of the div. Despite setting up the recorder, the resulting video file either had a 0-byte size or only captured parts of the content inconsistently.


FFmpeg and other libraries : I explored these tools hoping they would provide a seamless capture of the dynamic content, but they also failed to capture the full media elements, including videos playing within the layout.


In all cases, I expected to get a complete video recording of the div, including all media transitions, but the results were incomplete or not functional.


Now, I’m seeking an approach or best practice to record the entire div with its dynamic content and media playback.


-
Video streamign with FFMpeg and Nest.js+Next.js
17 septembre 2024, par AizenHere is my problem : I have one video src 1080p (on the frontend). On the frontend, I send this video-route to the backend :


const req = async()=>{try{const res = await axios.get('/catalog/item',{params:{SeriesName:seriesName}});return {data:res.data};}catch(err){console.log(err);return false;}}const fetchedData = await req();-On the backend i return seriesName.Now i can make a full path,what the video is,and where it is,code:



const videoUrl = 'C:/Users/arMori/Desktop/RedditClone/reddit/public/videos';console.log('IT VideoURL',videoUrl);



const selectedFile = `${videoUrl}/${fetchedData.data.VideoSource}/${seriesName}-1080p.mp4`
console.log(`ITS'S SELECTED FILE: ${selectedFile}`);



Ok, I have my src 1080p, now is the time to send it to the backend :


const response = await axios.post('/videoFormat', {videoUrl:selectedFile})console.log('Это консоль лог путей: ',response.data);const videoPaths = response.data;



Backend takes it and FFMpqg makes two types of resolution,720p and 480p,save it to the temp storage on backend, and then returns two routes where these videos stores


async videoUpload(videoUrl:string){try{const tempDir = C:/Users/arMori/Desktop/RedditClone/reddit_back/src/video/temp;const inputFile = videoUrl;console.log('VIDEOURL: ',videoUrl);



const outputFiles = [];
 
 await this.createDirectories(tempDir); 
 outputFiles.push(await this.convertVideo(inputFile, '1280x720', '720p.mp4'));
 outputFiles.push(await this.convertVideo(inputFile, '854x480', '480p.mp4'));
 console.log('OUTUPT FILES SERVICE: ',outputFiles);
 
 return outputFiles;

 }catch(err){
 console.error('VideoFormatterService Error: ',err);
 
 }
}

private convertVideo(inputPath:string,resolution:string,outputFileName:string):Promise<string>{
 const temp = `C:/Users/arMori/Desktop/RedditClone/reddit_back/src/video/temp`;
 return new Promise(async(resolve,reject)=>{
 const height = resolution.split('x')[1];
 console.log('HIEGHT: ',height);
 
 const outputDir = `C:/Users/arMori/Desktop/RedditClone/reddit_back/src/video/temp/${height}p`;
 const outputPath = join(outputDir, outputFileName);
 const isExists = await fs.access(outputPath).then(() => true).catch(() => false);
 if(isExists){ 
 console.log(`File already exists: ${outputPath}`);
 return resolve(outputPath)
 };
 ffmpeg(inputPath)
 .size(`${resolution}`)
 .videoCodec('libx264') // Кодек H.264
 .audioCodec('aac') 
 .output(outputPath)
 .on('end',()=>resolve(outputPath))
 .on('error',(err)=>reject(err))
 .run()
 
 })
}

private async createDirectories(temp:string){
 try{
 const dir720p = `${temp}/720p`;
 const dir480p = `${temp}/480p`;
 const dir720pExists = await fs.access(dir720p).then(() => true).catch(() => false);
 const dir480pExists = await fs.access(dir480p).then(() => true).catch(() => false);
 if(dir720pExists && dir480pExists){
 console.log('FILES ALIVE');
 return;
 }
 if (!dir720pExists) {
 await fs.mkdir(dir720p, { recursive: true });
 console.log('Папка 720p создана');
 }
 
 if (!dir480pExists) {
 await fs.mkdir(dir480p, { recursive: true });
 console.log('Папка 480p создана');
 }
 } catch (err) {
 console.error('Ошибка при создании директорий:', err);
 }
}
</string>


Continue frontentd code :


let videoPath;

if (quality === '720p') {
 videoPath = videoPaths[0];
} else if (quality === '480p') {
 videoPath = videoPaths[1];
}

if (!videoPath) {
 console.error('Video path not found!');
 return;
}

// Получаем видео по его пути
console.log('VIDEOPATH LOG: ',videoPath);
 
const videoRes = await axios.get('/videoFormat/getVideo', { 
 params: { path: videoPath } ,
 headers: { Range: 'bytes=0-' },
 responseType: 'blob'
 });
 console.log('Video fetched: ', videoRes);
 const videoBlob = new Blob([videoRes.data], { type: 'video/mp4' });
 const videoURL = URL.createObjectURL(videoBlob);
 return videoURL;
 /* console.log('Видео успешно загружено:', response.data); */
 } catch (error) {
 console.error('Ошибка при загрузке видео:', error);
 }
}



Here I just choose one of the route and make a new GET request (VideoRes), now in the controller in the backend, I'm trying to do a video streaming :


@Public()
 @Get('/getVideo')
 async getVideo(@Query('path') videoPath:string,@Req() req:Request,@Res() res:Response){
 try {
 console.log('PATH ARGUMENT: ',videoPath);
 console.log('VIDEOPATH IN SERVICE: ',videoPath);
 const videoSize = (await fs.stat(videoPath)).size;
 const CHUNK_SIZE = 10 ** 6;
 const range = req.headers['range'] as string | undefined;
 if (!range) {
 return new ForbiddenException('Range не найденно');
 }
 const start = Number(range.replace(/\D/g,""));
 const end = Math.min(start + CHUNK_SIZE,videoSize - 1);

 const contentLength = end - start + 1;
 const videoStream = fsSync.createReadStream(videoPath, { start, end });
 const headers = {
 'Content-Range':`bytes ${start}-${end}/${videoSize}`,
 'Accept-Ranges':'bytes',
 'Content-Length':contentLength,
 'Content-Type':'video/mp4'
 }
 
 res.writeHead(206,headers);

 // Передаем поток в ответ
 videoStream.pipe(res);
 

 // Если возникнет ошибка при стриминге, логируем ошибку
 videoStream.on('error', (error) => {
 console.error('Ошибка при чтении видео:', error);
 res.status(500).send('Ошибка при чтении видео');
 });
 } catch (error) {
 console.error('Ошибка при обработке запросов:', error);
 return res.status(400).json({ message: 'Ошибка при обработке getVideo запросов' });
 }
 }



Send to the frontend


res.writeHead(206,headers);



In the frontend, I make blob url for video src and return it


const videoBlob = new Blob([videoRes.data], { type: 'video/mp4' });const videoURL = URL.createObjectURL(videoBlob);return videoURL;



And assign src to the video :


useVideo(seriesName,quality).then(src => {
 if (src) {
 console.log('ITS VIDEOLOGISC GOIDA!');
 if(!playRef.current) return;
 
 const oldURL = playRef.current.src;
 if (oldURL && oldURL.startsWith('blob:')) {
 URL.revokeObjectURL(oldURL);
 }
 playRef.current.pause();
 playRef.current.src = '';
 setQuality(quality);
 console.log('SRC: ',src);
 
 playRef.current.src = src;
 playRef.current.load();
 console.log('ITS VIDEOURL GOIDA!');
 togglePlayPause();
 }
 })
 .catch(err => console.error('Failed to fetch video', err));



But the problem is :




Vinland-Saga:1 Uncaught (in promise) NotSupportedError : Failed to load because no supported source was found




And I don't know why...


I tried everything, but I don't understand why src is incorrect..