Windows Media Encoder 9 SDK OnStateChanged Event

21 11 2008

I’m working on a project that allows users to upload video to a website. We’re intending to use Silverlight Streaming Services to stream the content to users, so the video needs to be in a WMV format. Rather than ask the user to do that for themselves, we’re going to use the Windows Media Encoder SDK to re-encode the video for them.

I wrote a console app in vb.net to try it out. The Start() method of the Encoder object is an asynchronous call, so once you’ve kicked it off you need to wait around for it to complete. This doesn’t seem to be a problem – there’s an OnStateChanged event you can handle that should get called when the encoder’s state changes to “Stopped”. Problem was, the handler was receiving “Starting” and “Started” but then nothing else? Why not? After a few minutes of searching I found this little gem buried in the docs:


// In order for the events to be triggered correctly,

// the windows message queue needs to be processed.

// Note: This is only necessary in a C# console

// application. A C# Windows application processes the

//message queue automatically.

Eureka!

So, after a quick reference to System.Windows.Forms.dll and the addition of line 7  to the code sample below, my wait loop and event handler now look like this:


            objEncoder.PrepareToEncode(True)
            objEncoder.Start()

            Console.WriteLine("Encoding...")

            While Not c_blnDone
                Windows.Forms.Application.DoEvents()
                Threading.Thread.Sleep(1000)
            End While
    End Sub

    Protected Sub HandleEncoderStateChange(ByVal state As WMEncoderLib.WMENC_ENCODER_STATE)
        Console.WriteLine(state.ToString())

        Select Case state
            Case WMENC_ENCODER_STATE.WMENC_ENCODER_STOPPED
                c_blnDone = True
        End Select

    End Sub

…and everything works just fine.


Actions

Information

2 responses

30 01 2009
i-developer

Hi,

I think you couldn’t define the WMEncoder object. So you couldn’t get Events. That’s why you did your way. It’s perfect. I did too. :)

There is a hotfix to install then you can use it ;)

http://support.microsoft.com/default.aspx/kb/929182

Then you can use like below.

WMEncoder Encoder = new WMEncoder();
Encoder.OnSourceStateChange += new _IWMEncoderEvents_OnSourceStateChangeEventHandler(Encoder_OnSourceStateChange);

Encoder.OnStateChange += new _IWMEncoderEvents_OnStateChangeEventHandler(Encoder_OnStateChange);

Regards.

31 01 2009
Admin

i-developer:

Hi. The WMEncoder was being created ok, I just wasn’t getting all the events. I was running on XP anyway – the hotfix you mentioned appears to be for Vista. Still, the hotfix ought to be useful to a colleague of mine, so thanks for mentioning it.

Leave a comment