Recherche avancée

Médias (0)

Mot : - Tags -/formulaire

Aucun média correspondant à vos critères n’est disponible sur le site.

Autres articles (39)

  • Les autorisations surchargées par les plugins

    27 avril 2010, par

    Mediaspip core
    autoriser_auteur_modifier() afin que les visiteurs soient capables de modifier leurs informations sur la page d’auteurs

  • Des sites réalisés avec MediaSPIP

    2 mai 2011, par

    Cette page présente quelques-uns des sites fonctionnant sous MediaSPIP.
    Vous pouvez bien entendu ajouter le votre grâce au formulaire en bas de page.

  • Librairies et binaires spécifiques au traitement vidéo et sonore

    31 janvier 2010, par

    Les logiciels et librairies suivantes sont utilisées par SPIPmotion d’une manière ou d’une autre.
    Binaires obligatoires FFMpeg : encodeur principal, permet de transcoder presque tous les types de fichiers vidéo et sonores dans les formats lisibles sur Internet. CF ce tutoriel pour son installation ; Oggz-tools : outils d’inspection de fichiers ogg ; Mediainfo : récupération d’informations depuis la plupart des formats vidéos et sonores ;
    Binaires complémentaires et facultatifs flvtool2 : (...)

Sur d’autres sites (8550)

  • Why is my DSharpPlus Slash Command not playing my desired sound using FFMPEG in C# ?

    19 mai 2023, par IngeniousThoughts

    I'm having a problem with my ffmpeg setup the commands work fine but my play command doesn't play my desired sound.

    


    //The command.
        [SlashCommand("play", "plays a sound in a voice channel.")]
        public async Task HowlCommand(InteractionContext ctx, [Choice("ChoiceName", "C:\\My\\Program\\Directory\\Name\\MySound.mp3")]
                                                             [Option("Sound", "Please select a Sound")] string filepath)
        {
            //Creates a slash command used response.
            //Also removes the error message.
            await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder()
                                                                                                                    .WithContent("Playing sound in voice channel. Please wait just a moment!"));
 
            //Checks if the user is not a bot to send the message.
            if (ctx.Member.IsBot)
            {
                return;
            }
            else
            {
                if(filepath != "C:\\My\\Program\\Directory\\Name\\MySound.mp3")
                {
                    var embedmessage = new DiscordMessageBuilder()
                        .AddEmbed(new DiscordEmbedBuilder()
 
                        .WithAuthor("BotName", null, ctx.Client.CurrentApplication.Icon)
                        .WithTitle("Please select the following sound to play:")
                        .WithImageUrl(ctx.Client.CurrentApplication.Icon)
                        .WithFooter("VoiceChannel Error.", "ImageURL.png")
                        .WithTimestamp(DateTime.Now)
                        .Build()
 
                        );
 
                    //Makes the command wait 5 seconds before sending the rest of the command data.
                    await Task.Delay(TimeSpan.FromSeconds(5));
 
                    //Sends the embed in a message.
                    await ctx.Channel.SendMessageAsync(embedmessage);
                }
                else
                {
                    //Makes the command wait 5 seconds before sending the rest of the command data.
                    await Task.Delay(TimeSpan.FromSeconds(5));
 
 
                    var vnext = ctx.Client.GetVoiceNext();
                    var vnc = vnext.GetConnection(ctx.Guild);
                    
                    //if null throws exception.
                    if (vnc == null)
                        throw new System.InvalidOperationException("Not connected in this guild.");
 
 
                    //Gets the mp3 file to use.
                    var ffmpeg = Process.Start(new ProcessStartInfo
                    {
                        FileName = "ffmpeg",
                        Arguments = $@"-i ""{filepath}"" -ac 2 -f s16le -ar 48000 pipe:1",
                        RedirectStandardOutput = true,
                        UseShellExecute = false
                    });
                    Stream pcm = ffmpeg.StandardOutput.BaseStream;
 
                    VoiceTransmitSink transmit = vnc.GetTransmitSink();
                    await pcm.CopyToAsync(transmit);
                    vnc.GetTransmitSink().VolumeModifier = 5;
 
                    //Makes the command wait 10 seconds before sending the rest of the command data.
                    await Task.Delay(TimeSpan.FromSeconds(10));
 
                    //Disconnects the bot from the voice channel.
                    vnc.Disconnect();
                }
            }
        }


    


    //The command.
        [SlashCommand("join", "Joins a voice channel.")]
        public async Task JoinChannel(InteractionContext ctx, [Choice("MyVoiceChannel", "VoiceChannelName")]
                                                             [Option("VoiceChannel", "Please choose a Voice Channel.")] DiscordChannel channel)
        {
            //Creates a slash command used response.
            //Also removes the error message.
            await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder()
                                                                                                                    .WithContent("Joining voice channel. Please wait just a moment!"));
 
            //Checks if the user is not a bot to send the message.
            if (ctx.Member.IsBot)
            {
                return;
            }
            else
            {
                if (channel.Name != "MyVoiceChannelName")
                {
                    var embedmessage = new DiscordMessageBuilder()
                        .AddEmbed(new DiscordEmbedBuilder()
 
                        .WithAuthor("BotName", null, ctx.Client.CurrentApplication.Icon)
                        .WithTitle("Please Create The Following Voice Channel:")
                        .WithImageUrl(ctx.Client.CurrentApplication.Icon)
                        .AddField("VoiceChannel:", "**BotName**" + Environment.NewLine + "Is Case Sensitive: **Yes**")
                        .WithFooter("VoiceChannel Error.", "ImageURL.png")
                        .WithTimestamp(DateTime.Now)
                        .Build()
 
                        );
 
                    //Makes the command wait 5 seconds before sending the rest of the command data.
                    await Task.Delay(TimeSpan.FromSeconds(5));
 
                    //Sends the embed in a message.
                    await ctx.Channel.SendMessageAsync(embedmessage);
                }
                else
                {
                    //Makes the command wait 5 seconds before sending the rest of the command data.
                    await Task.Delay(TimeSpan.FromSeconds(5));
 
 
                    channel = ctx.Member.VoiceState?.Channel;
                    await channel.ConnectAsync();
 
                }
            }
        }
 
    }
}


    


    public sealed class Program&#xA;    {&#xA;        public static DiscordClient Client { get; private set; }&#xA;        public static InteractivityExtension Interactivity { get; private set; }&#xA;        public static CommandsNextExtension Commands { get; private set; }&#xA;        public static VoiceNextExtension VoiceNext { get; private set; }&#xA; &#xA; &#xA;        static async Task Main(string[] args)&#xA;        {&#xA; &#xA;            //Main Window configs specifying the title name and color.&#xA;            Console.BackgroundColor = ConsoleColor.Black;&#xA;            Console.ForegroundColor = ConsoleColor.Magenta;&#xA;            Console.Title = "BotName";&#xA; &#xA;            //1. Get the details of your config.json file by deserialising it&#xA;            var configJsonFile = new JSONReader();&#xA;            await configJsonFile.ReadJSON();&#xA; &#xA;            //2. Setting up the Bot Configuration&#xA;            var discordConfig = new DiscordConfiguration()&#xA;            {&#xA;                Intents = DiscordIntents.All,&#xA;                Token = configJsonFile.token,&#xA;                TokenType = TokenType.Bot,&#xA;                AutoReconnect = true&#xA;            };&#xA; &#xA;            //3. Apply this config to our DiscordClient&#xA;            Client = new DiscordClient(discordConfig);&#xA; &#xA;            //4. Set the default timeout for Commands that use interactivity&#xA;            Client.UseInteractivity(new InteractivityConfiguration()&#xA;            {&#xA;                Timeout = TimeSpan.FromMinutes(2)&#xA;            });&#xA; &#xA;            //5. Set up the Task Handler Ready event&#xA;            Client.Ready &#x2B;= OnClientReady;&#xA; &#xA;            //6. Set up the Commands Configuration&#xA;            var commandsConfig = new CommandsNextConfiguration()&#xA;            {&#xA;                StringPrefixes = new string[] { configJsonFile.prefix },&#xA;                EnableMentionPrefix = true,&#xA;                EnableDms = true,&#xA;                EnableDefaultHelp = false,&#xA;            };&#xA; &#xA;            Commands = Client.UseCommandsNext(commandsConfig);&#xA; &#xA;            //7. Register your commands&#xA;            var slashCommandsConfig = Client.UseSlashCommands();&#xA;            slashCommandsConfig.RegisterCommands<mysoundscommand>(MyGuildID);&#xA; &#xA;            //8. Allows usage of voice channels.&#xA;            var VoiceNext = Client.UseVoiceNext();&#xA; &#xA;            //9. Connect to get the Bot online&#xA;            await Client.ConnectAsync();&#xA;            await Task.Delay(-1);&#xA;        }&#xA; &#xA;        private static Task OnClientReady(DiscordClient sender, ReadyEventArgs e)&#xA;        {&#xA;            return Task.CompletedTask;&#xA;        }&#xA;    }&#xA;</mysoundscommand>

    &#xA;

    SourceCode Link :

    &#xA;

    text

    &#xA;

    playing the playsound slash command but wasn't expecting it to not play the mp3 file.

    &#xA;

    everything else worked fine except when it transmits the sound it doesn't play it.

    &#xA;

  • Memory Leak in c++/cli application

    10 décembre 2013, par Ankush

    I am passing bitmap from my c# app to c++/cli dll that add it to video.
    The problem is program slowly leaking memory. I tried _CrtDumpMemoryLeaks() shows me leak of bitmap & another 40 byte leak but i am disposing bitmap.
    Can anyone see memory leak, Here is code..

    Flow :

    1) Capture screenshot by takescreenshot()

    2) pass it to c++/cli function

    3) dispose bitmap

    lines from my c# app

    Bitmap snap = takescreeshot();
    vencoder.AddBitmap(snap);
    snap.Dispose();
    vencoder.printleak();

    private static Bitmap takescreeshot()
       {
           System.Drawing.Bitmap bitmap = null;
           System.Drawing.Graphics graphics = null;

           bitmap = new Bitmap
           (
               System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width,
               System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height,
               System.Drawing.Imaging.PixelFormat.Format24bppRgb
           );

           graphics = System.Drawing.Graphics.FromImage(bitmap);

           graphics.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size);

           //Write TimeSpamp
           Rectangle rect = new Rectangle(1166, 738, 200, 20);
           String datetime= System.String.Format("{0:dd:MM:yy  hh:mm:ss}",DateTime.Now);
           System.Drawing.Font sysfont = new System.Drawing.Font("Times New Roman", 14, FontStyle.Bold);
           graphics.DrawString(datetime, sysfont, Brushes.Red,rect);
           //

           Grayscale filter = new Grayscale(0.2125, 0.7154, 0.0721);
           Bitmap grayImage = filter.Apply(bitmap);

           //Dispose
           bitmap.Dispose();
           graphics.Dispose();

           return grayImage;
       }

    now in c++/cli dll

    bool VideoEncoder::AddBitmap(Bitmap^ bitmap)
       {
           BitmapData^ bitmapData = bitmap->LockBits( System::Drawing::Rectangle( 0, 0,bitmap->Width, bitmap->Height ),ImageLockMode::ReadOnly,PixelFormat::Format8bppIndexed);
           uint8_t* ptr = reinterpret_cast( static_cast( bitmapData->Scan0 ) );
           uint8_t* srcData[4] = { ptr, NULL, NULL, NULL };
           int srcLinesize[4] = { bitmapData->Stride, 0, 0, 0 };

           pCurrentPicture = CreateFFmpegPicture(pVideoStream->codec->pix_fmt, pVideoStream->codec->width, pVideoStream->codec->height);

           sws_scale(pImgConvertCtx, srcData, srcLinesize, 0, bitmap->Height, pCurrentPicture->data, pCurrentPicture->linesize );

           bitmap->UnlockBits( bitmapData );

           write_video_frame();

           bitmapData=nullptr;
           ptr=NULL;

           return true;
       }

    AVFrame * VideoEncoder::CreateFFmpegPicture(int pix_fmt, int nWidth, int nHeight)
       {

         AVFrame *picture     = NULL;
         uint8_t *picture_buf = NULL;
         int size;

         picture = avcodec_alloc_frame();
         if ( !picture)
         {
           printf("Cannot create frame\n");
           return NULL;
         }

         size = avpicture_get_size((AVPixelFormat)pix_fmt, nWidth, nHeight);

         picture_buf = (uint8_t *) av_malloc(size);

         if (!picture_buf)
         {
           av_free(picture);
           printf("Cannot allocate buffer\n");
           return NULL;
         }

         avpicture_fill((AVPicture *)picture, picture_buf,
           (AVPixelFormat)pix_fmt, nWidth, nHeight);

         return picture;
       }

       void VideoEncoder::write_video_frame()
       {
           AVCodecContext* codecContext = pVideoStream->codec;

           int out_size, ret = 0;

           if ( pFormatContext->oformat->flags &amp; AVFMT_RAWPICTURE )
           {
               printf( "raw picture must be written" );
           }
           else
           {
               out_size = avcodec_encode_video( codecContext, pVideoEncodeBuffer,nSizeVideoEncodeBuffer, pCurrentPicture );

               if ( out_size > 0 )
               {
                   AVPacket packet;
                   av_init_packet( &amp;packet );

                   if ( codecContext->coded_frame->pts != AV_NOPTS_VALUE )
                   {
                       packet.pts = av_rescale_q( packet.pts, codecContext->time_base, pVideoStream->time_base );
                   }

                   if ( codecContext->coded_frame->pkt_dts != AV_NOPTS_VALUE )
                   {
                       packet.dts = av_rescale_q( packet.dts, codecContext->time_base, pVideoStream->time_base );
                   }

                   if ( codecContext->coded_frame->key_frame )
                   {
                       packet.flags |= AV_PKT_FLAG_KEY;
                   }

                   packet.stream_index = pVideoStream->index;
                   packet.data = pVideoEncodeBuffer;
                   packet.size = out_size;

                   ret = av_interleaved_write_frame( pFormatContext, &amp;packet );

                   av_free_packet(&amp;packet);
                   av_freep(pCurrentPicture);
               }
               else
               {
                   // image was buffered
               }
           }

           if ( ret != 0 )
           {
               throw gcnew Exception( "Error while writing video frame." );
           }
       }


       void VideoEncoder::printleak()
       {
           printf("No of leaks: %d",_CrtDumpMemoryLeaks());
           printf("\n");
       }
  • Is it feasible to create FFmpegFrameGrabber one by one for single FFmpegFrameRecorder and maintain video stream keep alive ?

    12 juillet 2023, par zhoutian

    The reason why I ask these question is I got byte [] of container data(name is dhav) one by one and I need to push that data continuously to RTMP to play。

    &#xA;

    What's the current progress I made ?

    &#xA;

    For now ,I can push data to RTMP and play RTMP by VLC just for few seconds,then the RTMP stream is end .

    &#xA;

    because the grabber created by inputstream only contain a few of the data come from ByteBuffer ,when that inputstream is end, the RTMP is closed.

    &#xA;

    synchronized (buffer) {&#xA;                                buffer.flip();&#xA;                                byte[] bytes = new byte[buffer.remaining()];&#xA;                                buffer.get(bytes);&#xA;                                buffer.clear();&#xA;                                isByteBufferFull[0] = false;&#xA;                                try {&#xA;                                    grabAndPush(bytes, SRS_PUSH_ADDRESS);&#xA;                                } catch (Exception e) {&#xA;                                    //throw new RuntimeException(e);&#xA;                                }&#xA;&#xA;                            }&#xA;

    &#xA;

    private static synchronized void grabAndPush(byte[] bytes, String pushAddress) throws Exception {&#xA;        avutil.av_log_set_level(avutil.AV_LOG_INFO);&#xA;        FFmpegLogCallback.set();&#xA;&#xA;        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(new ByteArrayInputStream(bytes));&#xA;...&#xA;}&#xA;

    &#xA;

    So can anyone tell me how to keep the RTMP aways alive by FFmpegFrameGrabber and FFmpegFrameRecorder when the source data come from one by one.&#xA;very appreciate 😃

    &#xA;

    this is my code :

    &#xA;

    import lombok.extern.slf4j.Slf4j;&#xA;import org.bytedeco.ffmpeg.avcodec.AVCodecParameters;&#xA;import org.bytedeco.ffmpeg.avformat.AVFormatContext;&#xA;import org.bytedeco.ffmpeg.avformat.AVStream;&#xA;import org.bytedeco.ffmpeg.global.avcodec;&#xA;import org.bytedeco.ffmpeg.global.avutil;&#xA;import org.bytedeco.javacv.FFmpegFrameGrabber;&#xA;import org.bytedeco.javacv.FFmpegFrameRecorder;&#xA;import org.bytedeco.javacv.FFmpegLogCallback;&#xA;import org.bytedeco.javacv.Frame;&#xA;import org.jfjy.ch2ji.ecctv.dh.api.ApiService;&#xA;import org.jfjy.ch2ji.ecctv.dh.callback.RealPlayCallback;&#xA;&#xA;import java.io.ByteArrayInputStream;&#xA;import java.nio.ByteBuffer;&#xA;import java.util.concurrent.ExecutorService;&#xA;import java.util.concurrent.Executors;&#xA;&#xA;@Slf4j&#xA;public class GetBytes2PushRTMPNew2 {&#xA;&#xA;    private static final String SRS_PUSH_ADDRESS = "rtmp://127.0.0.1:1935/live/livestream";&#xA;&#xA;    static int BUFFER_CAPACITY = 1 * 1024 * 1024;&#xA;&#xA;    public static void main(String[] args) throws Exception {&#xA;        FFmpegLogCallback.set();&#xA;        ApiService apiService = new ApiService();&#xA;        Long login = apiService.login("10.3.0.54", 8801, "admin", "xxxx");&#xA;        ByteBuffer buffer = ByteBuffer.allocate(BUFFER_CAPACITY);&#xA;        final boolean[] isByteBufferFull = {false};&#xA;        apiService.startRealPlay(new RealPlayCallback() {&#xA;            @Override&#xA;            public void apply(Long aLong, Integer integer, byte[] bytes) {&#xA;                try {&#xA;                    //push data to bytebuffer&#xA;                    synchronized (buffer) {&#xA;                        if (buffer.remaining() > bytes.length) {&#xA;                            buffer.put(bytes);&#xA;                        } else {&#xA;                            isByteBufferFull[0] = true;&#xA;                        }&#xA;                    }&#xA;                } catch (Exception e) {&#xA;                    throw new RuntimeException(e);&#xA;                }&#xA;            }&#xA;        }, 0, 0);&#xA;&#xA;        ExecutorService executorService = Executors.newFixedThreadPool(1);&#xA;        executorService.execute(new Runnable() {&#xA;            @Override&#xA;            public void run() {&#xA;                while (true) {&#xA;                    //get data from bytebuffer when buffer is full&#xA;                    synchronized (isByteBufferFull) {&#xA;                        if (isByteBufferFull[0]) {&#xA;                            synchronized (buffer) {&#xA;                                buffer.flip();&#xA;                                byte[] bytes = new byte[buffer.remaining()];&#xA;                                buffer.get(bytes);&#xA;                                buffer.clear();&#xA;                                isByteBufferFull[0] = false;&#xA;                                try {&#xA;                                    //using grabber and recorder to push RTMP&#xA;                                    grabAndPush(bytes, SRS_PUSH_ADDRESS);&#xA;                                } catch (Exception e) {&#xA;                                    //throw new RuntimeException(e);&#xA;                                }&#xA;&#xA;                            }&#xA;                        }&#xA;                    }&#xA;                    try {&#xA;                        Thread.sleep(500);&#xA;                    } catch (InterruptedException e) {&#xA;                        throw new RuntimeException(e);&#xA;                    }&#xA;                }&#xA;&#xA;            }&#xA;        });&#xA;        while (true) {&#xA;&#xA;        }&#xA;    }&#xA;&#xA;    private static synchronized void grabAndPush(byte[] bytes, String pushAddress) throws Exception {&#xA;        avutil.av_log_set_level(avutil.AV_LOG_INFO);&#xA;        FFmpegLogCallback.set();&#xA;&#xA;        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(new ByteArrayInputStream(bytes));&#xA;&#xA;&#xA;        grabber.setFormat("dhav");&#xA;        grabber.start();&#xA;&#xA;        AVFormatContext avFormatContext = grabber.getFormatContext();&#xA;&#xA;        int streamNum = avFormatContext.nb_streams();&#xA;&#xA;        if (streamNum &lt; 1) {&#xA;            log.error("no media!");&#xA;            return;&#xA;        }&#xA;&#xA;        int frameRate = (int) grabber.getVideoFrameRate();&#xA;        if (0 == frameRate) {&#xA;            frameRate = 15;&#xA;        }&#xA;        log.info("frameRate[{}],duration[{}]秒,nb_streams[{}]",&#xA;                frameRate,&#xA;                avFormatContext.duration() / 1000000,&#xA;                avFormatContext.nb_streams());&#xA;&#xA;        for (int i = 0; i &lt; streamNum; i&#x2B;&#x2B;) {&#xA;            AVStream avStream = avFormatContext.streams(i);&#xA;            AVCodecParameters avCodecParameters = avStream.codecpar();&#xA;            log.info("stream index[{}],codec type[{}],codec ID[{}]", i, avCodecParameters.codec_type(), avCodecParameters.codec_id());&#xA;        }&#xA;&#xA;        int frameWidth = grabber.getImageWidth();&#xA;        int frameHeight = grabber.getImageHeight();&#xA;        int audioChannels = grabber.getAudioChannels();&#xA;&#xA;        log.info("frameWidth[{}],frameHeight[{}],audioChannels[{}]",&#xA;                frameWidth,&#xA;                frameHeight,&#xA;                audioChannels);&#xA;&#xA;        FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(pushAddress,&#xA;                frameWidth,&#xA;                frameHeight,&#xA;                audioChannels);&#xA;&#xA;        recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264);&#xA;        recorder.setInterleaved(true);&#xA;&#xA;        recorder.setFormat("flv");&#xA;&#xA;        recorder.setFrameRate(frameRate);&#xA;&#xA;        recorder.setGopSize(frameRate);&#xA;&#xA;        recorder.setAudioChannels(grabber.getAudioChannels());&#xA;&#xA;&#xA;        recorder.start();&#xA;&#xA;&#xA;        Frame frame;&#xA;&#xA;&#xA;        log.info("start push");&#xA;&#xA;        int videoFrameNum = 0;&#xA;        int audioFrameNum = 0;&#xA;        int dataFrameNum = 0;&#xA;&#xA;        int interVal = 1000 / frameRate;&#xA;        interVal /= 8;&#xA;&#xA;        while (null != (frame = grabber.grab())) {&#xA;&#xA;            if (null != frame.image) {&#xA;                videoFrameNum&#x2B;&#x2B;;&#xA;            }&#xA;&#xA;            if (null != frame.samples) {&#xA;                audioFrameNum&#x2B;&#x2B;;&#xA;            }&#xA;&#xA;            if (null != frame.data) {&#xA;                dataFrameNum&#x2B;&#x2B;;&#xA;            }&#xA;&#xA;            recorder.record(frame);&#xA;&#xA;            Thread.sleep(interVal);&#xA;        }&#xA;&#xA;        log.info("push complete,videoFrameNum[{}],audioFrameNum[{}],dataFrameNum[{}]",&#xA;                videoFrameNum,&#xA;                audioFrameNum,&#xA;                dataFrameNum);&#xA;&#xA;        recorder.close();&#xA;        grabber.close();&#xA;    }&#xA;&#xA;&#xA;}&#xA;

    &#xA;