PowerShell/scripts/play-mp3.ps1

50 lines
1.4 KiB
PowerShell
Raw Normal View History

2023-10-31 11:25:11 +01:00
<#
2021-07-13 21:10:02 +02:00
.SYNOPSIS
2021-11-26 17:17:18 +01:00
Plays a MP3 sound file
2021-07-13 21:10:02 +02:00
.DESCRIPTION
2022-02-10 08:57:52 +01:00
This PowerShell script plays a sound file in .MP3 file format.
2021-11-26 17:17:18 +01:00
.PARAMETER Path
2021-10-16 16:50:10 +02:00
Specifies the path to the .MP3 file
2021-07-13 21:10:02 +02:00
.EXAMPLE
2021-09-24 17:19:49 +02:00
PS> ./play-mp3 C:\thunder.mp3
2021-07-13 21:10:02 +02:00
.LINK
https://github.com/fleschutz/PowerShell
2022-09-06 21:42:04 +02:00
.NOTES
Author: Markus Fleschutz | License: CC0
2021-02-16 20:03:32 +01:00
#>
2021-11-26 17:17:18 +01:00
param([string]$Path = "")
2021-02-18 20:17:55 +01:00
2021-02-16 20:03:32 +01:00
try {
2023-03-01 10:52:37 +01:00
if ($Path -eq "" ) { $Path = Read-Host "Enter the path to the MP3 sound file" }
2021-07-15 15:51:22 +02:00
2023-03-01 10:52:37 +01:00
if (-not(Test-Path "$Path" -pathType leaf)) { throw "Can't access sound file: $Path" }
$FullPath = (Get-ChildItem $Path).fullname
$Filename = (Get-Item "$FullPath").name
2021-04-21 10:14:57 +02:00
2023-03-01 10:52:37 +01:00
Add-Type -assemblyName PresentationCore
$MediaPlayer = New-Object System.Windows.Media.MediaPlayer
2021-02-20 12:08:05 +01:00
do {
$MediaPlayer.open($FullPath)
2021-04-21 10:14:57 +02:00
$Milliseconds = $MediaPlayer.NaturalDuration.TimeSpan.TotalMilliseconds
} until ($Milliseconds)
2021-04-30 20:39:06 +02:00
2021-04-21 10:14:57 +02:00
[int]$Minutes = $Milliseconds / 60000
[int]$Seconds = ($Milliseconds / 1000) % 60
2021-11-26 17:17:18 +01:00
"▶️ Playing $Filename for $($Minutes.ToString('00')):$($Seconds.ToString('00')) sec..."
2021-05-06 16:19:50 +02:00
$PreviousTitle = $host.ui.RawUI.WindowTitle
$host.ui.RawUI.WindowTitle = "▶️ $Filename"
2021-02-20 12:08:05 +01:00
$MediaPlayer.Volume = 1
2021-02-17 20:09:44 +01:00
$MediaPlayer.play()
2023-03-01 10:52:37 +01:00
Start-Sleep -milliseconds $Milliseconds
2021-02-20 12:08:05 +01:00
$MediaPlayer.stop()
$MediaPlayer.close()
2021-05-06 16:19:50 +02:00
$host.ui.RawUI.WindowTitle = $PreviousTitle
2021-02-17 20:09:44 +01:00
2021-09-27 10:09:45 +02:00
exit 0 # success
2021-02-16 20:03:32 +01:00
} catch {
2022-04-13 12:06:32 +02:00
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
2021-02-16 20:03:32 +01:00
exit 1
}