Recherche avancée

Médias (1)

Mot : - Tags -/book

Autres articles (110)

  • Websites made ​​with MediaSPIP

    2 mai 2011, par

    This page lists some websites based on MediaSPIP.

  • Possibilité de déploiement en ferme

    12 avril 2011, par

    MediaSPIP 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, par

    Si 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 Sam

    I 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ık

    I 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")]&#xA;public async Task<iactionresult> ConvertVideoToMp3(Mp3 data)&#xA;{&#xA;    try&#xA;    {&#xA;        string videoId = GetYoutubeVideoId(data.VideoUrl);&#xA;&#xA;        var streamInfoSet = await _youtubeClient.Videos.Streams.GetManifestAsync(videoId);&#xA;        var videoStreamInfo = streamInfoSet.GetAudioOnlyStreams().GetWithHighestBitrate();&#xA;&#xA;        if (videoStreamInfo != null)&#xA;        {&#xA;            var videoStream = await _youtubeClient.Videos.Streams.GetAsync(videoStreamInfo);&#xA;            var memoryStream = new MemoryStream();&#xA;&#xA;            await videoStream.CopyToAsync(memoryStream);&#xA;            memoryStream.Seek(0, SeekOrigin.Begin);&#xA;&#xA;            var videoFilePath = $"{videoId}.mp4";&#xA;            await System.IO.File.WriteAllBytesAsync(videoFilePath, memoryStream.ToArray());&#xA;&#xA;            var mp3FilePath = $"{videoId}.mp3";&#xA;            var ffmpegProcess = Process.Start(new ProcessStartInfo&#xA;            {&#xA;                FileName = "ffmpeg",&#xA;                Arguments = $"-i \"{videoFilePath}\" -vn -acodec libmp3lame -ab 128k -id3v2_version 3 -metadata artist=\"YourArtistName\" -metadata title=\"YourTitle\" -metadata from=\"youtube\" \"{mp3FilePath}\"",&#xA;                RedirectStandardError = true,&#xA;                UseShellExecute = false,&#xA;                CreateNoWindow = true&#xA;            });&#xA;&#xA;            await ffmpegProcess.WaitForExitAsync();&#xA;&#xA;            var file = TagLib.File.Create(mp3FilePath);&#xA;&#xA;   &#xA;            file.Tag.Artists = new string [] { "YourArtistName"};&#xA;            file.Tag.Title = "YourTitle";&#xA;            file.Tag.Album = "YourAlbumName"; &#xA;            file.Tag.Comment = "Source: youtube";&#xA;  &#xA;&#xA;            file.Save();&#xA;&#xA;            var mp3Bytes = await System.IO.File.ReadAllBytesAsync(mp3FilePath);&#xA;&#xA;            System.IO.File.Delete(videoFilePath);&#xA;            System.IO.File.Delete(mp3FilePath);&#xA;&#xA;            return File(mp3Bytes, "audio/mpeg", $"{videoId}.mp3");&#xA;        }&#xA;        else&#xA;        {&#xA;            return NotFound("Video stream not found");&#xA;        }&#xA;    }&#xA;    catch (Exception ex)&#xA;    {&#xA;        return StatusCode(500, $"An error occurred: {ex.Message}");&#xA;    }&#xA;}&#xA;</iactionresult>

    &#xA;

    React Native :

    &#xA;

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

    &#xA;

  • how to fix Error 'FFmpegPCMAudio' object has no attribute '_process'

    30 novembre 2023, par Ma Me
    from ast import alias&#xA;import discord&#xA;from discord.ext import commands&#xA;from youtubesearchpython import VideosSearch&#xA;from yt_dlp import YoutubeDL&#xA;import asyncio&#xA;&#xA;class music_cog(commands.Cog):&#xA;    def __init__(self, bot):&#xA;        self.bot = bot&#xA;    &#xA;        #all the music related stuff&#xA;        self.is_playing = False&#xA;        self.is_paused = False&#xA;&#xA;        # 2d array containing [song, channel]&#xA;        self.music_queue = []&#xA;        self.YDL_OPTIONS = {&#x27;format&#x27;: &#x27;bestaudio/best&#x27;}&#xA;        self.FFMPEG_OPTIONS = {&#x27;options&#x27;: &#x27;-vn&#x27;}&#xA;&#xA;        self.vc = None&#xA;        self.ytdl = YoutubeDL(self.YDL_OPTIONS)&#xA;&#xA;     #searching the item on youtube&#xA;    def search_yt(self, item):&#xA;        if item.startswith("https://"):&#xA;            title = self.ytdl.extract_info(item, download=False)["title"]&#xA;            return{&#x27;source&#x27;:item, &#x27;title&#x27;:title}&#xA;        search = VideosSearch(item, limit=1)&#xA;        return{&#x27;source&#x27;:search.result()["result"][0]["link"], &#x27;title&#x27;:search.result()["result"][0]["title"]}&#xA;&#xA;    async def play_next(self):&#xA;        if len(self.music_queue) > 0:&#xA;            self.is_playing = True&#xA;&#xA;            #get the first url&#xA;            m_url = self.music_queue[0][0][&#x27;source&#x27;]&#xA;&#xA;            #remove the first element as you are currently playing it&#xA;            self.music_queue.pop(0)&#xA;            loop = asyncio.get_event_loop()&#xA;            data = await loop.run_in_executor(None, lambda: self.ytdl.extract_info(m_url, download=False))&#xA;            song = data[&#x27;url&#x27;]&#xA;            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))&#xA;            &#xA;        else:&#xA;            self.is_playing = False&#xA;&#xA;    # infinite loop checking &#xA;    async def play_music(self, ctx):&#xA;        if len(self.music_queue) > 0:&#xA;            self.is_playing = True&#xA;&#xA;            m_url = self.music_queue[0][0][&#x27;source&#x27;]&#xA;            #try to connect to voice channel if you are not already connected&#xA;            if self.vc == None or not self.vc.is_connected():&#xA;                self.vc = await self.music_queue[0][1].connect()&#xA;&#xA;                #in case we fail to connect&#xA;                if self.vc == None:&#xA;                    await ctx.send("```Could not connect to the voice channel```")&#xA;                    return&#xA;            else:&#xA;                await self.vc.move_to(self.music_queue[0][1])&#xA;            #remove the first element as you are currently playing it&#xA;            self.music_queue.pop(0)&#xA;            loop = asyncio.get_event_loop()&#xA;            data = await loop.run_in_executor(None, lambda: self.ytdl.extract_info(m_url, download=False))&#xA;            song = data[&#x27;url&#x27;]&#xA;            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,))&#xA;        else:&#xA;            self.is_playing = False&#xA;&#xA;    @commands.command(name="play", aliases=["p","playing"], help="Plays a selected song from youtube")&#xA;    async def play(self, ctx, *args):&#xA;        query = " ".join(args)&#xA;        try:&#xA;            voice_channel = ctx.author.voice.channel&#xA;        except:&#xA;            await ctx.send("```You need to connect to a voice channel first!```")&#xA;            return&#xA;        if self.is_paused:&#xA;            self.vc.resume()&#xA;        else:&#xA;            song = self.search_yt(query)&#xA;            if type(song) == type(True):&#xA;                await ctx.send("```Could not download the song. Incorrect format try another keyword. This could be due to playlist or a livestream format.```")&#xA;            else:&#xA;                if self.is_playing:&#xA;                    await ctx.send(f"**#{len(self.music_queue)&#x2B;2} -&#x27;{song[&#x27;title&#x27;]}&#x27;** added to the queue") &#xA;                else:&#xA;                    await ctx.send(f"**&#x27;{song[&#x27;title&#x27;]}&#x27;** added to the queue")  &#xA;                self.music_queue.append([song, voice_channel])&#xA;                if self.is_playing == False:&#xA;                    await self.play_music(ctx)&#xA;&#xA;&#xA;    @commands.command(name="pause", help="Pauses the current song being played")&#xA;    async def pause(self, ctx, *args):&#xA;        if self.is_playing:&#xA;            self.is_playing = False&#xA;            self.is_paused = True&#xA;            self.vc.pause()&#xA;        if self.is_paused:&#xA;            self.vc.resume()&#xA;            self.is_playing = True&#xA;            self.is_paused = False&#xA;&#xA;    @commands.command(name = "resume", aliases=["r"], help="Resumes playing with the discord bot")&#xA;    async def resume(self, ctx, *args):&#xA;        if self.is_paused:&#xA;            self.is_paused = False&#xA;            self.is_playing = True&#xA;            self.vc.resume()&#xA;&#xA;    @commands.command(name="skip", aliases=["s"], help="Skips the current song being played")&#xA;    async def skip(self, ctx):&#xA;        if self.vc != None and self.vc:&#xA;            self.vc.stop()&#xA;            #try to play next in the queue if it exists&#xA;            await self.play_music(ctx)&#xA;&#xA;&#xA;    @commands.command(name="queue", aliases=["q"], help="Displays the current songs in queue")&#xA;    async def queue(self, ctx):&#xA;        retval = ""&#xA;        for i in range(0, len(self.music_queue)):&#xA;            retval &#x2B;= f"#{i&#x2B;1} -" &#x2B; self.music_queue[i][0][&#x27;title&#x27;] &#x2B; "\n"&#xA;&#xA;        if retval != "":&#xA;            await ctx.send(f"```queue:\n{retval}```")&#xA;        else:&#xA;            await ctx.send("```No music in queue```")&#xA;&#xA;    @commands.command(name="clear", aliases=["c", "bin"], help="Stops the music and clears the queue")&#xA;    async def clear(self, ctx):&#xA;        if self.vc != None and self.is_playing:&#xA;            self.vc.stop()&#xA;        self.music_queue = []&#xA;        await ctx.send("```Music queue cleared```")&#xA;&#xA;    @commands.command(name="stop", aliases=["disconnect", "l", "d"], help="Kick the bot from VC")&#xA;    async def dc(self, ctx):&#xA;        self.is_playing = False&#xA;        self.is_paused = False&#xA;        await self.vc.disconnect()&#xA;    &#xA;    @commands.command(name="remove", help="Removes last song added to queue")&#xA;    async def re(self, ctx):&#xA;        self.music_queue.pop()&#xA;        await ctx.send("```last song removed```")&#xA;

    &#xA;

    I think everything is good but there is no sound Can you give me some advice ?
    &#xA;it python code

    &#xA;