Applies to all PowerShell versions
In fact, playing WAV files in PowerShell is very simple:
Copy Code code as follows:
# Find an available WAV audio file in the Windows directory
$WAVPath = Get-childitem-path $env: windir-filter *.wav-recurse-erroraction silentlycontinue |
Select-object-first 1-expandproperty FullName
# Load and Play
"Playing $WAVPath ..."
$player = New-object Media.soundplayer $WAVPath
$player. Play ()
"Done!"
In the first section, recursively locate the first WAV file from the Windows folder and select its path. Of course, you can also assign your own collection of WAV files to $WAVFile in the first row. Next use Media.soundplayer to load and play. Note that the play () method uses a child thread for playback, so the method returns immediately, but the audio may not have started playing or the playback has ended.
You can use it to create a sound progress bar: When PowerShell is doing a task, it can always play a piece of music until the task is complete:
Copy Code code as follows:
# Find an available WAV audio file in the Windows directory
$WAVPath = Get-childitem-path $env: windir-filter *.wav-recurse-erroraction silentlycontinue |
Select-object-first 1-expandproperty FullName
# Load and Play
$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, we use playlooping () to loop, and you need to call the Stop () method to stop manually. That's why we called the $player.stop () method at the end of the script.