Rob van der Woude's Scripting Pages
Powered by GeSHi

Source code for detectsound.cs

(view source code of detectsound.cs as plain text)

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Speech.Recognition;
  5.  
  6.  
  7. namespace RobvanderWoude
  8. {
  9. 	internal class DetectSound
  10. 	{
  11. 		static readonly string progver = "1.01";
  12.  
  13. 		static SpeechRecognitionEngine recognizer;
  14. 		static System.Timers.Timer timer;
  15. 		static TimeSpan interval = TimeSpan.FromSeconds( 10 );
  16. 		static int timeout = 10;
  17. 		static int linelength;
  18. 		static bool quiet = false;
  19. 		static readonly string decimalseparator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
  20.  
  21.  
  22. 		static int Main( string[] args )
  23. 		{
  24. 			int rc = 0;
  25.  
  26. 			if ( args.Length == 1 || args.Length == 2 )
  27. 			{
  28. 				foreach ( string arg in args )
  29. 				{
  30. 					if ( arg == "/?" )
  31. 					{
  32. 						return ShowHelp( );
  33. 					}
  34. 					else if ( arg.ToUpper( ) == "/Q" )
  35. 					{
  36. 						if ( quiet )
  37. 						{
  38. 							return ShowHelp( "Duplicate command line switch /Q" );
  39. 						}
  40. 						quiet = true;
  41. 					}
  42. 					else if ( int.TryParse( arg, out timeout ) )
  43. 					{
  44. 						if ( timeout < 1 || timeout > 600 )
  45. 						{
  46. 							return ShowHelp( "Specified timeout out of range (0{0}5..600)", decimalseparator );
  47. 						}
  48. 						interval = TimeSpan.FromSeconds( timeout );
  49. 					}
  50. 					else if ( float.TryParse( arg.Replace( ".", decimalseparator ).Replace( ",", decimalseparator ), out float timeoutfloat ) )
  51. 					{
  52. 						if ( timeoutfloat < 0.5 || timeoutfloat > 600 )
  53. 						{
  54. 							return ShowHelp( "Specified timeout out of range (0{0}5..600)", decimalseparator );
  55. 						}
  56. 						timeout = (int)timeoutfloat;
  57. 						interval = TimeSpan.FromSeconds( timeoutfloat );
  58. 					}
  59. 					else
  60. 					{
  61. 						return ShowHelp( "Invalid command line argument \"{0}\"", arg );
  62. 					}
  63. 				}
  64. 			}
  65. 			else if ( args.Length > 2 )
  66. 			{
  67. 				return ShowHelp( "Invalid command line arguments" );
  68. 			}
  69.  
  70. 			if ( !quiet )
  71. 			{
  72. 				timer = new System.Timers.Timer( );
  73. 				timer.Interval = 1000;
  74. 				timer.Elapsed += Timer_Elapsed;
  75. 				timer.Start( );
  76. 			}
  77.  
  78. 			// Based on source code by Wendy Zang
  79. 			// https://social.msdn.microsoft.com/Forums/vstudio/en-US/72f769f3-1465-402a-b090-86d0ce0530c5/c-console-application-how-to-detect-the-mic-input#3a1a664c-db49-4152-a2bd-080a03287b9f
  80. 			recognizer = new SpeechRecognitionEngine( );
  81. 			Grammar dictationGrammar = new DictationGrammar( );
  82. 			recognizer.LoadGrammar( dictationGrammar );
  83. 			try
  84. 			{
  85. 				if ( !quiet )
  86. 				{
  87. 					Console.Write( "Speak, you've got {0} seconds left \b", timeout );
  88. 				}
  89. 				recognizer.SetInputToDefaultAudioDevice( );
  90. 				recognizer.SpeechDetected += Recognizer_SpeechDetected;
  91. 				recognizer.Recognize( interval );
  92. 			}
  93. 			catch ( InvalidOperationException e )
  94. 			{
  95. 				rc = ShowHelp( "Default microphone not detected\n{0} - {1}.", e.Source, e.Message );
  96. 			}
  97. 			finally
  98. 			{
  99. 				if ( !quiet )
  100. 				{
  101. 					timer.Stop( );
  102. 				}
  103. 				recognizer.UnloadAllGrammars( );
  104. 			}
  105. 			if ( !quiet )
  106. 			{
  107. 				Console.Write( new string( '\b', linelength ) );
  108. 				Console.Write( new string( ' ', linelength ) );
  109. 				Console.Write( new string( '\b', linelength ) );
  110. 			}
  111. 			Console.ForegroundColor = ConsoleColor.Red;
  112. 			Console.WriteLine( "Silence only, no sound detected" );
  113. 			Console.ResetColor( );
  114. 			return rc;
  115. 		}
  116.  
  117.  
  118. 		private static void Timer_Elapsed( object sender, System.Timers.ElapsedEventArgs e )
  119. 		{
  120. 			string message = "Speak, you've got {0} seconds left \b";
  121. 			linelength = string.Format( message, timeout ).Length;
  122. 			Console.Write( new string( '\b', linelength ) );
  123. 			Console.Write( new string( ' ', linelength ) );
  124. 			Console.Write( new string( '\b', linelength ) );
  125. 			timeout--;
  126. 			if ( timeout >= 0 )
  127. 			{
  128. 				Console.Write( message, timeout );
  129. 			}
  130. 		}
  131.  
  132.  
  133. 		private static void Recognizer_SpeechDetected( object sender, SpeechDetectedEventArgs e )
  134. 		{
  135. 			if ( !quiet )
  136. 			{
  137. 				timer.Stop( );
  138. 				Console.Write( new string( '\b', linelength ) );
  139. 				Console.Write( new string( ' ', linelength ) );
  140. 				Console.Write( new string( '\b', linelength ) );
  141. 			}
  142. 			Console.ForegroundColor = ConsoleColor.Green;
  143. 			Console.WriteLine( "Sound detected" );
  144. 			Console.ResetColor( );
  145. 			Environment.Exit( 1 );
  146. 		}
  147.  
  148.  
  149. 		#region Error handling
  150.  
  151. 		static int ShowHelp( params string[] errmsg )
  152. 		{
  153. 			#region Error Message
  154.  
  155. 			if ( errmsg.Length > 0 )
  156. 			{
  157. 				List<string> errargs = new List<string>( errmsg );
  158. 				errargs.RemoveAt( 0 );
  159. 				Console.Error.WriteLine( );
  160. 				Console.ForegroundColor = ConsoleColor.Red;
  161. 				Console.Error.Write( "ERROR:\t" );
  162. 				Console.ForegroundColor = ConsoleColor.White;
  163. 				Console.Error.WriteLine( errmsg[0], errargs.ToArray( ) );
  164. 				Console.ResetColor( );
  165. 			}
  166.  
  167. 			#endregion Error Message
  168.  
  169.  
  170. 			#region Help Text
  171.  
  172. 			/*
  173. 			DetectSound.exe,  Version 1.00
  174. 			Detect sound input on default microphone before detection period expires
  175. ?
  176. 			Usage:    DetectSound.exe  [ timeout ]  [ /Q ]
  177. ?
  178. 			Where:    timeout     detection period in seconds (0.5..600; default: 10)
  179. 			          /Q          Quiet mode: no messages except result
  180.  
  181. 			Credits:  Based on source code by Wendy Zang
  182. 			          https://social.msdn.microsoft.com/Forums/vstudio/en-US
  183. 			          /72f769f3-1465-402a-b090-86d0ce0530c5
  184. 			          /c-console-application-how-to-detect-the-mic-input
  185. 			          #3a1a664c-db49-4152-a2bd-080a03287b9f
  186. ?
  187. 			Notes:    This program uses Microsoft's speech recognition technology
  188. 			          to detect sound, so it will be sensitive to speech and yells,
  189. 			          but less so to other noises like clapping or whistling.
  190. 			          Decimal separator for timeout may be dot or comma.
  191. 			          Return code 0 if sound is detected within the timeout period,
  192. 			          1 if not, or -1 in case of errors
  193. ?
  194. 			Written by Rob van der Woude
  195. 			https://www.robvanderwoude.com
  196. 			*/
  197.  
  198. 			#endregion Help Text
  199.  
  200.  
  201. 			#region Display Help Text
  202.  
  203. 			Console.Error.WriteLine( );
  204.  
  205. 			Console.Error.WriteLine( "DetectSound.exe,  Version {0}", progver );
  206.  
  207. 			Console.Error.WriteLine( "Detect sound input on default microphone before detection period expires" );
  208.  
  209. 			Console.Error.WriteLine( );
  210.  
  211. 			Console.Error.Write( "Usage:    " );
  212. 			Console.ForegroundColor = ConsoleColor.White;
  213. 			Console.Error.WriteLine( "DetectSound.exe  [ timeout ]  [ /Q ]" );
  214. 			Console.ResetColor( );
  215.  
  216. 			Console.Error.WriteLine( );
  217.  
  218. 			Console.Error.Write( "Where:    " );
  219. 			Console.ForegroundColor = ConsoleColor.White;
  220. 			Console.Error.Write( "timeout" );
  221. 			Console.ResetColor( );
  222. 			Console.Error.WriteLine( "     detection period in seconds (0{0}5..600; default: 10)", decimalseparator );
  223.  
  224. 			Console.ForegroundColor = ConsoleColor.White;
  225. 			Console.Error.Write( "          /Q          Q" );
  226. 			Console.ResetColor( );
  227. 			Console.Error.WriteLine( "uiet mode: no messages except result" );
  228.  
  229. 			Console.Error.WriteLine( );
  230.  
  231. 			Console.Error.WriteLine( "Credits:  Based on source code by Wendy Zang" );
  232.  
  233. 			Console.ForegroundColor = ConsoleColor.DarkGray;
  234. 			Console.Error.WriteLine( "          https://social.msdn.microsoft.com/Forums/vstudio/en-US" );
  235.  
  236. 			Console.Error.WriteLine( "          /72f769f3-1465-402a-b090-86d0ce0530c5" );
  237.  
  238. 			Console.Error.WriteLine( "          /c-console-application-how-to-detect-the-mic-input" );
  239.  
  240. 			Console.Error.WriteLine( "          #3a1a664c-db49-4152-a2bd-080a03287b9f" );
  241. 			Console.ResetColor( );
  242.  
  243. 			Console.Error.WriteLine( );
  244.  
  245. 			Console.Error.WriteLine( "Notes:    This program uses Microsoft's speech recognition technology" );
  246.  
  247. 			Console.Error.WriteLine( "          to detect sound, so it will be sensitive to speech and yells," );
  248.  
  249. 			Console.Error.WriteLine( "          but less so to other noises like clapping or whistling." );
  250.  
  251. 			Console.Error.WriteLine( "          Decimal separator for timeout may be dot or comma." );
  252.  
  253. 			Console.Error.WriteLine( "          Return code 0 if sound is detected within the timeout period," );
  254.  
  255. 			Console.Error.WriteLine( "          1 if not, or -1 in case of errors" );
  256.  
  257. 			Console.Error.WriteLine( );
  258.  
  259. 			Console.Error.WriteLine( "Written by Rob van der Woude" );
  260.  
  261. 			Console.Error.WriteLine( "https://www.robvanderwoude.com" );
  262.  
  263. 			#endregion Display Help Text
  264.  
  265.  
  266. 			return -1;
  267. 		}
  268.  
  269. 		#endregion Error handling
  270. 	}
  271. }

page last modified: 2022-10-20