public void UpdateMeter() { try{ recorder.UpdateMeters(); //lblDisplay.Text = recorder.PeakPower(0).ToString (); if (recorder.PeakPower(0) == 0) { UserKnocked(); } }catch { } }
protected override async Task <List <Datum> > PollAsync(CancellationToken cancellationToken) { AVAudioRecorder recorder = null; string recordPath = Path.GetTempFileName(); try { AVAudioSession audioSession = AVAudioSession.SharedInstance(); NSError error = audioSession.SetCategory(AVAudioSessionCategory.Record); if (error != null) { throw new Exception("Failed to initialize iOS audio recording session: " + error.LocalizedDescription); } error = audioSession.SetActive(true); if (error != null) { throw new Exception("Failed to make audio session active: " + error.LocalizedDescription); } recorder = AVAudioRecorder.Create(NSUrl.FromFilename(recordPath), new AudioSettings(_settings), out error); if (error != null) { throw new Exception("Failed to create sound recorder: " + error.LocalizedDescription); } recorder.MeteringEnabled = true; // we need to take a meter reading while the recorder is running, so record for one second beyond the sample length if (recorder.RecordFor(SampleLengthMS / 1000d + 1)) { await Task.Delay(SampleLengthMS); recorder.UpdateMeters(); double decibels = 100 * (recorder.PeakPower(0) + 160) / 160f; // range looks to be [-160 - 0] from http://b2cloud.com.au/tutorial/obtaining-decibels-from-the-ios-microphone return(new Datum[] { new SoundDatum(DateTimeOffset.UtcNow, decibels) }.ToList()); } else { throw new Exception("Failed to start recording."); } } finally { try { File.Delete(recordPath); } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Failed to delete sound file: " + ex.Message, LoggingLevel.Debug, GetType()); } if (recorder != null) { try { recorder.Stop(); } catch (Exception) { } try { recorder.Dispose(); } catch (Exception) { } } } }