
Recherche avancée
Médias (1)
-
The Great Big Beautiful Tomorrow
28 octobre 2011, par
Mis à jour : Octobre 2011
Langue : English
Type : Texte
Autres articles (110)
-
Websites made with MediaSPIP
2 mai 2011, parThis page lists some websites based on MediaSPIP.
-
Possibilité de déploiement en ferme
12 avril 2011, parMediaSPIP peut être installé comme une ferme, avec un seul "noyau" hébergé sur un serveur dédié et utilisé par une multitude de sites différents.
Cela permet, par exemple : de pouvoir partager les frais de mise en œuvre entre plusieurs projets / individus ; de pouvoir déployer rapidement une multitude de sites uniques ; d’éviter d’avoir à mettre l’ensemble des créations dans un fourre-tout numérique comme c’est le cas pour les grandes plate-formes tout public disséminées sur le (...) -
La gestion des forums
3 novembre 2011, parSi les forums sont activés sur le site, les administrateurs ont la possibilité de les gérer depuis l’interface d’administration ou depuis l’article même dans le bloc de modification de l’article qui se trouve dans la navigation de la page.
Accès à l’interface de modération des messages
Lorsqu’il est identifié sur le site, l’administrateur peut procéder de deux manières pour gérer les forums.
S’il souhaite modifier (modérer, déclarer comme SPAM un message) les forums d’un article particulier, il a à sa (...)
Sur d’autres sites (8309)
-
Discord bot returns ffmpeg error despite being added to PATH
22 février 2024, par SamI am creating a Discord bot to play music via Youtube as practice with APIs. Every time I run the command to play a Youtube video I am met with "ffmpeg was not found". I have downloaded ffmpeg (as I'm on Windows) and moved the folder to my C : drive. Once done, I've added it to the path within environment variables. The error persists.


- 

- I've added ffmpeg to my PATH as described in this video.
- Additionally, I've found forums where the suggested answer is to add ffmpeg to your PATH.






In command prompt, if I type "ffmpeg" it returns "'FFmpeg' is not recognized as an internal or external command, operable program or batch file."


Here is my code :


from typing import Final
import os
from dotenv import load_dotenv
from discord import Intents, Client, Message
from responses import get_response
import asyncio
import yt_dlp
import discord

#Step 0: Load our token from somewhere safe
load_dotenv()
#Final decorator makes it so that this cannot be overwritten or have subclasses
TOKEN: Final[str] = os.getenv('DISCORD_TOKEN')


voice_clients = {}
#Settings for the video download.
yt_dl_opts = {'format': 'bestaudio/best'}
ytdl = yt_dlp.YoutubeDL(yt_dl_opts)

#Settings for ffmpeg. 
ffmpeg_options = {'options': '-vn'}

# Step 1: Bot Setup - activate intents
intents: Intents = Intents.default()
intents.message_content = True #NOQA
client: Client = Client(intents=intents)

#Step 2: Message Functionality
async def send_message(message: Message, user_message: str):
 if not user_message:
 print('Message was empty because intents were not enabled... probably')
 return
 
 # The := "Walrus Operator" is used to prompt for input.
 if is_private := user_message[0] == '?':
 user_message = user_message[1:]
 
 try:
 response: str = get_response(user_message)
 await message.author.send(response) if is_private else await message.channel.send(response)
 except Exception as e:
 print(e)

#Step 3: Handling the startup for our bot.
 
@client.event
async def on_ready() -> None:
 print(f"{client.user} is now running")

#Step 4: Handle incoming messages
@client.event
async def on_message(message: Message) -> None:
 if message.author == client.user:
 return
 
 username: str = str(message.author)
 user_message: str = message.content
 channel: str = str(message.channel)

 print(f"[{channel}] {username}: '{user_message}")
 await send_message(message, user_message)

 if message.content.startswith("!play"):
 try:
 url = message.content.split()[1]
 
 #Handles the voice connection that a bot has to a certain channel
 voice_client = await message.author.voice.channel.connect()
 voice_clients[voice_client.guild.id] = voice_client

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

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

 voice_client.play(player)



 except Exception as err:
 print(err)

# Step 5: Main entry point
def main() -> None:
 client.run(token=TOKEN)

if __name__ == '__main__':
 main()```



-
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 fix Error 'FFmpegPCMAudio' object has no attribute '_process'
30 novembre 2023, par Ma Mefrom ast import alias
import discord
from discord.ext import commands
from youtubesearchpython import VideosSearch
from yt_dlp import YoutubeDL
import asyncio

class music_cog(commands.Cog):
 def __init__(self, bot):
 self.bot = bot
 
 #all the music related stuff
 self.is_playing = False
 self.is_paused = False

 # 2d array containing [song, channel]
 self.music_queue = []
 self.YDL_OPTIONS = {'format': 'bestaudio/best'}
 self.FFMPEG_OPTIONS = {'options': '-vn'}

 self.vc = None
 self.ytdl = YoutubeDL(self.YDL_OPTIONS)

 #searching the item on youtube
 def search_yt(self, item):
 if item.startswith("https://"):
 title = self.ytdl.extract_info(item, download=False)["title"]
 return{'source':item, 'title':title}
 search = VideosSearch(item, limit=1)
 return{'source':search.result()["result"][0]["link"], 'title':search.result()["result"][0]["title"]}

 async def play_next(self):
 if len(self.music_queue) > 0:
 self.is_playing = True

 #get the first url
 m_url = self.music_queue[0][0]['source']

 #remove the first element as you are currently playing it
 self.music_queue.pop(0)
 loop = asyncio.get_event_loop()
 data = await loop.run_in_executor(None, lambda: self.ytdl.extract_info(m_url, download=False))
 song = data['url']
 self.vc.play(discord.FFmpegPCMAudio(song, executable= "ffmpeg.exe", **self.FFMPEG_OPTIONS), after=lambda e: asyncio.run_coroutine_threadsafe(self.play_next(), self.bot.loop))
 
 else:
 self.is_playing = False

 # infinite loop checking 
 async def play_music(self, ctx):
 if len(self.music_queue) > 0:
 self.is_playing = True

 m_url = self.music_queue[0][0]['source']
 #try to connect to voice channel if you are not already connected
 if self.vc == None or not self.vc.is_connected():
 self.vc = await self.music_queue[0][1].connect()

 #in case we fail to connect
 if self.vc == None:
 await ctx.send("```Could not connect to the voice channel```")
 return
 else:
 await self.vc.move_to(self.music_queue[0][1])
 #remove the first element as you are currently playing it
 self.music_queue.pop(0)
 loop = asyncio.get_event_loop()
 data = await loop.run_in_executor(None, lambda: self.ytdl.extract_info(m_url, download=False))
 song = data['url']
 self.vc.play(discord.FFmpegPCMAudio(song, executable= "ffmpeg.exe", **self.FFMPEG_OPTIONS), after=lambda e: asyncio.run_coroutine_threadsafe(self.play_next(), self.bot.loop,))
 else:
 self.is_playing = False

 @commands.command(name="play", aliases=["p","playing"], help="Plays a selected song from youtube")
 async def play(self, ctx, *args):
 query = " ".join(args)
 try:
 voice_channel = ctx.author.voice.channel
 except:
 await ctx.send("```You need to connect to a voice channel first!```")
 return
 if self.is_paused:
 self.vc.resume()
 else:
 song = self.search_yt(query)
 if type(song) == type(True):
 await ctx.send("```Could not download the song. Incorrect format try another keyword. This could be due to playlist or a livestream format.```")
 else:
 if self.is_playing:
 await ctx.send(f"**#{len(self.music_queue)+2} -'{song['title']}'** added to the queue") 
 else:
 await ctx.send(f"**'{song['title']}'** added to the queue") 
 self.music_queue.append([song, voice_channel])
 if self.is_playing == False:
 await self.play_music(ctx)


 @commands.command(name="pause", help="Pauses the current song being played")
 async def pause(self, ctx, *args):
 if self.is_playing:
 self.is_playing = False
 self.is_paused = True
 self.vc.pause()
 if self.is_paused:
 self.vc.resume()
 self.is_playing = True
 self.is_paused = False

 @commands.command(name = "resume", aliases=["r"], help="Resumes playing with the discord bot")
 async def resume(self, ctx, *args):
 if self.is_paused:
 self.is_paused = False
 self.is_playing = True
 self.vc.resume()

 @commands.command(name="skip", aliases=["s"], help="Skips the current song being played")
 async def skip(self, ctx):
 if self.vc != None and self.vc:
 self.vc.stop()
 #try to play next in the queue if it exists
 await self.play_music(ctx)


 @commands.command(name="queue", aliases=["q"], help="Displays the current songs in queue")
 async def queue(self, ctx):
 retval = ""
 for i in range(0, len(self.music_queue)):
 retval += f"#{i+1} -" + self.music_queue[i][0]['title'] + "\n"

 if retval != "":
 await ctx.send(f"```queue:\n{retval}```")
 else:
 await ctx.send("```No music in queue```")

 @commands.command(name="clear", aliases=["c", "bin"], help="Stops the music and clears the queue")
 async def clear(self, ctx):
 if self.vc != None and self.is_playing:
 self.vc.stop()
 self.music_queue = []
 await ctx.send("```Music queue cleared```")

 @commands.command(name="stop", aliases=["disconnect", "l", "d"], help="Kick the bot from VC")
 async def dc(self, ctx):
 self.is_playing = False
 self.is_paused = False
 await self.vc.disconnect()
 
 @commands.command(name="remove", help="Removes last song added to queue")
 async def re(self, ctx):
 self.music_queue.pop()
 await ctx.send("```last song removed```")



I think everything is good but there is no sound Can you give me some advice ?

it python code