@@ -57,7 +57,7 @@ private void registerWith(BinaryMessenger messenger) {
5757 private EventChannel .EventSink eventSink ;
5858
5959 // Audio recorder + initial values
60- private static volatile AudioRecord recorder ;
60+ private static volatile AudioRecord recorder = null ;
6161
6262 private int AUDIO_SOURCE = MediaRecorder .AudioSource .DEFAULT ;
6363 private int SAMPLE_RATE = 16000 ;
@@ -90,16 +90,28 @@ public void onMethodCall(MethodCall call, Result result) {
9090 }
9191 }
9292
93+ private void initRecorder () {
94+ // Try to initialize and start the recorder
95+ recorder = new AudioRecord (AUDIO_SOURCE , SAMPLE_RATE , CHANNEL_CONFIG , AUDIO_FORMAT , BUFFER_SIZE );
96+ if (recorder .getState () != AudioRecord .STATE_INITIALIZED ) {
97+ eventSink .error ("-1" , "PlatformError" , null );
98+ return ;
99+ }
100+
101+ recorder .startRecording ();
102+ }
103+
93104 private final Runnable runnable = new Runnable () {
94105 @ Override
95106 public void run () {
107+ if (recorder == null ) initRecorder ();
96108 isRecording = true ;
97-
109+
98110 actualSampleRate = recorder .getSampleRate ();
99111 actualBitDepth = (recorder .getAudioFormat () == AudioFormat .ENCODING_PCM_8BIT ? 8 : 16 );
100112
101113 // Wait until recorder is initialised
102- while (recorder .getRecordingState () != AudioRecord .RECORDSTATE_RECORDING );
114+ while (recorder == null || recorder .getRecordingState () != AudioRecord .RECORDSTATE_RECORDING );
103115
104116 // Repeatedly push audio samples to stream
105117 while (record ) {
@@ -194,15 +206,6 @@ public void onListen(Object args, final EventChannel.EventSink eventSink) {
194206
195207 this .eventSink = new MainThreadEventSink (eventSink );
196208
197- // Try to initialize and start the recorder
198- recorder = new AudioRecord (AUDIO_SOURCE , SAMPLE_RATE , CHANNEL_CONFIG , AUDIO_FORMAT , BUFFER_SIZE );
199- if (recorder .getState () != AudioRecord .STATE_INITIALIZED ) {
200- eventSink .error ("-1" , "PlatformError" , null );
201- return ;
202- }
203-
204- recorder .startRecording ();
205-
206209 // Start runnable
207210 record = true ;
208211 new Thread (runnable ).start ();
@@ -212,12 +215,13 @@ record = true;
212215 public void onCancel (Object o ) {
213216 // Stop runnable
214217 record = false ;
218+ while (isRecording );
215219 if (recorder != null ) {
216220 // Stop and reset audio recorder
217221 recorder .stop ();
218222 recorder .release ();
219- recorder = null ;
220223 }
224+ recorder = null ;
221225 }
222226}
223227
0 commit comments