Powershell ISE 5.1 - WindowsMediaPlayer Class - Events not firing

Viewed 122

Does anyone know how to get the MediaEnded Event of the WindowsMediaPlayer Class to fire? The event is registered, but it's not firing. It's not an issue of the action, as I have tried outputting results using Out-file. I can use the Register-ObjectEvent command to fire events from Start-Job, but for some reason, MediaPlayer does not want to fire events.

cls
Unregister-Event *
Add-Type -AssemblyName PresentationCore 
$Player = [System.Windows.Media.MediaPlayer]::new()
$path = "D:\MineSweeper\Sound\Sounds\Bomb.wav"
$file = (Get-Item $path)
$Player.Open($file.FullName)
$player.Play()
$null = Register-ObjectEvent -InputObject $Player -EventName MediaEnded -Action {write-host "$(Get-Date)"}
Get-EventSubscriber
1 Answers

This is not really a PowerShell code or specific issue, as discussed here:

C# MediaPlayer.MediaEnded event not firing.

But here ...

I'm trying to use the 'MediaEnded' event handle to work out when the sound file has ended, then move onto the next sound file.

powershell 'system.windows.media.mediaplayer' Register-ObjectEvent

... is a workaround.

Add-Type -AssemblyName PresentationCore 
$_MediaPlayer = New-Object System.Windows.Media.MediaPlayer 
$_MusicFolder = 'C:\Users\Making JESUS Proud\Music'
$_MusicFiles = Get-ChildItem -path $_MusicFolder -include *.mp3 -recurse
$duration = $null
foreach($_file in $_MusicFiles){ 
     "Playing $($_file.BaseName)"
     [uri]$_song = $_file.FullName
     do {
        $_MediaPlayer.Open($_song)
        $_songDuration = $_MediaPlayer.NaturalDuration.TimeSpan.TotalMilliseconds
     }
     until ($_songDuration)
     $_MediaPlayer.Volume = 1
     $_MediaPlayer.Play()
     Start-Sleep -Milliseconds $_songDuration
     $_MediaPlayer.Stop()
     $_MediaPlayer.Close()
}
Related