PowerShell Script to play video with Windows Media

2019-08-28 21:27发布

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

1条回答
够拽才男人
2楼-- · 2019-08-28 21:59

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
查看更多
登录 后发表回答