0

I have a requirement to run a video via windows Media Player. And also track the duration it play. Suppose I close the video in 5 Sec it should give the duration 5. The below is the script I wrote. But there is problem with this. As the video do not launch nor I am able to the application getting launched . I am only able to here the audio.

Add-Type -AssemblyName presentationCore
 $filepath = [uri] "C:\Temp\test\Wildlife.wmv"
  $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.Seconds
 $wmplayer.Play()
 Start-Sleep $duration
 $wmplayer.Stop()
 $wmplayer.Close()
 Write-Host $duration

Please help... Regards, Suman Rout

Suman Rout
  • 11
  • 2
  • 4

1 Answers1

1

You need to be creating a form that shows up, then creating a VideoDrawing, then a DrawingBrush, and then applying it as the background of some portion of the form. From my understanding, MediaElement is easier to use - but regardless you're not starting media player here, you're using Windows Media objects without creating a form to display them on.

If you merely mean to open the video and close it, try launching the Windows Media Player application instead. I used your code and did something like maybe you're intending:

Add-Type -AssemblyName presentationCore
$filepath = "C:\Temp\test\Wildlife.wmv"

#Here we use your code to get the duration of the video
$wmplayer = New-Object System.Windows.Media.MediaPlayer
$wmplayer.Open($filepath)
Start-Sleep 2 
$duration = $wmplayer.NaturalDuration.TimeSpan.Seconds
$wmplayer.Close()

#Here we just open media player and play the file, with an extra second for it to start playing
$proc = Start-process -FilePath wmplayer.exe -ArgumentList $filepath -PassThru
Start-Sleep ($duration + 1)

#Here we kill the media player
Stop-Process $proc.Id -force

Write-Host $duration
Chris N
  • 7,239
  • 1
  • 24
  • 27
  • Hi Chris, Thank you for that. But when I close the player in between I get the below error and duration as 30 which is the complete duration of the video, not the duration for which the video ran......Stop-Process : Cannot find a process with the process identifier 7828. At line:16 char:1 + Stop-Process $proc.Id -force + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (7828:Int32) [Stop-Process], ProcessCommandException + FullyQualifiedErrorId : NoProcessFoundForGivenId,Microsoft.PowerShell.Commands.StopProcessCommand 30 – Suman Rout Sep 09 '16 at 08:50
  • Yeah - so if you want to catch that, check with Get-Process that something has that pid, if not, don't stop it. – Chris N Sep 09 '16 at 18:24