PowerShell/scripts/play-mp3.ps1

54 lines
1.5 KiB
PowerShell
Raw Normal View History

2024-10-01 15:24:16 +02:00
<#
2021-07-13 21:10:02 +02:00
.SYNOPSIS
2024-04-18 09:03:21 +02:00
Plays a .MP3 sound file
2021-07-13 21:10:02 +02:00
.DESCRIPTION
2024-04-18 09:03:21 +02:00
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
2021-07-13 21:10:02 +02:00
.EXAMPLE
2024-04-18 09:03:21 +02:00
PS> ./play-mp3.ps1 C:\thunder.mp3
2024-11-21 08:07:03 +01:00
Playing 'thunder.mp3' (00:03) ...
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
#>
2024-04-18 09:03:21 +02:00
param([string]$path = "")
2021-02-18 20:17:55 +01:00
2021-02-16 20:03:32 +01:00
try {
2024-04-18 09:03:21 +02:00
if ($path -eq "" ) { $path = Read-Host "Enter the file path to the MP3 sound file" }
2021-07-15 15:51:22 +02:00
2024-04-18 09:03:21 +02: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
2024-04-18 09:03:21 +02:00
$mediaPlayer = New-Object System.Windows.Media.MediaPlayer
2021-02-20 12:08:05 +01:00
do {
2024-04-18 09:03:21 +02:00
$mediaPlayer.open($fullPath)
$milliseconds = $mediaPlayer.NaturalDuration.TimeSpan.TotalMilliseconds
} until ($milliseconds)
2021-02-17 20:09:44 +01:00
2024-04-18 09:03:21 +02:00
[int]$minutes = $milliseconds / 60000
[int]$seconds = ($milliseconds / 1000) % 60
Write-Host " ▶️" -noNewline -foregroundColor green
2024-11-21 08:07:03 +01:00
Write-Host "Playing '$filename' ($($minutes.ToString('00')):$($seconds.ToString('00'))) ..."
2024-04-18 09:03:21 +02:00
$previousTitle = $host.ui.RawUI.WindowTitle
$host.ui.RawUI.WindowTitle = "▶️ $filename"
2024-11-21 08:07:03 +01:00
2024-04-18 09:03:21 +02:00
$mediaPlayer.Volume = 1
$mediaPlayer.play()
Start-Sleep -milliseconds $milliseconds
$mediaPlayer.stop()
$mediaPlayer.close()
2024-11-21 08:07:03 +01:00
2024-04-18 09:03:21 +02:00
$host.ui.RawUI.WindowTitle = $previousTitle
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
}