Listening to Music in the Background

by Aug 25, 2016

PowerShell 3+

In the previous tip we presented to you a “Dancing Rick ASCII”, created by Lee Holmes. Lee uses music stored on his server as background. Here is an example that illustrates how you can spawn a background thread, and for example play music received from the Internet.

Just run this code, then call Start-Music to start the background music, and Stop-Music to stop it again.

function Start-Music
{
  $code = {
    $player = New-Object -ComObject 'MediaPlayer.MediaPlayer'
    $player.Open('http://www.leeholmes.com/projects/ps_html5/background.mp3')
    $player
  }

  $script:ps = [PowerShell]::Create()
  $script:player = @($ps.AddScript($code).Invoke())[0]
}

function Stop-Music
{
  if ($script:player -ne $null)
  {
    $script:player.Stop()
    Remove-Variable -Name player -Scope script
  }
  if ($script:ps -ne $null)
  {
    $script:ps.Runspace.Close()
    $script:ps.Dispose()
    Remove-Variable -Name ps -Scope script
  }
}

Twitter This Tip! ReTweet this Tip!