
Recherche avancée
Médias (1)
-
The pirate bay depuis la Belgique
1er avril 2013, par
Mis à jour : Avril 2013
Langue : français
Type : Image
Autres articles (107)
-
Amélioration de la version de base
13 septembre 2013Jolie sélection multiple
Le plugin Chosen permet d’améliorer l’ergonomie des champs de sélection multiple. Voir les deux images suivantes pour comparer.
Il suffit pour cela d’activer le plugin Chosen (Configuration générale du site > Gestion des plugins), puis de configurer le plugin (Les squelettes > Chosen) en activant l’utilisation de Chosen dans le site public et en spécifiant les éléments de formulaires à améliorer, par exemple select[multiple] pour les listes à sélection multiple (...) -
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" ; -
Menus personnalisés
14 novembre 2010, parMediaSPIP utilise le plugin Menus pour gérer plusieurs menus configurables pour la navigation.
Cela permet de laisser aux administrateurs de canaux la possibilité de configurer finement ces menus.
Menus créés à l’initialisation du site
Par défaut trois menus sont créés automatiquement à l’initialisation du site : Le menu principal ; Identifiant : barrenav ; Ce menu s’insère en général en haut de la page après le bloc d’entête, son identifiant le rend compatible avec les squelettes basés sur Zpip ; (...)
Sur d’autres sites (11593)
-
Python musical bot
14 juin 2022, par Лагуш ЛюбомирI was working on bot for my discord server for 2 hours but still it doesnt work and not even connecting to voice chat


import discord
from discord.ext import commands
from youtube_dl import YoutubeDL
YDL_OPTIONS = {'format': 'worstaudio/best', 'noplaylist': 'False', 'simulate': 'True',
 'preferredquality': '192', 'preferredcodec': 'mp3', 'key': 'FFmpegExtractAudio'}
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
client = commands.Bot ( command_prefix='>')
@client.event
async def on_ready():
 print("Meepo connected")
@client.command(pass_context = True )
async def hello( ctx ):
 author = ctx.message.author
 await ctx.send(f"{ author.mention }///Добрий день шановне панство, Я пан Міпарний!")
@client.command()
async def play(ctx, *, arg):
 vc = await ctx.message.author.voice.channel.connect()

 with YoutubeDL(YDL_OPTIONS) as ydl:
 if 'https://' in arg:
 info = ydl.extract_info(arg, download=False)
 else:
 info = ydl.extract_info(f"ytsearch:{arg}", download=False)['entries'][0]

 url = info['formats'][0]['url']

 vc.play(discord.FFmpegPCMAudio(executable="ffmpeg\\bin\\ffmpeg.exe", source=url, **FFMPEG_OPTIONS))
token = open("token.txt", "r").readline()
client.run(token)



in my server console i was getting this message
M


eepo connected
Ignoring exception in command play:
Traceback (most recent call last):
 File "C:\Users\orest\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 85, in wrapped
 ret = await coro(*args, **kwargs)
 File "C:\Users\orest\Desktop\server\bot.py", line 17, in play
 vc = await ctx.message.author.voice.channel.connect()
 File "C:\Users\orest\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\abc.py", line 1277, in connect
 voice = cls(client, self)
 File "C:\Users\orest\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\voice_client.py", line 199, in __init__
 raise RuntimeError("PyNaCl library needed in order to use voice")
RuntimeError: PyNaCl library needed in order to use voice

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
 File "C:\Users\orest\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\bot.py", line 939, in invoke
 await ctx.command.invoke(ctx)
 File "C:\Users\orest\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 863, in invoke
 await injected(*ctx.args, **ctx.kwargs)
 File "C:\Users\orest\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 94, in wrapped
 raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: RuntimeError: PyNaCl library needed in order to use voice



i cant really understand whats wrong, is there something with my code or i need more Python packages ?


-
Running ffmpeg on cmd works, but integrating it with PHP gives out an error
11 juin 2022, par digiboyRunning ffmpeg to covert files to mp4 works normally when ran from a command line prompt, but
upon trying to integrate it into a php code I keep getting errors and I am not sure why that is. The error says :


'-i' is not recognized as an internal or external command,
operable program or batch file.
Upload failed 



This is the function that is responsible for running ffmpeg code that converts the file :


public function convertVideoToMp4($tempFilePath, $finalFilePath) {
 $cmd = "$this->ffmpegPath -i $tempFilePath $finalFilePath 2>&1";

 $outputLog = array();
 exec($cmd, $outputLog, $returnCode);

 if($returnCode != 0) {
 //Command failed
 foreach($outputLog as $line) {
 echo $line . "<br />";
 }
 return false;
 }

 return true;
}



and since my code is returning an error pointing to a command line command being faulty, I am guessing it is triggering the
echo $line . "<br />";
from the function above.
However, right under this error output, I have an errorUpload failed

which points to a different function in the program, mainly the one responsible for the upload of the file itself :

if(move_uploaded_file($videoData["tmp_name"], $tempFilePath)) {
 $finalFilePath = $targetDir . uniqid() . ".mp4";

 if(!$this->insertVideoData($videoUploadData, $finalFilePath)) {
 echo "Insert query failed\n";
 return false;
 }

 if(!$this->convertVideoToMp4($tempFilePath, $finalFilePath)) {
 echo "Upload failed\n";
 return false;
 }

 if(!$this->deleteFile($tempFilePath)) {
 echo "Upload failed\n";
 return false;
 }

 if(!$this->generateThumbnails($finalFilePath)) {
 echo "Upload failed - could not generate thumbnails\n";
 return false;
 }

 }



But even though I get the output saying Upload failed, my file DOES get transfered into the folder that is dedicated as the "Upload folder" but the file is NOT converted from flv to mp4 before being uploaded, so I am left very confused.


For those who are wondering what the whole code looks like, this is VideoProcessor.php :


<?php
class VideoProcessor {

 private $con;
 private $sizeLimit = 500000000;
 private $allowedTypes = array("mp4", "flv", "webm", "mkv", "vob", "ogv", "ogg", "avi", "wmv", "mov", "mpeg", "mpg");

 private $ffmpegPath;

 private $ffprobePath;

 public function __construct($con) {
 $this->con = $con;
 $this->ffmpegPath = realpath("C:\Program Files\ffmpeg\bin\ffmpeg");
 $this->ffprobePath = realpath("C:\Program Files\ffmpeg\bin\ffprobe");

 }

 public function upload($videoUploadData) {

 $targetDir = "uploads/videos/";
 $videoData = $videoUploadData->videoDataArray;

 $tempFilePath = $targetDir . uniqid() . basename($videoData["name"]);
 $tempFilePath = str_replace(" ", "_", $tempFilePath);

 $isValidData = $this->processData($videoData, $tempFilePath);

 if(!$isValidData) {
 return false;
 }

 if(move_uploaded_file($videoData["tmp_name"], $tempFilePath)) {
 $finalFilePath = $targetDir . uniqid() . ".mp4";

 if(!$this->insertVideoData($videoUploadData, $finalFilePath)) {
 echo "Insert query failed\n";
 return false;
 }

 if(!$this->convertVideoToMp4($tempFilePath, $finalFilePath)) {
 echo "Upload failed\n";
 return false;
 }

 if(!$this->deleteFile($tempFilePath)) {
 echo "Upload failed\n";
 return false;
 }

 if(!$this->generateThumbnails($finalFilePath)) {
 echo "Upload failed - could not generate thumbnails\n";
 return false;
 }

 }
 }

 private function processData($videoData, $filePath) {
 $videoType = pathInfo($filePath, PATHINFO_EXTENSION);

 if(!$this->isValidSize($videoData)) {
 echo "File too large. Can't be more than " . $this->sizeLimit . " bytes";
 return false;
 }
 else if(!$this->isValidType($videoType)) {
 echo "Invalid file type";
 return false;
 }
 else if($this->hasError($videoData)) {
 echo "Error code: " . $videoData["error"];
 return false;
 }

 return true;
 }

 private function isValidSize($data) {
 return $data["size"] <= $this->sizeLimit;
 }

 private function isValidType($type) {
 $lowercased = strtolower($type);
 return in_array($lowercased, $this->allowedTypes);
 }

 private function hasError($data) {
 return $data["error"] != 0;
 }

 private function insertVideoData($uploadData, $filePath) {
 $query = $this->con->prepare("INSERT INTO videos(title, uploadedBy, description, privacy, category, filePath)
 VALUES(:title, :uploadedBy, :description, :privacy, :category, :filePath)");

 $query->bindParam(":title", $uploadData->title);
 $query->bindParam(":uploadedBy", $uploadData->uploadedBy);
 $query->bindParam(":description", $uploadData->description);
 $query->bindParam(":privacy", $uploadData->privacy);
 $query->bindParam(":category", $uploadData->category);
 $query->bindParam(":filePath", $filePath);

 return $query->execute();
 }

 public function convertVideoToMp4($tempFilePath, $finalFilePath) {
 $cmd = "$this->ffmpegPath -i $tempFilePath $finalFilePath 2>&1";

 $outputLog = array();
 exec($cmd, $outputLog, $returnCode);

 if($returnCode != 0) {
 //Command failed
 foreach($outputLog as $line) {
 echo $line . "<br />";
 }
 return false;
 }

 return true;
 }

 private function deleteFile($filePath) {
 if(!unlink($filePath)) {
 echo "Could not delete file\n";
 return false;
 }

 return true;
 }

 public function generateThumbnails($filePath) {

 $thumbnailSize = "210x118";
 $numThumbnails = 3;
 $pathToThumbnail = "uploads/videos/thumbnails";

 $duration = $this->getVideoDuration($filePath);

 echo "duration: $duration";
 }

 private function getVideoDuration($filePath) {
 return shell_exec("$this->ffprobePath -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 $filePath");
 }
}
?>



-
Pycord Music Bot : AttributeError : 'FFmpegAudio' object has no attribute '_process'
5 juin 2022, par Steven MaoI've made a discord Cog that should be able to queue up and play music, but I'm getting an error from FFmpeg when I actually try to play the URL. I have found an identical question on StackOverflow, but this user's problem was a random typo. The inputs should all be correct, so I am not sure if the problem is my code or my package.


What have I done wrong ?


class MusicClass(commands.Cog):
 #universal attributes
 YDL_OPTIONS = {'format': 'bestaudio', 'noplaylist': 'True'}
 FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}

 def __init__(self, bot):
 self.bot = bot
 self.is_playing = False
 self.music_queue = [[],''] #[[music1, music2, music3...], channel_obj]
 self.vc = ''

 @commands.command()
 async def join(self, ctx):
 if not ctx.message.author.voice:
 await ctx.send("{} is not connected to a voice channel".format(ctx.message.author.name))
 return
 else:
 channel = ctx.message.author.voice.channel
 await channel.connect()

 @commands.command()
 async def leave(self, ctx):
 voice_client = ctx.message.guild.voice_client
 if voice_client.is_connected():
 await voice_client.disconnect()
 else:
 await ctx.send("The bot is not connected to a voice channel.")
 
 #rtype: list[dict{str:}]
 #params: search string/web URL, top number of results to show
 #returns list of top 5 queries and their information
 def search_yt(self, search_query, num_results = 3):
 with YoutubeDL(self.YDL_OPTIONS) as ydl:
 try:
 top_results = ydl.extract_info(f"ytsearch{num_results}:{search_query}", download=False)['entries'][0:{num_results}]
 for i in range(len(top_results)):
 top_results[i] = {
 'title': top_results[i]['title'],
 'source': top_results[i]['formats'][0]['url'],
 'channel': top_results[i]['channel'],
 'duration': top_results[i]['duration'],
 'url': top_results[i]['webpage_url']
 }
 except:
 print(f'SEARCH_YT ERROR\t search="{search_query}"')
 return False
 return top_results
 
 #rtype: None
 #looks at queue, decides whether to play the next song in queue or stop
 def play_next(self):
 print('called play_next')
 if len(self.music_queue) > 0:
 self.is_playing = True
 #assigns url AND removes from queue
 music_url = self.music_queue[0][0]['source']
 self.music_queue[0].pop(0)
 self.vc.play(discord.FFmpegAudio(music_url, **self.FFMPEG_OPTIONS), after = lambda e: self.play_next())
 else:
 self.is_playing = False

 #rtype: None
 #similar to play_next but optimized for first-time playing
 #checks if a song in queue + checks if bot's connected, then begins to play
 async def play_now(self):
 print('called play_now, queue:', self.music_queue[0])
 if len(self.music_queue) > 0:
 self.is_playing = True
 music_url = self.music_queue[0][0]['source']
 if self.vc == '' or not self.vc.is_connected():
 self.vc = await self.music_queue[1].connect()
 else:
 print('moving to new channel')
 self.vc = await self.bot.move_to(self.music_queue[1])
 self.music_queue[0].pop(0)

 #######################################################################################################
 print('ERROR HAPPENS RIGHT HERE')
 self.vc.play(discord.FFmpegAudio(music_url, **self.FFMPEG_OPTIONS), after = lambda e: self.play_next())
 #######################################################################################################
 
 else:
 self.is_playing = False

 @commands.command()
 #dynamically checks for URL link or search query, then attempts to play
 async def p(self, ctx, *args):
 voice_channel = ctx.author.voice.channel

 if voice_channel == None: #not in a VC
 await ctx.send('You have to be in a voice channel first')
 return
 else: #set channel, search and play music
 if self.music_queue[1] != voice_channel:
 self.music_queue[1] = voice_channel
 if args[0].startswith('https://www.youtube.com/watch'): #search URL
 #search web_url directly and send object to music queue
 with YoutubeDL(self.YDL_OPTIONS) as ydl:
 try:
 print('attempting to extract URL:', args[0])
 music_obj = ydl.extract_info(args[0], download=False)
 music_obj = {
 'title': music_obj['title'],
 'source': music_obj['formats'][0]['url'],
 'channel': music_obj['channel'],
 'duration': music_obj['duration'],
 'url': music_obj['webpage_url']
 }
 print('music object:', music_obj)
 print('appending URL song queue')
 self.music_queue[0].append(music_obj)
 except:
 print('URL search failed. URL =', args[0])
 else: #search query, display search results, ask for which one, then add to queue
 num_results = args[len(args)-1] if args[len(args)-1].isdigit() else 3
 song_list = self.search_yt(' '.join(args), num_results)
 
 if not self.is_playing:
 await self.play_now()



Now my error message...


Exception ignored in: <function at="at" 0x7ff4b0a5b5e0="0x7ff4b0a5b5e0">
Traceback (most recent call last):
 File "/home/stevenmao/.local/lib/python3.8/site-packages/discord/player.py", line 127, in __del__
 self.cleanup()
 File "/home/stevenmao/.local/lib/python3.8/site-packages/discord/player.py", line 247, in cleanup
 self._kill_process()
 File "/home/stevenmao/.local/lib/python3.8/site-packages/discord/player.py", line 198, in _kill_process
 proc = self._process
AttributeError: 'FFmpegAudio' object has no attribute '_process'
</function>