Playing WAV Sounds

by Sep 1, 2014

PowerShell 3.0 or later

To play a WAV sound file in a background process, PowerShell can use the built-in SoundPlayer class. It accepts a path to a WAV file and lets you then decide whether you want to play the sound once or repeatedly.

This would play a sound repeatedly:

$player = New-Object -TypeName System.Media.SoundPlayer
$player.SoundLocation = 'C:\Windows\Media\chimes.wav'
$player.Load()
$player.PlayLooping()

Once your script is done, it can stop playback using this call:

$player.Stop()

If you'd like to ship a custom sound with your PowerShell script, simply place it into the same folder together with your script, and use $PSScriptRoot to reference the folder your script is located in.

This example would playback the file mySound.wav that is located in the same folder as your script:

$player = New-Object -TypeName System.Media.SoundPlayer
$player.SoundLocation = "$PSScriptRoot\mySound.wav"
$player.Load()
$player.PlayLooping()

# do something...
Start-Sleep -Seconds 5

$player.Stop() 

Note that $PSScriptRoot requires PowerShell version 3.0 or later. It also requires your script to be saved to a file, of course.

Twitter This Tip! ReTweet this Tip!