2015. 3. 9. 08:39

Playing WAV Files

All Versions

 

There is a simple way for PowerShell to play back WAV sound files:

 

# find first available WAV file in Windows folder
$WAVPath = Get-ChildItem -Path $env:windir -Filter *.wav -Recurse -ErrorAction SilentlyContinue |
  Select-Object -First 1 -ExpandProperty FullName
 
 
# load file and play it
"Playing $WAVPath..."
 
$player = New-Object Media.SoundPlayer $WAVPath
$player.Play()
 
"Done!"

 

The first part of this script finds the first WAV file it can get inside the Windows folder, and selects its path. Of course, you can assign the path to your favorite WAV file to $WAVFile in the first place.

Next, the Media.SoundPlayer loads and then plays the WAV file. Note how Play() plays the sound: it is played in a separate thread, and PowerShell will immediately continue.

You can use this to create an acoustic progress bar: it will play for as long as PowerShell is busy doing something:

 

# find first available WAV file in Windows folder
$WAVPath = Get-ChildItem -Path $env:windir -Filter *.wav -Recurse -ErrorAction SilentlyContinue |
  Select-Object -First 1 -ExpandProperty FullName


# load file and play it

$player = New-Object Media.SoundPlayer $WAVPath
$player.PlayLooping()
 
1..100 | ForEach-Object {
  Write-Progress -Activity 'Doing Something. Hang in' -Status $_ -PercentComplete $_
  Start-Sleep -MilliSeconds (Get-Random -Minimum 300 -Maximum 1300)
  }
$player.Stop()

 

This time, PlayLooping() is used to repeat the sound. The sound now plays forever, so you need to call Stop() manually. That’s what the script does when it is done.


Comment on this PowerTip >>