Wednesday, 3 September 2014

HB Blog 14: Use Android Sensors To Detect Noise/Sound.

How to detect noise and set a noise threshold , when this noise/sound frequency cross threshold in Android?

Refer the below link for complete sample code:-
Download Sample Code
Download Apk File


Have a look on few code snippets,
 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
//Define runnable thread again and again detect noise
 private Runnable mSleepTask = new Runnable() {
               public void run() {
                   //Log.i("Noise", "runnable mSleepTask");
                   start();
               }
       };

  //Create runnable thread to Monitor Voice
       private Runnable mPollTask = new Runnable() {
               public void run() {
                       double amp = mSensor.getAmplitude();
                       //Log.i("Noise", "runnable mPollTask");
                       updateDisplay("Monitoring Voice...", amp);
                       if ((amp > mThreshold)) {
                             callForHelp();
                             //Log.i("Noise", "==== onCreate ===");
                       }
                       // Runnable(mPollTask) will again execute after POLL_INTERVAL
                       mHandler.postDelayed(mPollTask, POLL_INTERVAL);
               }
       };
       
  //onCreate
       @Override
       public void onCreate(Bundle savedInstanceState) {
               super.onCreate(savedInstanceState);
               // Defined SoundLevelView in main.xml file
               setContentView(R.layout.activity_main);
               mStatusView = (TextView) findViewById(R.id.status);
               // Used to record voice
               mSensor = new SoundMeter();
               mDisplay = (SoundLevelView) findViewById(R.id.volume);
               PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
               mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "NoiseAlert");
       }

//start Noise monitoring
   private void start() {
               mSensor.start();
               if (!mWakeLock.isHeld()) {
                       mWakeLock.acquire();
               }
               //Noise monitoring start
               // Runnable(mPollTask) will execute after POLL_INTERVAL
               mHandler.postDelayed(mPollTask, POLL_INTERVAL);
       }

No comments:

Post a Comment