
Recherche avancée
Médias (1)
-
La conservation du net art au musée. Les stratégies à l’œuvre
26 mai 2011
Mis à jour : Juillet 2013
Langue : français
Type : Texte
Autres articles (104)
-
Soumettre améliorations et plugins supplémentaires
10 avril 2011Si vous avez développé une nouvelle extension permettant d’ajouter une ou plusieurs fonctionnalités utiles à MediaSPIP, faites le nous savoir et son intégration dans la distribution officielle sera envisagée.
Vous pouvez utiliser la liste de discussion de développement afin de le faire savoir ou demander de l’aide quant à la réalisation de ce plugin. MediaSPIP étant basé sur SPIP, il est également possible d’utiliser le liste de discussion SPIP-zone de SPIP pour (...) -
Emballe médias : à quoi cela sert ?
4 février 2011, parCe plugin vise à gérer des sites de mise en ligne de documents de tous types.
Il crée des "médias", à savoir : un "média" est un article au sens SPIP créé automatiquement lors du téléversement d’un document qu’il soit audio, vidéo, image ou textuel ; un seul document ne peut être lié à un article dit "média" ; -
ANNEXE : Les plugins utilisés spécifiquement pour la ferme
5 mars 2010, parLe site central/maître de la ferme a besoin d’utiliser plusieurs plugins supplémentaires vis à vis des canaux pour son bon fonctionnement. le plugin Gestion de la mutualisation ; le plugin inscription3 pour gérer les inscriptions et les demandes de création d’instance de mutualisation dès l’inscription des utilisateurs ; le plugin verifier qui fournit une API de vérification des champs (utilisé par inscription3) ; le plugin champs extras v2 nécessité par inscription3 (...)
Sur d’autres sites (10278)
-
React Native (Android) : Download mp3 file
21 février 2024, par Batuhan FındıkI get the youtube video link from the ui. I download the video from this link and convert it to mp3. I download it to my phone as mp3. The song opens on WhatsApp on the phone. but it doesn't open on the mp3 player. The song is not broken because it opens on WhatsApp too. Why do you think the mp3 player doesn't open ? Could it be from the file information ? I tried to enter some file information but it still won't open. For example, there is from information in songs played on an mp3 player. There is no from information in my song file. I tried to add it but it wasn't added.


.net 8 api return :


[HttpPost("ConvertVideoToMp3")]
public async Task<iactionresult> ConvertVideoToMp3(Mp3 data)
{
 try
 {
 string videoId = GetYoutubeVideoId(data.VideoUrl);

 var streamInfoSet = await _youtubeClient.Videos.Streams.GetManifestAsync(videoId);
 var videoStreamInfo = streamInfoSet.GetAudioOnlyStreams().GetWithHighestBitrate();

 if (videoStreamInfo != null)
 {
 var videoStream = await _youtubeClient.Videos.Streams.GetAsync(videoStreamInfo);
 var memoryStream = new MemoryStream();

 await videoStream.CopyToAsync(memoryStream);
 memoryStream.Seek(0, SeekOrigin.Begin);

 var videoFilePath = $"{videoId}.mp4";
 await System.IO.File.WriteAllBytesAsync(videoFilePath, memoryStream.ToArray());

 var mp3FilePath = $"{videoId}.mp3";
 var ffmpegProcess = Process.Start(new ProcessStartInfo
 {
 FileName = "ffmpeg",
 Arguments = $"-i \"{videoFilePath}\" -vn -acodec libmp3lame -ab 128k -id3v2_version 3 -metadata artist=\"YourArtistName\" -metadata title=\"YourTitle\" -metadata from=\"youtube\" \"{mp3FilePath}\"",
 RedirectStandardError = true,
 UseShellExecute = false,
 CreateNoWindow = true
 });

 await ffmpegProcess.WaitForExitAsync();

 var file = TagLib.File.Create(mp3FilePath);

 
 file.Tag.Artists = new string [] { "YourArtistName"};
 file.Tag.Title = "YourTitle";
 file.Tag.Album = "YourAlbumName"; 
 file.Tag.Comment = "Source: youtube";
 

 file.Save();

 var mp3Bytes = await System.IO.File.ReadAllBytesAsync(mp3FilePath);

 System.IO.File.Delete(videoFilePath);
 System.IO.File.Delete(mp3FilePath);

 return File(mp3Bytes, "audio/mpeg", $"{videoId}.mp3");
 }
 else
 {
 return NotFound("Video stream not found");
 }
 }
 catch (Exception ex)
 {
 return StatusCode(500, $"An error occurred: {ex.Message}");
 }
}
</iactionresult>


React Native :


const handleConvertAndDownload = async () => {
 try {
 const url = 'http://192.168.1.5:8080/api/Mp3/ConvertVideoToMp3';
 const fileName = 'example';
 const newFileName = generateUniqueSongName(fileName);
 const filePath = RNFS.DownloadDirectoryPath + '/'+newFileName;

 fetch(url, {
 method: 'POST',
 headers: {
 'Content-Type': 'application/json',
 },
 body: JSON.stringify({videoUrl:videoUrl}),
 })
 .then((response) => {
 if (!response.ok) {
 Alert.alert('Error', 'Network');
 throw new Error('Network response was not ok');
 }
 return response.blob();
 })
 .then((blob) => {
 return new Promise((resolve, reject) => {
 const reader = new FileReader();
 reader.onloadend = () => {
 resolve(reader.result.split(',')[1]); 
 };
 reader.onerror = reject;
 reader.readAsDataURL(blob);
 });
 })
 .then((base64Data) => {
 // Dosyanın varlığını kontrol et
 return RNFS.exists(filePath)
 .then((exists) => {
 if (exists) {
 console.log('File already exists');
 return RNFS.writeFile(filePath, base64Data, 'base64', 'append');
 } else {
 console.log('File does not exist');
 return RNFS.writeFile(filePath, base64Data, 'base64');
 }
 })
 .catch((error) => {
 console.error('Error checking file existence:', error);
 throw error;
 });
 })
 .then(() => {
 Alert.alert('Success', 'MP3 file downloaded successfully.');
 console.log('File downloaded successfully!');
 })
 .catch((error) => {
 Alert.alert('Error', error.message);
 console.error('Error downloading file:', error);
 });
 } catch (error) {
 Alert.alert('Error', error.message);
 console.error(error);
 }
 };



-
How to Correctly Implement ffmpeg Complex Filters in Node.js for Image Processing ?
24 janvier 2024, par LukeProblem :


I am trying to add filters and transitions between my image slideshow array, and am struggling to apply the proper filters. For example, I get errors like this :


{
 "errorType": "Error",
 "errorMessage": "ffmpeg exited with code 234: Failed to set value 'fade=type=in:start_time=0:duration=1,zoompan=z=zoom+0.002:d=120:x=if(gte(zoom,1.2),x,x+1):y=if(gte(zoom,1.2),y,y+1)' for option 'filter_complex': Invalid argument\nError parsing global options: Invalid argument\n",
 "trace": [
 "Error: ffmpeg exited with code 234: Failed to set value 'fade=type=in:start_time=0:duration=1,zoompan=z=zoom+0.002:d=120:x=if(gte(zoom,1.2),x,x+1):y=if(gte(zoom,1.2),y,y+1)' for option 'filter_complex': Invalid argument",
 "Error parsing global options: Invalid argument",
 "",
 " at ChildProcess.<anonymous> (/opt/nodejs/node_modules/fluent-ffmpeg/lib/processor.js:182:22)",
 " at ChildProcess.emit (node:events:517:28)",
 " at ChildProcess._handle.onexit (node:internal/child_process:292:12)"
 ]
}
</anonymous>


Lambda Function Code :


async function concat(bucketName, imageKeys) {
 const imageStreams = await Promise.all(
 imageKeys.map(async (key, i) => {
 const command = new GetObjectCommand({ Bucket: bucketName, Key: key });
 const response = await s3.send(command);
 // Define the temporary file path based on the index
 const tempFilePath = `/tmp/${i}.png`;
 
 // Write the image data to the temporary file
 await fs.writeFile(tempFilePath, response.Body);
 
 // Return the file path to be used later
 return tempFilePath;
 })
 );
 
 // Create a file list content with durations
 let fileContent = "";
 for (let i = 0; i < imageStreams.length; i++) {
 fileContent += `file '${imageStreams[i]}'\nduration 1\n`;
 
 // Check if it's the last image, and if so, add it again
 if (i === imageStreams.length - 1) {
 fileContent += `file '${imageStreams[i]}'\nduration 1\n`;
 }
 }
 
 // Define the file path for the file list
 const fileListPath = "/tmp/file_list.txt";
 
 // Write the file list content to the file
 await fs.writeFile(fileListPath, fileContent);
 
 try {
 await fs.writeFile(fileListPath, fileContent);
 } catch (error) {
 console.error("Error writing file list:", error);
 throw error;
 }
 
 // Create a complex filter to add zooms and pans
 // Simplified filter example
 let complexFilter = [
 // Example of a fade transition
 {
 filter: 'fade',
 options: { type: 'in', start_time: 0, duration: 1 },
 inputs: '0:v', // first video stream
 outputs: 'fade0'
 },
 // Example of dynamic zoompan
 {
 filter: 'zoompan',
 options: {
 z: 'zoom+0.002',
 d: 120, // duration for this image
 x: 'if(gte(zoom,1.2),x,x+1)', // dynamic x position
 y: 'if(gte(zoom,1.2),y,y+1)' // dynamic y position
 },
 inputs: 'fade0',
 outputs: 'zoom0'
 }
 // Continue adding filters for each image
 ];

 let filterString = complexFilter
 .map(
 (f) =>
 `${f.filter}=${Object.entries(f.options)
 .map(([key, value]) => `${key}=${value}`)
 .join(":")}`
 )
 .join(",");
 
 let filterString = complexFilter
 .map(
 (f) =>
 `${f.filter}=${Object.entries(f.options)
 .map(([key, value]) => `${key}=${value}`)
 .join(":")}`
 )
 .join(",");
 
 console.log("Filter String:", filterString);
 
 return new Promise((resolve, reject) => {
 ffmpeg()
 .input(fileListPath)
 .complexFilter(filterString)
 .inputOptions(["-f concat", "-safe 0"])
 .outputOptions("-c copy")
 .outputOptions("-c:v libx264")
 .outputOptions("-pix_fmt yuv420p")
 .outputOptions("-r 30")
 .on("end", () => {
 resolve();
 })
 .on("error", (err) => {
 console.error("Error during video concatenation:", err);
 reject(err);
 })
 .saveToFile("/tmp/output.mp4");
 });
 }



Filter String Console Log :


Filter String: fade=type=in:start_time=0:duration=1,zoompan=z=zoom+0.002:d=120:x=if(gte(zoom,1.2),x,x+1):y=if(gte(zoom,1.2),y,y+1)



Questions :


- 

- What is the correct syntax for implementing complex filters like zoompan and fade in ffmpeg when used in a Node.js environment ?
- How do I ensure the filters are applied correctly to each image in the sequence ?
- Is there a better way to dynamically generate these filters based on the number of images or their content ?








Any insights or examples of correctly implementing this would be greatly appreciated !


-
How do I merge images and an audio file into a single video ?
3 janvier 2024, par AnilI am creating a web application using next js.
I want to create a video by combining three images and an audio track in such a way that each image is displayed for an equal duration that collectively matches the length of the audio. It will all happen locally on the browser.


This is my code for converting images and audio into a video.


import {FFmpeg} from '@ffmpeg/ffmpeg';
import { fetchFile, toBlobURL } from '@ffmpeg/util';


export async function createVideo(ImageFiles, audioFile) {

 try {
 const baseURL = 'https://unpkg.com/@ffmpeg/core@0.12.4/dist/umd';
 const ffmpeg = new FFmpeg({ log: true});

 console.log('Loading ffmpeg core');
 await ffmpeg.load({
 corePath: await toBlobURL(`${baseURL}/ffmpeg-core.js`, 'text/javascript'),
 wasmPath: await toBlobURL(`${baseURL}/ffmpeg-core.wasm`, 'application/wasm'),
 });
 await ffmpeg.load();
 console.log('Finished loading ffmpeg core');

 for (let i = 0; i < ImageFiles.length; i++) {
 ffmpeg.writeFile(
 `image${i+1}.jpg`,
 await fetchFile(ImageFiles[i].imageUrl)
 );
 }

 ffmpeg.FS('writeFile', 'audio.mp3', await fetchFile(audioFile));


 const durationPerImage = (await getAudioDuration(ffmpeg, 'audio.mp3')) / ImageFiles.length;
 let filterComplex = '';
 for (let i = 0; i < ImageFiles.length - 1; i++) {filterComplex += `[${i}:v]trim=duration=${durationPerImage},setpts=PTS-STARTPTS[v${i}]; `;
 }
 filterComplex += `${ImageFiles.slice(0, -1).map((_, i) => `[v${i}]`).join('')}concat=n=${ImageFiles.length - 1}:v=1:a=0,format=yuv420p[v];`;

 await ffmpeg.run(
 '-framerate', '1', '-loop', '1', '-t', durationPerImage, '-i', 'image%d.jpg', '-i', 'audio.mp3',
 '-filter_complex', filterComplex, '-map', '[v]', '-map', '1:a',
 '-c:v', 'libx264', '-tune', 'stillimage', '-c:a', 'aac', '-b:a', '192k', 'output.mp4'
 );

 const data = ffmpeg.FS('readFile', 'output.mp4');

 const videoURL = URL.createObjectURL(new Blob([data.buffer], { type: 'video/mp4' }));
 return videoURL;
 } catch (error) {
 console.error('Error creating video:', error);
 throw new Error('Failed to create video');
 }
}

async function getAudioDuration(ffmpeg, audioFilename) {
 await ffmpeg.run('-i', audioFilename, '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', 'duration.txt');
 const data = ffmpeg.FS('readFile', 'duration.txt');
 const durationString = new TextDecoder().decode(data);
 const duration = Math.floor(parseFloat(durationString.trim())); 
 return duration;
}



I am getting this error :


CreateVideo.js:65 Error creating video: RuntimeError: Aborted(LinkError: WebAssembly.instantiate(): Import #70 module="a" function="qa": function import requires a callable). Build with -sASSERTIONS for more info.



Can someone help me with this ?