Playing Music in PowerShell

email me



# Play a single file
Add-Type -AssemblyName presentationCore
$mediaPlayer = New-Object system.windows.media.mediaplayer
$musicPath = "C:\music\"
$mediaPlayer.open($musicPath + 'PlayMyMusic.mp3')
$mediaPlayer.Play()
exit
 
# Create a playlist of files from folder
# Preview each song for 30 seconds
Add-Type -AssemblyName presentationCore
 
$mediaPlayer = New-Object system.windows.media.mediaplayer
$musicPath = "C:\music\"
$mediaPlayer.open([uri]"$($file.fullname)")

$musicFiles = Get-ChildItem -path $musicPath -include *.mp3,*.wma -recurse

foreach($file in $musicFiles)
{
 "Playing $($file.BaseName)"
  $mediaPlayer.open([uri]"$($file.fullname)")
  $mediaPlayer.Play()
  Start-Sleep -Seconds 30
  $mediaPlayer.Stop()
} 

 
 
Another method

Add-Type -AssemblyName presentationCore
 $filepath = [uri] "C:\Orchestra.mp3"
 $wmplayer = New-Object System.Windows.Media.MediaPlayer
 $wmplayer.Open($filepath)
 Start-Sleep 2 # This allows the $wmplayer time to load the audio file
 $duration = $wmplayer.NaturalDuration.TimeSpan.TotalSeconds
 $wmplayer.Play()
 Start-Sleep $duration
 $wmplayer.Stop()
 $wmplayer.Close()