PoshCode Logo PowerShell Code Repository

play-note(s) (modification of post by karl prosser view diff)
diff | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/835"></script>download | new post

code to play distinct “musical” notes using Console.Beep allowing you to specify the note/octave/duration as well as speaking
-Karl Prosser

  1. function Play-Note([string]$note,[int] $duration = 5)  
  2. {  
  3.   if (!($note -match '(\d+)')) { $note+='4' };[void]($note -match '([A-G#]{1,2})(\d+)')  
  4.   [console]::Beep((440 * [math]::Pow([math]::pow(2,(1/12)),
  5.     (([int] $matches[2]) - 4)* 12 + $( switch($matches[1])  
  6.   {  'A'  { 0 }  'A#' { 1 }  'Bb' { 1 }  'B'  { 2 }  'C'  { 3 }  'C#' { 4 }  'Db' { 4 }  
  7.      'D'  { 5 }  'D#' { 6 }  'Eb' { 6 }  'E'  { 7 }  'F'  { 8 }  'F#' { 9 }  'Gb' { 9 }  
  8.      'G'  { 10 } 'G#' { 11 } 'Ab' { 11 }  
  9.   }))),$duration * 100 )    
  10. }  
  11.  
  12. function Speak-words ([string]$words,[bool]$pause = $true)
  13. {   $flag = 1
  14.     if ($pause) {$flag = 2}
  15.     $voice = new-Object -com SAPI.spvoice
  16.     $voice.speak($words, [int] $flag) # 2 means wait until speaking is finished to continue
  17. }
  18.  
  19.  
  20. function Play-Notes
  21. {
  22. $defaultduration = 5;if($args[0] -is [int]) {$defaultduration = $args[0]}
  23. for($i = 0;$i -lt $args.length;$i++)
  24.  {    $duration = $defaultduration
  25.     if ($i -lt $args.length-1) { if ($args[$i+1] -is [int]) {$duration = $args[$i+1] } }
  26.     if ($args[$i] -is [string]) {
  27.         if ($args[$i].startswith("!")) { speak-words $args[$i].replace('!','') } else
  28.         { play-note $args[$i] $duration }
  29.         }
  30.  }
  31. }
  32.  
  33. play-notes A B C 20 E 10 B 10
  34. play-notes A B C 20 E 10 B 10
  35. play-notes F5 2 E5 2 D5 2 C5 2 B5 2 A5 2 G 4 F5 2 E5 2 D5 2 C5 2 B5 2 A5 2 G 4
  36. play-notes 2 F5 E5 D5 C5 B5 A5 G 4 F5 E5 D5 C5 B5 A5 G 4
  37. play-notes 4 F5 E5 D5 C5 B5 A5 G F5 E5 D5 C5 B5 A5 G
  38. play-notes "!here we go now" Db5 Db Eb Gb Ab "C#" 6 !YEAH
  39. play-notes A "!$([datetime]::now)" C

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me