I’ve seen this question several times over the past few weeks so I decided to sit down and find a solution. There’s a plethora of reasons why you might want to mute or unmute sound volume from within a WSH script. Until now, there’s been no viable solution.
There are several third-party ActiveX controls available that offer the ability to mute sound volume; but if you’re like me, you’d much rather have a native way of doing this. Third-party ActiveX controls hinder script compatibility (and portability) because they are required to be installed on every system.
Knowing that neither WScript nor VBScript had a method of doing this, my first instinct was to look at WMI. That was a no-go. WMI allows you to work with sound hardware, but it doesn’t allow you to control it’s functionality.
Next, I looked to the command-line. I knew that Sndvol32.exe controlled was the Sound and Volume control, but it doesn’t provide any useful command-lines.
Finally, I decided to look toward some native objects. In many cases scriptable objects like Word and Media Player can offer methods of interacting with the Windows API that are otherwise inaccessible to scripters. Again, no such luck.
I had exhausted all of my normal avenues of approach, and, to be honest, was quite ready to beat my head off the wall. I was just about to give in and choose a third-party ActiveX or command-line utility when I remembered something: the multimedia keyboard!
Windows has native support for multimedia keyboards and these keyboards offer a nifty little Mute button. In short, this means that Windows can detect (and respond) to that particular key code. My problem then became: How on earth do I simulate that keystroke?
Anytime you’re working with keystrokes you should be thinking of the WshShell object’s SendKeys method. However, we’ve been told that it only accepts predefined string values–namely, common alphanumeric characters and some predefined symbolic names. This got me to thinking. How does this function really work.
The SendKeys method accepts can accept a string characters. This would indicate that it iterates through each of those characters. Logically, that would indicate that it’s functionality is based on character codes, rather than the specific characters themselves. So I decided to try it. A little research revealed that the character code for the Mute button was 0xAD (or decimal 173).
Set WshShell = CreateObject("WScript.Shell") WshShell.SendKeys(chr(&hAD))
You may recall that VBScript provides the Chr() function that returns a string representation for a character based on its hex or decimal value. This is commonly used to return non-printable characters, which conveniently enough is exactly what we need here. You can see above that I’m simply passing the result of the Chr() function directly to the SendKeys method.
Voila! It works. This code will toggle the sound volume on and off.