
Recherche avancée
Autres articles (41)
-
Publier sur MédiaSpip
13 juin 2013Puis-je poster des contenus à partir d’une tablette Ipad ?
Oui, si votre Médiaspip installé est à la version 0.2 ou supérieure. Contacter au besoin l’administrateur de votre MédiaSpip pour le savoir -
Initialisation de MediaSPIP (préconfiguration)
20 février 2010, parLors de l’installation de MediaSPIP, celui-ci est préconfiguré pour les usages les plus fréquents.
Cette préconfiguration est réalisée par un plugin activé par défaut et non désactivable appelé MediaSPIP Init.
Ce plugin sert à préconfigurer de manière correcte chaque instance de MediaSPIP. Il doit donc être placé dans le dossier plugins-dist/ du site ou de la ferme pour être installé par défaut avant de pouvoir utiliser le site.
Dans un premier temps il active ou désactive des options de SPIP qui ne le (...) -
Taille des images et des logos définissables
9 février 2011, parDans beaucoup d’endroits du site, logos et images sont redimensionnées pour correspondre aux emplacements définis par les thèmes. L’ensemble des ces tailles pouvant changer d’un thème à un autre peuvent être définies directement dans le thème et éviter ainsi à l’utilisateur de devoir les configurer manuellement après avoir changé l’apparence de son site.
Ces tailles d’images sont également disponibles dans la configuration spécifique de MediaSPIP Core. La taille maximale du logo du site en pixels, on permet (...)
Sur d’autres sites (4933)
-
"Application provided invalid, non monotonically increasing dts to muxer in stream 0 : 47104 >= -4251" in C ffmpeg video & audio streams processing
30 décembre 2023, par M.HakimFor an input.mp4 file containing a video stream and an audio stream, intend to convert the video stream into h264 codec and the audio stream into aac codec and combine the two streams in output.mp4 file using C and ffmpeg libraries.
Am getting an error [mp4 @ 0x5583c88fd340] Application provided invalid, non monotonically increasing dts to muxer in stream 0 : 47104 >= -4251
How do i solve that error ?


#include 
#include <libavcodec></libavcodec>avcodec.h>
#include <libavformat></libavformat>avformat.h> 
#include <libavutil></libavutil>opt.h>

int encodeVideoAndAudio4(char *pInName, char *pOutName) {

 AVFormatContext *format_ctx = avformat_alloc_context();

 AVCodecContext *video_dec_ctx = NULL;
 AVCodecContext *video_enc_ctx = NULL;
 AVCodec *video_dec_codec = NULL;
 AVCodec *video_enc_codec = NULL;
 AVDictionary *video_enc_opts = NULL;

 AVCodecContext *audio_dec_ctx = NULL;
 AVCodecContext *audio_enc_ctx = NULL;
 AVCodec *audio_dec_codec = NULL;
 AVCodec *audio_enc_codec = NULL;


 if (avformat_open_input(&format_ctx, pInName, NULL, NULL) < 0) {
 fprintf(stderr, "Error: Could not open input file\n");
 return 1;
 }

 if (avformat_find_stream_info(format_ctx, NULL) < 0) {
 fprintf(stderr, "Error: Could not find stream information\n");
 return 1;
 }

 for (int i = 0; i < format_ctx->nb_streams; i++) {
 AVStream *stream = format_ctx->streams[i];
 const char *media_type_str = av_get_media_type_string(stream->codecpar->codec_type);
 AVRational time_base = stream->time_base;

 }

 int video_stream_index = -1;
 for (int i = 0; i < format_ctx->nb_streams; i++) {
 if (format_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
 video_stream_index = i;
 break;
 }
 }
 if (video_stream_index == -1) {
 fprintf(stderr, "Error: Could not find a video stream\n");
 return 1;
 }

 AVStream *videoStream = format_ctx->streams[video_stream_index];
 video_dec_ctx = avcodec_alloc_context3(NULL);
 avcodec_parameters_to_context(video_dec_ctx, videoStream->codecpar);

 video_dec_codec = avcodec_find_decoder(video_dec_ctx->codec_id);

 if (!video_dec_codec) {
 fprintf(stderr, "Unsupported video codec!\n");
 return 1;
 }

 if (avcodec_open2(video_dec_ctx, video_dec_codec, NULL) < 0) {
 fprintf(stderr, "Error: Could not open a video decoder codec\n");
 return 1;
 }

 video_enc_codec = avcodec_find_encoder(AV_CODEC_ID_H264);
 if (!video_enc_codec) {
 fprintf(stderr, "Error: Video Encoder codec not found\n");
 return 1;
 }

 video_enc_ctx = avcodec_alloc_context3(video_enc_codec);
 if (!video_enc_ctx) {
 fprintf(stderr, "Error: Could not allocate video encoder codec context\n");
 return 1;
 }

 videoStream->time_base = (AVRational){1, 25};

 video_enc_ctx->bit_rate = 1000; 
 video_enc_ctx->width = video_dec_ctx->width;
 video_enc_ctx->height = video_dec_ctx->height;
 video_enc_ctx->time_base = (AVRational){1, 25};
 video_enc_ctx->gop_size = 10;
 video_enc_ctx->max_b_frames = 1;
 video_enc_ctx->pix_fmt = AV_PIX_FMT_YUV420P;

 if (avcodec_open2(video_enc_ctx, video_enc_codec, NULL) < 0) {
 fprintf(stderr, "Error: Could not open encoder codec\n");
 return 1;
 }

 av_dict_set(&video_enc_opts, "preset", "medium", 0);
 av_opt_set_dict(video_enc_ctx->priv_data, &video_enc_opts);

 AVPacket video_pkt;
 av_init_packet(&video_pkt);
 video_pkt.data = NULL;
 video_pkt.size = 0;

 AVPacket pkt;
 av_init_packet(&pkt);
 pkt.data = NULL;
 pkt.size = 0;

 AVFrame *video_frame = av_frame_alloc();
 if (!video_frame) {
 fprintf(stderr, "Error: Could not allocate video frame\n");
 return 1;
 }

 video_frame->format = video_enc_ctx->pix_fmt;
 video_frame->width = video_enc_ctx->width;
 video_frame->height = video_enc_ctx->height;
 
 int audio_stream_index = -1;
 for (int i = 0; i < format_ctx->nb_streams; i++) {
 if (format_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
 audio_stream_index = i;
 break;
 }
 }

 if (audio_stream_index == -1) {
 fprintf(stderr, "Error: Could not find an audio stream\n");
 return 1;
 }
 
 AVStream *audioStream = format_ctx->streams[audio_stream_index];
 audio_dec_ctx = avcodec_alloc_context3(NULL);
 avcodec_parameters_to_context(audio_dec_ctx, audioStream->codecpar);
 
 audio_dec_codec = avcodec_find_decoder(audio_dec_ctx->codec_id);
 
 if (!audio_dec_codec) {
 fprintf(stderr, "Unsupported audio codec!\n");
 return 1;
 }
 
 if (avcodec_open2(audio_dec_ctx, audio_dec_codec, NULL) < 0) {
 fprintf(stderr, "Error: Could not open Audio decoder codec\n");
 return 1;
 }
 
 audio_enc_codec = avcodec_find_encoder(AV_CODEC_ID_AAC);
 if (!audio_enc_codec) {
 fprintf(stderr, "Error: Audio Encoder codec not found\n");
 return 1;
 }
 
 audio_enc_ctx = avcodec_alloc_context3(audio_enc_codec);
 if (!audio_enc_ctx) {
 fprintf(stderr, "Error: Could not allocate audio encoder codec context\n");
 return 1;
 }

 audioStream->time_base = (AVRational){1, audio_dec_ctx->sample_rate};
 
 audio_enc_ctx->bit_rate = 64000; 
 audio_enc_ctx->sample_rate = audio_dec_ctx->sample_rate;
 audio_enc_ctx->channels = audio_dec_ctx->channels;
 audio_enc_ctx->channel_layout = av_get_default_channel_layout(audio_enc_ctx->channels);
 audio_enc_ctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
 audio_enc_ctx->profile = FF_PROFILE_AAC_LOW;
 
 if (avcodec_open2(audio_enc_ctx, audio_enc_codec, NULL) < 0) {
 fprintf(stderr, "Error: Could not open encoder codec\n");
 return 1;
 }
 
 AVPacket audio_pkt;
 av_init_packet(&audio_pkt);
 audio_pkt.data = NULL;
 audio_pkt.size = 0;
 
 AVFrame *audio_frame = av_frame_alloc();
 if (!audio_frame) {
 fprintf(stderr, "Error: Could not allocate audio frame\n");
 return 1;
 }

 audio_frame->format = audio_enc_ctx->sample_fmt;
 audio_frame->sample_rate = audio_enc_ctx->sample_rate;
 audio_frame->channels = audio_enc_ctx->channels;
 
 AVFormatContext *output_format_ctx = NULL;
 if (avformat_alloc_output_context2(&output_format_ctx, NULL, NULL, pOutName) < 0) {
 fprintf(stderr, "Error: Could not create output context\n");
 return 1;
 }
 
 if (avio_open(&output_format_ctx->pb, pOutName, AVIO_FLAG_WRITE) < 0) {
 fprintf(stderr, "Error: Could not open output file\n");
 return 1;
 }
 
 AVStream *video_stream = avformat_new_stream(output_format_ctx, video_enc_codec);
 if (!video_stream) {
 fprintf(stderr, "Error: Could not create video stream\n");
 return 1;
 }
 
 av_dict_set(&video_stream->metadata, "rotate", "90", 0);
 
 if (avcodec_parameters_from_context(video_stream->codecpar, video_enc_ctx) < 0) {
 fprintf(stderr, "Error: Could not copy video codec parameters\n");
 return 1;
 }
 
 AVStream *audio_stream = avformat_new_stream(output_format_ctx, audio_enc_codec);
 if (!audio_stream) {
 fprintf(stderr, "Error: Could not create audio stream\n");
 return 1;
 }
 
 if (avcodec_parameters_from_context(audio_stream->codecpar, audio_enc_ctx) < 0) {
 fprintf(stderr, "Error: Could not copy audio codec parameters\n");
 return 1;
 }
 
 if (avformat_write_header(output_format_ctx, NULL) < 0) {
 fprintf(stderr, "Error: Could not write header\n");
 return 1;
 }
 
 int video_frame_count = 0, audio_frame_count = 0;
 
 while (1) {

 if (av_read_frame(format_ctx, &pkt) < 0) {
 fprintf(stderr, "BREAK FROM MAIN WHILE LOOP\n");
 break;
 }

 if (pkt.stream_index == video_stream_index) {

 if (avcodec_send_packet(video_dec_ctx, &pkt) < 0) {
 fprintf(stderr, "Error: Could not send video packet for decoding\n");
 return 1;
 }

 while (avcodec_receive_frame(video_dec_ctx, video_frame) == 0) { 

 if (avcodec_send_frame(video_enc_ctx, video_frame) < 0) {
 fprintf(stderr, "Error: Could not send video frame for encoding\n");
 return 1;
 }

 while (avcodec_receive_packet(video_enc_ctx, &video_pkt) == 0) {
 
 if (av_write_frame(output_format_ctx, &video_pkt) < 0) {
 fprintf(stderr, "Error: Could not write video packet to output file.\n");
 return 1;
 }

 av_packet_unref(&video_pkt);
 }

 video_frame_count++;
 }
 } else if (pkt.stream_index == audio_stream_index) {

 if (avcodec_send_packet(audio_dec_ctx, &pkt) < 0) {
 fprintf(stderr, "Error: Could not send audio packet for decoding\n");
 return 1;
 }

 while (avcodec_receive_frame(audio_dec_ctx, audio_frame) == 0) { 
 
 if (avcodec_send_frame(audio_enc_ctx, audio_frame) < 0) {
 fprintf(stderr, "Error: Could not send audio frame for encoding\n");
 return 1;
 }

 while (avcodec_receive_packet(audio_enc_ctx, &audio_pkt) == 0) { if (av_write_frame(output_format_ctx, &audio_pkt) < 0) {
 fprintf(stderr, "Error: Could not write audio packet to output file\n");
 return 1;
 }

 av_packet_unref(&audio_pkt);
 }

 audio_frame_count++;
 }
 }

 av_packet_unref(&pkt);
 }

 if (av_write_trailer(output_format_ctx) < 0) {
 fprintf(stderr, "Error: Could not write trailer\n");
 return 1;
 } 
 
 avformat_close_input(&format_ctx);
 avio_close(output_format_ctx->pb);
 avformat_free_context(output_format_ctx);
 
 av_frame_free(&video_frame);
 avcodec_free_context(&video_dec_ctx);
 avcodec_free_context(&video_enc_ctx);
 av_dict_free(&video_enc_opts);
 
 av_frame_free(&audio_frame);
 avcodec_free_context(&audio_dec_ctx);
 avcodec_free_context(&audio_enc_ctx);

 printf("Conversion complete. %d video frames processed and %d audio frames processed.\n",video_frame_count, audio_frame_count);

 return 0;
}


int main(int argc, char *argv[]) {
 if (argc != 3) {
 printf("Usage: %s \n", argv[0]);
 return 1;
 }

 const char *input_filename = argv[1];
 const char *output_filename = argv[2];

 avcodec_register_all();
 av_register_all();

 int returnValue = encodeVideoAndAudio4(input_filename, output_filename);
 
 return 0;
}




When i comment out the blocks that process one of the two streams, the other stream is converted and written to the output.mp4 successfully.
When each stream is processed in a separate loop, only the first stream is processed and written to the output.mp4 file and the other stream is skipped.
When both streams are processed in a common loop as it is in the code above, the above mentioned error appears.


-
"FFmpeg : Error not transitioning to the next song in Discord Bot's queue."
1er avril 2024, par nooberI have 3 modules, but I'm sure the error occurs within this module, and here is the entire code within that module :


import asyncio
import discord
from discord import FFmpegOpusAudio, Embed
import os

async def handle_help(message):
 embed = discord.Embed(
 title="Danh sách lệnh cho Bé Mèo",
 description="Dưới đây là các lệnh mà chủ nhân có thể bắt Bé Mèo phục vụ:",
 color=discord.Color.blue()
 )
 embed.add_field(name="!play", value="Phát một bài hát từ YouTube.", inline=False)
 embed.add_field(name="!pause", value="Tạm dừng bài hát đang phát.", inline=False)
 embed.add_field(name="!resume", value="Tiếp tục bài hát đang bị tạm dừng.", inline=False)
 embed.add_field(name="!skip", value="Chuyển đến bài hát tiếp theo trong danh sách chờ.", inline=False)
 embed.add_field(name="!stop", value="Dừng phát nhạc và cho phép Bé Mèo đi ngủ tiếp.", inline=False)
 # Thêm các lệnh khác theo cùng mẫu trên
 await message.channel.send(embed=embed)

class Song:
 def __init__(self, title, player):
 self.title = title # Lưu trữ tiêu đề bài hát ở đây
 self.player = player

# Thêm đối tượng Song vào hàng đợi
def add_song_to_queue(guild_id, queues, song):
 queues.setdefault(guild_id, []).append(song)

async def handle_list(message, queues):
 log_file_path = "C:\\Bot Music 2\\song_log.txt"
 if os.path.exists(log_file_path):
 with open(log_file_path, "r", encoding="utf-8") as f:
 song_list = f.readlines()

 if song_list:
 embed = discord.Embed(
 title="Danh sách bài hát",
 description="Danh sách các bài hát đã phát:",
 color=discord.Color.blue()
 )

 for i, song in enumerate(song_list, start=1):
 if i == 1:
 song = "- Đang phát: " + song.strip()
 embed.add_field(name=f"Bài hát {i}", value=song, inline=False)

 await message.channel.send(embed=embed)
 else:
 await message.channel.send("Hiện không có dữ liệu trong file log.")
 else:
 await message.channel.send("File log không tồn tại.")

async def handle_commands(message, client, queues, voice_clients, yt_dl_options, ytdl, ffmpeg_options=None, guild_id=None, data=None):
 # Nếu không có ffmpeg_options, sử dụng các thiết lập mặc định
 if ffmpeg_options is None:
 ffmpeg_options = {
 'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
 'options': '-vn -filter:a "volume=0.25"'
 }
 
 # Khởi tạo voice_client
 if guild_id is None:
 guild_id = message.guild.id

 if guild_id in voice_clients:
 voice_client = voice_clients[guild_id]
 else:
 voice_client = None

 # Xử lý lệnh !play
 if message.content.startswith("!play"):
 try:
 # Kiểm tra xem người gửi tin nhắn có đang ở trong kênh voice không
 voice_channel = message.author.voice.channel
 # Kiểm tra xem bot có đang ở trong kênh voice của guild không
 if voice_client and voice_client.is_connected():
 await voice_client.move_to(voice_channel)
 else:
 voice_client = await voice_channel.connect()
 voice_clients[guild_id] = voice_client
 except Exception as e:
 print(e)

 try:
 query = ' '.join(message.content.split()[1:])
 if query.startswith('http'):
 url = query
 else:
 query = 'ytsearch:' + query
 loop = asyncio.get_event_loop()
 data = await loop.run_in_executor(None, lambda: ytdl.extract_info(query, download=False))
 if not data:
 raise ValueError("Không có dữ liệu trả về từ YouTube.")
 url = data['entries'][0]['url']

 player = FFmpegOpusAudio(url, **ffmpeg_options)
 # Lấy thông tin của bài hát mới đang được yêu cầu
 title = data['entries'][0]['title']
 duration = data['entries'][0]['duration']
 creator = data['entries'][0]['creator'] if 'creator' in data['entries'][0] else "Unknown"
 requester = message.author.nick if message.author.nick else message.author.name
 
 # Tạo embed để thông báo thông tin bài hát mới
 embed = discord.Embed(
 title="Thông tin bài hát mới",
 description=f"**Bài hát:** *{title}*\n**Thời lượng:** *{duration}*\n**Tác giả:** *{creator}*\n**Người yêu cầu:** *{requester}*",
 color=discord.Color.green()
 )
 await message.channel.send(embed=embed)
 
 # Sau khi lấy thông tin của bài hát diễn ra, gọi hàm log_song_title với title của bài hát
 # Ví dụ:
 title = data['entries'][0]['title']
 await log_song_title(title)

 # Thêm vào danh sách chờ nếu có bài hát đang phát
 if voice_client.is_playing():
 queues.setdefault(guild_id, []).append(player)
 else:
 voice_client.play(player)
 
 except Exception as e:
 print(e)
 
 if message.content.startswith("!link"):
 try:
 voice_client = await message.author.voice.channel.connect()
 voice_clients[voice_client.guild.id] = voice_client
 except Exception as e:
 print(e)

 try:
 url = message.content.split()[1]

 loop = asyncio.get_event_loop()
 data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=False))

 song = data['url']
 player = discord.FFmpegOpusAudio(song, **ffmpeg_options)

 voice_clients[message.guild.id].play(player)
 except Exception as e:
 print(e)

 # Xử lý lệnh !queue
 elif message.content.startswith("!queue"):
 queue = queues.get(guild_id, [])
 if queue:
 await message.channel.send("Danh sách chờ:")
 for index, item in enumerate(queue, 1):
 await message.channel.send(f"{index}. {item.title}")
 else:
 await message.channel.send("Không có bài hát nào trong danh sách chờ.")

 # Xử lý lệnh !skip
 elif message.content.startswith("!skip"):
 try:
 if voice_client and voice_client.is_playing():
 voice_client.stop()
 await play_next_song(guild_id, queues, voice_client, skip=True)
 await remove_first_line_from_log()
 except Exception as e:
 print(e)

 # Xử lý các lệnh như !pause, !resume, !stop
 elif message.content.startswith("!pause"):
 try:
 if voice_client and voice_client.is_playing():
 voice_client.pause()
 except Exception as e:
 print(e)

 elif message.content.startswith("!resume"):
 try:
 if voice_client and not voice_client.is_playing():
 voice_client.resume()
 except Exception as e:
 print(e)

 elif message.content.startswith("!stop"):
 try:
 if voice_client:
 voice_client.stop()
 await voice_client.disconnect()
 del voice_clients[guild_id] # Xóa voice_client sau khi dừng
 except Exception as e:
 print(e)

async def log_song_title(title):
 log_file_path = "C:\\Bot Music 2\\song_log.txt"
 try:
 # Kiểm tra xem tệp tin log đã tồn tại chưa
 if not os.path.exists(log_file_path):
 # Nếu chưa tồn tại, tạo tệp tin mới và ghi title vào tệp tin đó
 with open(log_file_path, 'w', encoding='utf-8') as file:
 file.write(title + '\n')
 else:
 # Nếu tệp tin log đã tồn tại, mở tệp tin và chèn title vào cuối tệp tin
 with open(log_file_path, 'a', encoding='utf-8') as file:
 file.write(title + '\n')
 except Exception as e:
 print(f"Error logging song title: {e}")

async def remove_first_line_from_log():
 log_file_path = "C:\\Bot Music 2\\song_log.txt"
 try:
 with open(log_file_path, "r", encoding="utf-8") as f:
 lines = f.readlines()
 # Xóa dòng đầu tiên trong list lines
 lines = lines[1:]
 with open(log_file_path, "w", encoding="utf-8") as f:
 for line in lines:
 f.write(line)
 except Exception as e:
 print(f"Error removing first line from log: {e}")
 
async def clear_log_file():
 log_file_path = "C:\\Bot Music 2\\song_log.txt"
 try:
 with open(log_file_path, "w", encoding="utf-8") as f:
 f.truncate(0)
 except Exception as e:
 print(f"Error clearing log file: {e}")


async def play_next_song(guild_id, queues, voice_client, skip=False):
 queue = queues.get(guild_id, [])
 if queue:
 player = queue.pop(0)
 voice_client.play(player, after=lambda e: asyncio.run_coroutine_threadsafe(play_next_song(guild_id, queues, voice_client, skip=False), voice_client.loop))
 if skip:
 return
 else:
 await remove_first_line_from_log() # Xóa dòng đầu tiên trong file log
 elif skip:
 await remove_first_line_from_log() # Xóa dòng đầu tiên trong file log
 await voice_client.disconnect()
 del voice_client[guild_id] # Xóa voice_client sau khi dừng
 else:
 await clear_log_file() # Xóa dòng đầu tiên trong file log
 await voice_client.disconnect()
 del voice_client[guild_id] # Xóa voice_client sau khi dừng



I have tried asking ChatGPT, Gemini, or Bing, and they always lead me into a loop of errors that cannot be resolved. This error only occurs when the song naturally finishes playing due to its duration. If the song is playing and I use the command !skip, the next song in the queue will play and function normally. I noticed that it seems like if a song ends naturally, the song queue is also cleared immediately. I hope someone can help me with this


-
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 ?