Click here to Skip to main content
Click here to Skip to main content

Mplayer control by VB.NET used in Veron Media Player

, 10 Dec 2013
Rate this:
Please Sign up or sign in to vote.
Code describing that how we can easily control mplayer in VB.NET Winform application

Introduction

This article will demonstrate that how we can use mplayer to easily control in VB.NET WinForm application without using any COM/ActiveX control. Download source code is sample part of Veron Media Player. At First , we need mplayer.exe in our main application's start path. It can be downloaded from here

Background

Mplayer is a command line audio & video player. It can play audio or video file using several different output drivers. There were no previous examples of how to use mplayer to play audio or video in VB.NET winform application. C++ examples that were found to control mplayer but it is more easy and reliable if VB.NET program use. This article will show how can we use Mplayer to easily play audio or video files in our applications.    

Screenshot of sample part of Veron media player:  

undefined

Techniques  

Process object, Window handle control, Input and Output redirection. 

Using the code  

We will use Process class of System.Diagnostics namespace to launch an instance of mplayer to play files. We'll redirect input & output so that we can send commands to mplayer and get information about file from mplayer.

Here is the code that we use to declare variables and initialize process: 

' To declare Variables :-
Dim args, file, time_length As String
Dim str As Long
Dim ps As Process = Nothing
 ' To initialize process :-
' To initialize process :-
ps = New Process()
ps.StartInfo.ErrorDialog = False
ps.StartInfo.UseShellExecute = False
ps.StartInfo.RedirectStandardInput = True
ps.StartInfo.RedirectStandardOutput = True
ps.StartInfo.FileName = "mplayer.exe"
ps.StartInfo.CreateNoWindow = True

Here, args will hold the arguments that will be passed to process except file name. file will be the name of file that is selected to be opened. ps is the process object which will use it to keep a reference to the mplayer process.    

We will use "-slave" option because we want to run mplayer  in 'slave' mode where it will read commands from another process and do actions accordingly.

Here , -nofs option for not to run in full screen mode. -wid option will tell the id of window where we want to display video output. Here we want to display in PictureBox1, so we get its handle and pass it after -wid.

Now , when a user clicks on select file, a file open dialog will open and after a file is selected, its path is stored in the file variable.  

Here code that to open file :-

If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
    time_length = ""
    str = 1
    Timer1.Stop()
    Timer2.Stop()
    Timer3.Stop()
    Button1.Text = "Pause"
    Button1.Enabled = True
    TrackBar2.Enabled = True
    TrackBar1.Enabled = True
    Try
        ps.Kill()
    Catch
    End Try
    file = OpenFileDialog1.FileName
    args = "-nofs -noquiet -identify -slave -volume " & _
      TrackBar1.Value & _
      " -nomouseinput -sub-fuzziness 1 -vo direct3d, -ao dsound -osdlevel 0 -wid " _
      & CInt(PictureBox1.Handle.ToInt32)
    ps.StartInfo.Arguments = args & " """ & file & """"
    ps.Start()
    Timer1.Start()
    Timer2.Start()
    Timer3.Start()
End If

First, We want to make sure that any previous instance of mplayer started by us is closed. So, ps.Kill in try catch used that if the process has already exited or not started, the error does not show. Here timer1 , timer2 & timer3 are used, i will discuss later.

We can write commands to mplayer to control the file that is being played. Each command must end with vbLf. SendCommand function will perform the task of sending commands to mplayer process. 

Public Sub SendCommand(ByVal cmd As String)
    Try
        If ps IsNot Nothing AndAlso ps.HasExited = False Then
            ps.StandardInput.Write(cmd & vbLf)
        End If
    Catch
    End Try
End Sub 

So, we can pass commands and control the file that is being played. Now to play or pause a selected file, the following code is used:

If Button1.Text = "Pause" Then
    Button1.Text = "Start"
    Timer2.Stop()
    Timer1.Stop()
    Timer3.Stop()
    SendCommand("pause")
    TrackBar2.Enabled = False
    TrackBar1.Enabled = False
Else
    Button1.Text = "Pause"
    SendCommand("pause")
    Timer2.Start()
    Timer1.Start()
    Timer3.Start()
    TrackBar2.Enabled = True
    TrackBar1.Enabled = True
End If 

Here button1 is used to pause or play the file. So, we can give any slave mode command to mplayer by SendCommand function. All slave mode commands can be found in here

Now, description about timer1. It is used to get file's duration & time position. Following code is used in timer1. 

Dim sLine As String = ""
Try
    sLine = ps.StandardOutput.ReadLine
    If (Not String.IsNullOrEmpty(sLine)) Then
    If sLine.Contains("ANS_") Then
        If str = 1 Then
            Dim b As String = sLine.Replace("ANS_LENGTH=", "")
            ConvertTimeHHMMSS(b)
        Else
            Dim b As String = sLine.Replace("ANS_TIME_POSITION=", "")
            ConvertTimeHHMMSS(b)
        End If
    End If
    End If
Catch
End Try 

Interval of timer1 & timer2 must be 1 millisecond cause if we use greater than 1 then playing process's problem will arise. Timer1 , 2 & 3 must be start for playing file and stop when pause or stop file. In timer1 process, we can read output file's time position successively 1 millisecond. But mplayer shows file's time position in seconds and we want to see it HH:MM:SS format. Therefore ConvertTimeHHMMSS function was used. Following code is used for that function:    

Public Sub ConvertTimeHHMMSS(ByVal timeInSeconds As Double)
    Try
        If timeInSeconds >= 0 Then
            Dim iSecond As Double = timeInSeconds
            Dim iSpan As TimeSpan = TimeSpan.FromSeconds(iSecond)
            Dim time_string As String = ""
            time_string = iSpan.Hours.ToString.PadLeft(2, "0"c) & ":" & _
              iSpan.Minutes.ToString.PadLeft(2, "0"c) & _
              ":" & iSpan.Seconds.ToString.PadLeft(2, "0"c)
            If str = 1 Then
                time_length = time_string
                TrackBar2.Maximum = timeInSeconds
                If Not time_length = "" Then
                    str = 0
                End If
            Else
                Label1.Text = time_string & " / " & time_length
                TrackBar2.Value = timeInSeconds
            End If
        End If
    Catch
    End Try
End Sub 

Here, TimeSpan.FromSeconds method is used which returns a timespan that represents a specified number of seconds , where the specification is accurate to the nearest millisecond. Now, Timer2 is used to read line from mplayer. Though this process is used in timer1 but it should be used in timer2 otherwise problem will arise for pausing or starting mplayer. So program in time2 is :

Try
    ps.StandardOutput.ReadLine()
Catch
End Try  

Timer3 is used to send command to mplayer for reading file's time position. Code is:

 If str = 1 Then
    SendCommand("get_time_length")
Else
    SendCommand("get_time_pos")
End If

 Here code for Volume Control Track bar is :-

SendCommand("set_property volume " & TrackBar1.Value) 

 And TrackBar2 as Seek Bar is  :-

Private Sub TrackBar2_MouseDown(ByVal sender As System.Object, _
         ByVal e As System.Windows.Forms.MouseEventArgs) Handles TrackBar2.MouseDown
    If e.Button = Windows.Forms.MouseButtons.Left Then
        Dim dValue As Double
        dValue = (Convert.ToDouble(e.X) / Convert.ToDouble(TrackBar2.Width)) * (TrackBar2.Maximum - TrackBar2.Minimum)
        TrackBar2.Value = Convert.ToInt32(dValue)
        SendCommand("seek " & TrackBar2.Value & " 2")
    End If
End Sub

Points of Interest 

Mplayer is a really great command line application program and obviously VB.NET Program is one of the best to control mplayer. However, Mplayer has no audio visualization but it can be possible by using FFT algorithm.

History  

  • 03 September , 2013 - First release.  
  • 09 December , 2013 - Second release.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

S.M.A.Faisal
Engineer
United States United States
B.Sc in Electrical & Electronics Engineering
Interest in Power electronics & Computer programming

Comments and Discussions

 
Questionsong list? Pinmembermouse7118-Dec-13 16:04 
QuestionSuggestion to use only one timer PinmemberJohannes Weidenauer1-Nov-13 13:20 
AnswerRe: Suggestion to use only one timer [modified] PinmemberS.M.A.Faisal2-Nov-13 4:56 
Dear Johannes,
 
You should experiment on differnet types of files [all types of HD , split file , blueray file...etc] with different drivers & see what will happen if you don’t use these two timer. Timer2 must use for playing high definition / BluRay video file otherwise sometimes mplayer will crash or video file will stuck while playing. Mplayer control with VB.NET is not so much easy for high bit rate HD files. In timer2 , "ps.StandardOutput.ReadLine" used for backup protection that helps not to stuck HD/bluray video file while playing.
 
Timer 3 must use for remove complexity in timer 1. I know that mplayer show position in seconds frequently while running but not that format means "A: 913.5 V: 913.2 A-V: 0.326..." all times. If you use only audio then another format, video with no audio then another format. So then you need a "if else" method with Substring in timer1. So, why do you go to complexity. Best is send command to get time position and timer3 interval must be from 100 to 500 ms depends on your choice.
 
If you think that you want to go to your method then do whatever you like Smile | :)

modified 6-Nov-13 4:25am.

GeneralMy vote of 5 PinmemberJohannes Weidenauer30-Oct-13 4:07 
Questionmplayer.exe PinmemberJohannes Weidenauer28-Oct-13 23:22 
AnswerRe: mplayer.exe PinmemberS.M.A.Faisal30-Oct-13 3:12 
GeneralRe: mplayer.exe [modified] PinmemberJohannes Weidenauer30-Oct-13 4:11 
Questionshow video in mirror image PinmemberPatrick McGorty15-Oct-13 21:07 
AnswerRe: show video in mirror image PinmemberS.M.A.Faisal20-Oct-13 8:39 
GeneralRe: show video in mirror image PinmemberPatrick McGorty20-Oct-13 13:46 
GeneralRe: show video in mirror image PinmemberS.M.A.Faisal20-Oct-13 23:48 
GeneralRe: show video in mirror image PinmemberPatrick McGorty21-Oct-13 5:28 
GeneralRe: show video in mirror image PinmemberPatrick McGorty22-Oct-13 2:38 
GeneralRe: show video in mirror image PinmemberS.M.A.Faisal22-Oct-13 4:25 
GeneralRe: show video in mirror image PinmemberPatrick McGorty22-Oct-13 5:38 
GeneralMy vote of 5 PinmemberVolynsky Alex4-Sep-13 2:02 
QuestionA novel approach, gets my 5 PinmvpSacha Barber3-Sep-13 21:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140709.1 | Last Updated 10 Dec 2013
Article Copyright 2013 by S.M.A.Faisal
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid