summaryrefslogtreecommitdiff
path: root/webcam/com/neave/media/NeaveMicrophone.as
blob: 4f6e6c198786c6b3a48001674484dcdbf9aa1c42 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/**
 * Neave Microphone
 * 
 * Copyright (C) 2008 Paul Neave
 * http://www.neave.com/
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation at http://www.gnu.org/licenses/gpl.html
 */

package com.neave.media
{
	import flash.events.*;
	import flash.media.*;
	import flash.system.*;
	import flash.utils.*;
	
	public class NeaveMicrophone
	{
		static private var mic:Microphone;
		static private var gainTimer:Timer;
		
		public function NeaveMicrophone() { }
		
		/**
		 * Sets up and returns the microphone object
		 * 
		 * @return	A microphone object
		 */
		static public function getMicrophone():Microphone
		{
			// Return the same microphone if it has been successfully requested before
			if (mic != null)
			{
				if (mic.muted) Security.showSettings(SecurityPanel.PRIVACY);
				else NeaveMicrophone.startAutoGain();
				return mic;
			}
			
			gainTimer = new Timer(100);
			
			// Get the microphone
			mic = Microphone.getMicrophone();
			if (mic != null)
			{
				// Set properties if a microphone was found
				mic.setLoopBack(true);
				mic.rate = 44;
				mic.gain = 25;
				mic.setSilenceLevel(0);
				mic.setUseEchoSuppression(true);
				mic.soundTransform = new SoundTransform(0); // Mute microphone from sounding on speakers
				mic.addEventListener(StatusEvent.STATUS, NeaveMicrophone.statusListener);
				
				return mic;
			}
			else
			{
				// No microphone found
				Security.showSettings(SecurityPanel.MICROPHONE);
				return new Microphone();
			}
		}

		/**
		 * Microphone status response
		 */
		static private function statusListener(e:StatusEvent):void
		{
			if (e.code == "Microphone.Unmuted") NeaveMicrophone.startAutoGain();
			else NeaveMicrophone.stopAutoGain();
		}
		
		/**
		 * Set up gain control
		 */
		static public function startAutoGain():void
		{
			gainTimer.start();
			if (!gainTimer.hasEventListener(TimerEvent.TIMER)) gainTimer.addEventListener(TimerEvent.TIMER, setGain);
		}
		
		/**
		 * Stop gain control
		 */
		static public function stopAutoGain():void
		{
			gainTimer.stop();
			gainTimer.reset();
			gainTimer.removeEventListener(TimerEvent.TIMER, setGain);
		}
		
		/**
		 * Dynamically adjust the microphone's gain value
		 */
		static private function setGain(e:TimerEvent):void
		{
			if (mic.activityLevel < 15) mic.gain = 30;
			else if (mic.activityLevel > 90) mic.gain = 20;
			else mic.gain = 25;
		}
	}
}