Rob van der Woude's Scripting Pages
Powered by GeSHi

Source code for detectsound1.cs

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

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

page last modified: 2025-10-11; loaded in 0.0094 seconds