PoshCode Logo PowerShell Code Repository

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

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

  1. function Play-Notes
  2. {
  3. $defaultduration = 5;if($args[0] -is [int]) {$defaultduration = $args[0]}
  4. for($i = 0;$i -lt $args.length;$i++)
  5.  {    
  6.     $duration = $defaultduration
  7.     if ($i -lt $args.length-1) { if ($args[$i+1] -is [int]) {$duration = $args[$i+1] } }
  8.     if ($args[$i] -is [string]) { play-note $args[$i] $duration }
  9.  }
  10. }
  11.  
  12. function Play-Note([string]$note,[int] $duration = 5)  
  13. {  
  14.   if (!($note -match '(\d+)')) { $note+='4' };[void]($note -match '([A-G#]{1,2})(\d+)')  
  15.   [console]::Beep((440 * [math]::Pow([math]::pow(2,(1/12)),
  16.     (([int] $matches[2]) - 4)* 12 + $( switch($matches[1])  
  17.   {  'A'  { 0 }  'A#' { 1 }  'Bb' { 1 }  'B'  { 2 }  'C'  { 3 }  'C#' { 4 }  'Db' { 4 }  
  18.      'D'  { 5 }  'D#' { 6 }  'Eb' { 6 }  'E'  { 7 }  'F'  { 8 }  'F#' { 9 }  'Gb' { 9 }  
  19.      'G'  { 10 } 'G#' { 11 } 'Ab' { 11 }  
  20.   }))),$duration * 100 )    
  21. }  
  22.  
  23. PLAY-note "C#3"
  24.  
  25. play-notes A B C 20 E 10 B 10
  26. 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
  27. play-notes 2 F5 E5 D5 C5 B5 A5 G 4 F5 E5 D5 C5 B5 A5 G 4
  28. play-notes 4 F5 E5 D5 C5 B5 A5 G F5 E5 D5 C5 B5 A5 G
  29. play-notes Db5 Db Eb Gb Ab "C#" 6

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