C# How to avoid repeated video playback when playing back rtsp video through ffmpeg.autogen

        When using the ffmpeg.autogen library to play back RTSP videos, if you want to avoid playing the video repeatedly, you need to stop the video after it has finished playing instead of reopening and setting up the input stream. This can usually be accomplished by checking the return value of the decoder. You can stop playback when the decoder returns AVERROR_EOF (indicating that the end of the file or stream has been reached).

Here is an example showing how to implement this functionality:

​using FFmpeg.AutoGen;

public class VideoPlayer
{
    private AVFormatContext* pFormatContext;
    private string url;

    public VideoPlayer(string url)、
    {
        this.url = url;
        ffmpeg.av_register_all();
        ffmpeg.avformat_network_init();
    }

    public void Play()
    {
        OpenStream();

        // 这里是播放视频的代码
        while (true)
        {
            AVPacket packet;
            ffmpeg.av_init_packet(&packet);
            int ret = ffmpeg.av_read_frame(pFormatContext, &packet);
            if (ret == ffmpeg.AVERROR_EOF)
            {
                // 到达文件或流的末尾,停止播放
                break;
            }
            // 其他处理代码
        }
        CloseStream();
    }

    private void OpenStream()
    {
        pFormatContext = ffmpeg.avformat_alloc_context();
        if (ffmpeg.avformat_open_input(&pFormatContext, url, null, null) != 0)
        {
            throw new Exception("Could not open input stream.");

        }
    }

    private void CloseStream()
    {
        ffmpeg.avformat_close_input(&pFormatContext);
    }
}

​

In this example, we added a loop to the Play method that reads and processes video frames until the end of the file or stream is reached. When the end of the file or stream is reached, the av_read_frame function will return AVERROR_EOF. We check this return value. If it is AVERROR_EOF, we will break out of the loop and stop playing.

Guess you like

Origin blog.csdn.net/u013543846/article/details/132895870