PowerShell/docs/play-mp3.md
2025-01-23 12:15:35 +01:00

100 lines
2.5 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

The *play-mp3.ps1* Script
===========================
This PowerShell script plays the given sound file (MPEG-1 audio layer-3 file format).
Parameters
----------
```powershell
/Repos/PowerShell/scripts/play-mp3.ps1 [[-path] <String>] [<CommonParameters>]
-path <String>
Specifies the file path to the .MP3 file
Required? false
Position? 1
Default value
Accept pipeline input? false
Accept wildcard characters? false
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
```
Example
-------
```powershell
PS> ./play-mp3.ps1 C:\thunder.mp3
Playing 'thunder.mp3' (00:03) ...
```
Notes
-----
Author: Markus Fleschutz | License: CC0
Related Links
-------------
https://github.com/fleschutz/PowerShell
Script Content
--------------
```powershell
<#
.SYNOPSIS
Plays a .MP3 sound file
.DESCRIPTION
This PowerShell script plays the given sound file (MPEG-1 audio layer-3 file format).
.PARAMETER path
Specifies the file path to the .MP3 file
.EXAMPLE
PS> ./play-mp3.ps1 C:\thunder.mp3
▶️ Playing 'thunder.mp3' (00:03) ...
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param([string]$path = "")
try {
if ($path -eq "" ) { $path = Read-Host "Enter the file path to the MP3 sound file" }
if (-not(Test-Path "$path" -pathType leaf)) { throw "Can't access sound file: $path" }
$fullPath = (Get-ChildItem $path).fullname
$filename = (Get-Item "$fullPath").name
Add-Type -assemblyName PresentationCore
$mediaPlayer = New-Object System.Windows.Media.MediaPlayer
do {
$mediaPlayer.open($fullPath)
$milliseconds = $mediaPlayer.NaturalDuration.TimeSpan.TotalMilliseconds
} until ($milliseconds)
[int]$minutes = $milliseconds / 60000
[int]$seconds = ($milliseconds / 1000) % 60
Write-Host " ▶️" -noNewline -foregroundColor green
Write-Host "Playing '$filename' ($($minutes.ToString('00')):$($seconds.ToString('00'))) ..."
$previousTitle = $host.ui.RawUI.WindowTitle
$host.ui.RawUI.WindowTitle = "▶️ $filename"
$mediaPlayer.Volume = 1
$mediaPlayer.play()
Start-Sleep -milliseconds $milliseconds
$mediaPlayer.stop()
$mediaPlayer.close()
$host.ui.RawUI.WindowTitle = $previousTitle
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
```
*(page generated by convert-ps2md.ps1 as of 01/23/2025 12:15:24)*