DIM x AS NEW SpeechSynthesizer

Filed under .NET, VB Feng Shui

Here’s an interesting one for you.

I was playing with the SpeechSynthesis namespace recently when I ran off into a coding ditch. You know, one of those times when things are moving along nicely, and you swerve to avoid some minor nit, only to find yourself stuck upside down with the wheels half sunk in muck, trying to claw yourself out with an ICE and log files…

Anyway, I had this:

Public Class Connect
   Private WithEvents rSynth As New SpeechSynthesizer

And a little later in the class, I was using it like so…

      If rSynth.State <> SynthesizerState.Speaking Then
      End If

Simple enough.

But it didn’t work. State was always coming back Ready, not Speaking, so I was getting a rather laughable stuttering intro to tracks as they were playing… “Now…Now…Now…Playing….Playing….Swerve…Playing….Swerve…”

(Sorry, the app in question is a little MP3 player plug in to announce tracks and allow you to navigate through the player using only a remote and no screen.)

I tried several different approaches but none worked. I could never get the proper state of the synthesizer to be reflected.

Then, on a lark, I remove the New from the SpeechSynthesizer declaration line:

Public Class Connect
   Private WithEvents rSynth As SpeechSynthesizer

And just assigned a new instance to the rSynth var from Sub New.

It worked!? Huh?

What was going on here?

I’m still not 100% sure, and the documentation on the NEW modifier for a DIM statement certainly doesn’t help to clarify things. From what I can tell, it looks like each reference to the regional var rSynth ends up retrieving a new SpeechSynthesizer object. Definitely not the behavior I was expecting. And not behavior I’ve seen before given this use of the New clause.

In reality, I’ve had far too many lessons about Dim x as New from VB6 to normally use it like this anyway. I guess I thought VB was past all that now in .NET, but I’m slowing learning that VB.NET is every bit as quirky as VB6, just differently so.

Ah, progress.

Post a Comment

Your email is never published nor shared. Required fields are marked *