تقييم الموضوع :
  • 0 أصوات - بمعدل 0
  • 1
  • 2
  • 3
  • 4
  • 5
[سؤال] حول استخدام ffmpeg مع progressbar
#1
وجدت الشرح التالي من قوقل عبر ذكائهم الاصطناعي لكن توقفت عند نقطة لم افهمها وهي calculatedPercentage

وهذا الكود كملا:

PHP كود :
Integrating an FFmpeg progress bar into a VB.NET application involves running FFmpeg as a separate process and then parsing its output to update a ProgressBar control in your VB.NET form.
1. Set up the FFmpeg Process:
Use 
System.Diagnostics.Process to start FFmpeg.
Redirect the standard output of the FFmpeg process to capture its progress information.

Imports System.Diagnostics
Imports System
.IO

Public Class Form1

    Private Sub ButtonStartFFmpeg_Click
(sender As ObjectAs EventArgsHandles ButtonStartFFmpeg.Click
        Dim ffmpegProcess 
As New Process()
 
       ffmpegProcess.StartInfo.FileName "ffmpeg.exe" ' Or full path to ffmpeg.exe
        ffmpegProcess.StartInfo.Arguments = "-i input.mp4 -vf scale=640:-1 output.mp4" ' 
Your FFmpeg command
        ffmpegProcess
.StartInfo.UseShellExecute False
        ffmpegProcess
.StartInfo.RedirectStandardOutput True
        ffmpegProcess
.StartInfo.CreateNoWindow True ' Hide the FFmpeg console window

        AddHandler ffmpegProcess.OutputDataReceived, AddressOf FFmpegOutputHandler

        ffmpegProcess.Start()
        ffmpegProcess.BeginOutputReadLine() ' 
Start asynchronous reading of output

        
' Optional: Wait for the process to exit
        ' 
ffmpegProcess.WaitForExit()
 
   End Sub

2. Parse FFmpeg Output 
for Progress:
FFmpeg outputs progress informationincluding out_time_us (output time in microseconds) or frame (frame number).
You'll need to parse this output to extract the relevant values.
To calculate percentage, you'
ll also need the total duration or total frames of the input filewhich can be obtained using ffprobe beforehand.

 
   Private Sub FFmpegOutputHandler(sender As ObjectAs DataReceivedEventArgs)
 
       If Not String.IsNullOrEmpty(e.DataThen
            
' Example: Parsing for "frame=" or "out_time_us="
            If e.Data.Contains("frame=") Then
                Dim frameMatch As Match = Regex.Match(e.Data, "frame=\s*(\d+)")
                If frameMatch.Success Then
                    Dim currentFrame As Integer = Integer.Parse(frameMatch.Groups(1).Value)
                    ' 
Calculate percentage based on currentFrame and total frames (from ffprobe)
 
                   ' Update ProgressBar1.Value on the UI thread
                    Me.Invoke(Sub() ProgressBar1.Value = calculatedPercentage)
                End If
            ElseIf e.Data.Contains("out_time_us=") Then
                Dim timeMatch As Match = Regex.Match(e.Data, "out_time_us=(\d+)")
                If timeMatch.Success Then
                    Dim outTimeUs As Long = Long.Parse(timeMatch.Groups(1).Value)
                    ' 
Calculate percentage based on outTimeUs and total duration (from ffprobe)
 
                   ' Update ProgressBar1.Value on the UI thread
                    Me.Invoke(Sub() ProgressBar1.Value = calculatedPercentage)
                End If
            End If
        End If
    End Sub

3. Update the Progress Bar:
The ProgressBar control'
s Value property should be updated within the FFmpegOutputHandler.
Since FFmpegOutputHandler runs on a separate threadyou must use Me.Invoke to update UI elements on the main UI thread.
Set the ProgressBar's Minimum and Maximum properties (e.g., 0 and 100 for percentage).
Considerations:
Error Handling: Implement error handling for the FFmpeg process (e.g., Exited event, checking ExitCode).
Total Duration/Frames: Use ffprobe to get the total duration or total frames of the input video before running FFmpeg for accurate percentage calculation.
Regular Expressions: Use System.Text.RegularExpressions to efficiently parse the FFmpeg output.
UI Responsiveness: Performing these operations asynchronously ensures your UI remains responsive during the FFmpeg process. 
 و شكرا مسبقا
اللهم إني أعوذ بك من غلبة الدين وغلبة العدو، اللهم إني أعوذ بك من جهد البلاء ومن درك الشقاء ومن سوء القضاء ومن شماتة الأعداء
اللهم اغفر لي خطيئتي وجهلي، وإسرافي في أمري وما أنت أعلم به مني، اللهم اغفر لي ما قدمت وما أخرت، وما أسررت وما أعلنت وما أنت أعلم به مني، أنت المقدم وأنت المؤخر وأنت على كل شيء قدير
الرد }}}
تم الشكر بواسطة:
#2
PHP كود :
Imports System.Text.RegularExpressions

Public Class Form1

    Dim ffprobe 
As String "ffprobe.exe"   ' Path to ffprobe.exe
    Dim ffmpeg As String = "ffmpeg.exe"     ' 
Path to ffmpeg.exe

    Dim inputFile 
As String "input.mp4"   ' Path to input file
    Dim outputFile As String = "output.mp4" ' 
Path to output file

    Dim totalDurationSeconds 
As Double ' total duration seconds

    Private Sub ButtonStart_Click(ByVal sender As Object, ByVal e As EventArgs) Handles ButtonStart.Click
        If IO.File.Exists(outputFile) Then
            MsgBox(String.Format(" The file '
{0}' exists.", outputFile))
            Exit Sub
        End If

        ProgressBar1.Value = 0
        LabelProgress.Text = "0%"
        Dim processingThread As New System.Threading.Thread(AddressOf StartFFmpegProcessing)
        processingThread.Start()

        ' 
ButtonStart disable
        ButtonStart
.Enabled False
    End Sub

    Private Sub StartFFmpegProcessing
()
 
       ' Get total duration seconds
        GetTotalDurationSeconds(inputFile)

        ' 
ffmpeg Process
        Dim ffmpegProcess 
As New Process()
 
       Dim startInfo As New ProcessStartInfo()

 
       startInfo.FileName ffmpeg ' Path to ffmpeg.exe
        startInfo.Arguments = "-i """ & inputFile & """ -progress pipe:1 -vf scale=640:-1 """ & outputFile & """" ' 
Example argumentsincluding -progress pipe:for machine-readable output
        startInfo
.UseShellExecute False
        startInfo
.RedirectStandardOutput True
        startInfo
.CreateNoWindow True

        ffmpegProcess
.StartInfo startInfo
        ffmpegProcess
.EnableRaisingEvents True

        AddHandler ffmpegProcess
.OutputDataReceivedAddressOf FFmpegOutputHandler

        ffmpegProcess
.Start()
 
       ffmpegProcess.BeginOutputReadLine() ' Start asynchronous reading of output

        ' 
Wait for FFmpeg to exit (optionalcan be handled in a separate thread)
 
       ffmpegProcess.WaitForExit()

 
       ' Clean up event handler
        RemoveHandler ffmpegProcess.OutputDataReceived, AddressOf FFmpegOutputHandler

        ' 
ButtonStart enable
        ButtonStart
.Invoke(Sub() ButtonStart.Enabled True)

 
   End Sub

    Private Sub FFmpegOutputHandler
(ByVal sender As ObjectByVal e As DataReceivedEventArgs)
 
       If Not String.IsNullOrEmpty(e.DataThen
            
' Parse FFmpeg output to extract progress information
            ' 
For examplelook for "out_time_ms=" or "time=" to get current time
            
' Example: Assuming totalDurationSeconds is available (e.g., from a class-level variable)
            Dim currentTimeMatch As Match = Regex.Match(e.Data, "out_time_ms=(\d+)")
            If currentTimeMatch.Success Then
                Dim currentTimeMilliseconds As Long = Long.Parse(currentTimeMatch.Groups(1).Value)
                Dim currentTimeSeconds As Double = currentTimeMilliseconds / 1000.0

                If totalDurationSeconds > 0 Then
                    Dim progressPercentage As Integer = CInt((currentTimeSeconds / totalDurationSeconds) * 100)
                    If progressPercentage > 100 Then progressPercentage = 100
                    If progressPercentage < 0 Then progressPercentage = 0

                    ' 
Update ProgressBar on the UI thread
                    Me
.Invoke(Sub()
 
                                 ProgressBar1.Value progressPercentage
                                  LabelProgress
.Text progressPercentage.ToString() & "%"
 
                             End Sub)
 
               End If
 
           End If
 
       End If
 
   End Sub

    Private Sub GetTotalDurationSeconds
(ByVal inputFile As String)
 
       ' Get total duration seconds (from ffprobe)
        Dim proc As New Process()
        Dim startInfo As New ProcessStartInfo()
        startInfo.FileName = ffprobe ' 
Path to ffprobe.exe
        startInfo
.Arguments "-v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 """ inputFile """"
 
       startInfo.RedirectStandardInput True
        startInfo
.RedirectStandardOutput True
        startInfo
.CreateNoWindow True
        startInfo
.UseShellExecute False
        proc
.StartInfo startInfo
        proc
.Start()
 
       If Not IsNothing(procThen totalDurationSeconds Val(proc.StandardOutput.ReadToEnd) * 1000.0
        proc
.WaitForExit()
 
   End Sub

End 
Class 
الرد }}}
تم الشكر بواسطة: justforit
#3
(08-10-25, 12:47 PM)Zuhare كتب :
PHP كود :
Imports System.Text.RegularExpressions

Public Class Form1

    Dim ffprobe 
As String "ffprobe.exe"   ' Path to ffprobe.exe
    Dim ffmpeg As String = "ffmpeg.exe"     ' 
Path to ffmpeg.exe

    Dim inputFile 
As String "input.mp4"   ' Path to input file
    Dim outputFile As String = "output.mp4" ' 
Path to output file

    Dim totalDurationSeconds 
As Double ' total duration seconds

    Private Sub ButtonStart_Click(ByVal sender As Object, ByVal e As EventArgs) Handles ButtonStart.Click
        If IO.File.Exists(outputFile) Then
            MsgBox(String.Format(" The file '
{0}' exists.", outputFile))
            Exit Sub
        End If

        ProgressBar1.Value = 0
        LabelProgress.Text = "0%"
        Dim processingThread As New System.Threading.Thread(AddressOf StartFFmpegProcessing)
        processingThread.Start()

        ' 
ButtonStart disable
        ButtonStart
.Enabled False
    End Sub

    Private Sub StartFFmpegProcessing
()
 
       ' Get total duration seconds
        GetTotalDurationSeconds(inputFile)

        ' 
ffmpeg Process
        Dim ffmpegProcess 
As New Process()
 
       Dim startInfo As New ProcessStartInfo()

 
       startInfo.FileName ffmpeg ' Path to ffmpeg.exe
        startInfo.Arguments = "-i """ & inputFile & """ -progress pipe:1 -vf scale=640:-1 """ & outputFile & """" ' 
Example argumentsincluding -progress pipe:for machine-readable output
        startInfo
.UseShellExecute False
        startInfo
.RedirectStandardOutput True
        startInfo
.CreateNoWindow True

        ffmpegProcess
.StartInfo startInfo
        ffmpegProcess
.EnableRaisingEvents True

        AddHandler ffmpegProcess
.OutputDataReceivedAddressOf FFmpegOutputHandler

        ffmpegProcess
.Start()
 
       ffmpegProcess.BeginOutputReadLine() ' Start asynchronous reading of output

        ' 
Wait for FFmpeg to exit (optionalcan be handled in a separate thread)
 
       ffmpegProcess.WaitForExit()

 
       ' Clean up event handler
        RemoveHandler ffmpegProcess.OutputDataReceived, AddressOf FFmpegOutputHandler

        ' 
ButtonStart enable
        ButtonStart
.Invoke(Sub() ButtonStart.Enabled True)

 
   End Sub

    Private Sub FFmpegOutputHandler
(ByVal sender As ObjectByVal e As DataReceivedEventArgs)
 
       If Not String.IsNullOrEmpty(e.DataThen
            
' Parse FFmpeg output to extract progress information
            ' 
For examplelook for "out_time_ms=" or "time=" to get current time
            
' Example: Assuming totalDurationSeconds is available (e.g., from a class-level variable)
            Dim currentTimeMatch As Match = Regex.Match(e.Data, "out_time_ms=(\d+)")
            If currentTimeMatch.Success Then
                Dim currentTimeMilliseconds As Long = Long.Parse(currentTimeMatch.Groups(1).Value)
                Dim currentTimeSeconds As Double = currentTimeMilliseconds / 1000.0

                If totalDurationSeconds > 0 Then
                    Dim progressPercentage As Integer = CInt((currentTimeSeconds / totalDurationSeconds) * 100)
                    If progressPercentage > 100 Then progressPercentage = 100
                    If progressPercentage < 0 Then progressPercentage = 0

                    ' 
Update ProgressBar on the UI thread
                    Me
.Invoke(Sub()
 
                                 ProgressBar1.Value progressPercentage
                                  LabelProgress
.Text progressPercentage.ToString() & "%"
 
                             End Sub)
 
               End If
 
           End If
 
       End If
 
   End Sub

    Private Sub GetTotalDurationSeconds
(ByVal inputFile As String)
 
       ' Get total duration seconds (from ffprobe)
        Dim proc As New Process()
        Dim startInfo As New ProcessStartInfo()
        startInfo.FileName = ffprobe ' 
Path to ffprobe.exe
        startInfo
.Arguments "-v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 """ inputFile """"
 
       startInfo.RedirectStandardInput True
        startInfo
.RedirectStandardOutput True
        startInfo
.CreateNoWindow True
        startInfo
.UseShellExecute False
        proc
.StartInfo startInfo
        proc
.Start()
 
       If Not IsNothing(procThen totalDurationSeconds Val(proc.StandardOutput.ReadToEnd) * 1000.0
        proc
.WaitForExit()
 
   End Sub

End 
Class 

شكر الله لك اخي الكريم 
باذن الله تعالى ساجرب الكود فقد اتعبني حاولت فيه اكثر من طريقة .
اللي كنت ادربه هو دمج صور مع صوت ليكون فيديو وتم الامر لكن اما تكون االصورة سابقة للصوت او العكس وقد يتم اقتطاع جزء من الصوت.
اللهم إني أعوذ بك من غلبة الدين وغلبة العدو، اللهم إني أعوذ بك من جهد البلاء ومن درك الشقاء ومن سوء القضاء ومن شماتة الأعداء
اللهم اغفر لي خطيئتي وجهلي، وإسرافي في أمري وما أنت أعلم به مني، اللهم اغفر لي ما قدمت وما أخرت، وما أسررت وما أعلنت وما أنت أعلم به مني، أنت المقدم وأنت المؤخر وأنت على كل شيء قدير
الرد }}}
تم الشكر بواسطة:


المواضيع المحتمل أن تكون متشابهة .
الموضوع : الكاتب الردود : المشاهدات : آخر رد
  كيف نضبط قيمة progressbar في حال العد العكسي justforit 2 152 01-11-25, 09:43 AM
آخر رد: justforit
  كيف الى استخدام webview2 من ملف dll justforit 2 191 28-10-25, 02:49 AM
آخر رد: justforit
  [VB.NET] استخدام كلمة برمجية كمتغير mmaalmesry 1 160 02-10-25, 08:55 AM
آخر رد: Taha Okla
  [VB.NET] مشكلة تظهر عند استخدام الملف manifest mmaalmesry 2 620 12-05-25, 12:15 AM
آخر رد: mmaalmesry
  [VB.NET] تحويل pdf الى صورة بدون استخدام الاكروبات بأستخدام adobe reader العادى فقط AhmedNagib 1 1,167 11-07-24, 01:16 PM
آخر رد: تركي الحلواني
  استخدام فونت جديد في البرنامج Emam emam 5 481 14-04-24, 01:29 PM
آخر رد: عبد العزيز البسكري
  [VB.NET] أرغب فى استخدام هذا الكود بالتحديد على الإصدار 10 AmeenRashed 3 501 19-01-24, 12:42 PM
آخر رد: Taha Okla
  [VB.NET] كيف اقوم بمنع المستخدم من استخدام الكيبورد وخصوصا مفتاح Print screen Ameenh 0 490 07-10-23, 10:45 PM
آخر رد: Ameenh
  طريقة استخدام حلقة For Each ASUS2020 5 931 11-04-23, 01:26 AM
آخر رد: ASUS2020
  [VB.NET] بطئ تحديث كونترول اثناء استخدام linq الماجيك مسعد 9 1,492 23-10-22, 02:39 PM
آخر رد: الماجيك مسعد

التنقل السريع :


يقوم بقرائة الموضوع: