2

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
Chris
  • 135
  • 1
  • 1
  • 9

1 Answers1

0

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()
}
postanote
  • 15,138
  • 2
  • 14
  • 25
  • Thanks postanote, but I already have such a workaround. The issue is that incorporating the workaround into my script is so vastly more complicated that I have yet to figure out how to do it and so I would like to see if mediaplayer events are usable. I've been working on this issue for over a month and still haven't gotten my workaround or the mediaplayer events to work. To get the workaround to somehow work for my case, I've sent the workaround code into another thread using Start-Job. That job updates a text file that my main script can read. How to trigger event when text file changes? – Chris Oct 11 '20 at 20:56
  • @postanote, if the gist of your answer is a _verbatim copy_ of an answer to another question, please post a _comment_ containing a _link_ instead of an answer. – mklement0 Oct 11 '20 at 23:30
  • @user117294, consider a `FileSystemWatcher`-based solution - see [this answer](https://stackoverflow.com/a/59772743/45375), for example. – mklement0 Oct 11 '20 at 23:36