-
Notifications
You must be signed in to change notification settings - Fork 110
/
SoundStreamPlugin.kt
397 lines (346 loc) · 15 KB
/
SoundStreamPlugin.kt
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
package vn.casperpas.sound_stream
import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.media.*
import android.media.AudioRecord.OnRecordPositionUpdateListener
import android.util.Log
import androidx.annotation.NonNull
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugin.common.PluginRegistry.Registrar
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.ShortBuffer
const val methodChannelName = "vn.casperpas.sound_stream:methods"
enum class SoundStreamErrors {
FailedToRecord,
FailedToPlay,
FailedToStop,
FailedToWriteBuffer,
Unknown,
}
enum class SoundStreamStatus {
Unset,
Initialized,
Playing,
Stopped,
}
/** SoundStreamPlugin */
public class SoundStreamPlugin : FlutterPlugin,
MethodCallHandler,
PluginRegistry.RequestPermissionsResultListener,
ActivityAware {
private val logTag = "SoundStreamPlugin"
private val audioRecordPermissionCode = 14887
private lateinit var methodChannel: MethodChannel
private var currentActivity: Activity? = null
private var pluginContext: Context? = null
private var permissionToRecordAudio: Boolean = false
private var activeResult: Result? = null
private var debugLogging: Boolean = false
//========= Recorder's vars
private val mRecordFormat = AudioFormat.ENCODING_PCM_16BIT
private var mRecordSampleRate = 16000 // 16Khz
private var mRecorderBufferSize = 8192
private var mPeriodFrames = 8192
private var audioData: ShortArray? = null
private var mRecorder: AudioRecord? = null
private var mListener: OnRecordPositionUpdateListener? = null
//========= Player's vars
private var mAudioTrack: AudioTrack? = null
private var mPlayerSampleRate = 16000 // 16Khz
private var mPlayerBufferSize = 10240
private var mPlayerFormat: AudioFormat = AudioFormat.Builder()
.setEncoding(AudioFormat.ENCODING_PCM_16BIT)
.setChannelMask(AudioFormat.CHANNEL_OUT_MONO)
.setSampleRate(mPlayerSampleRate)
.build()
/** ======== Basic Plugin initialization ======== **/
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
onAttachedToEngine(flutterPluginBinding.applicationContext, flutterPluginBinding.binaryMessenger)
}
// This static function is optional and equivalent to onAttachedToEngine. It supports the old
// pre-Flutter-1.12 Android projects. You are encouraged to continue supporting
// plugin registration via this function while apps migrate to use the new Android APIs
// post-flutter-1.12 via https://flutter.dev/go/android-project-migration.
//
// It is encouraged to share logic between onAttachedToEngine and registerWith to keep
// them functionally equivalent. Only one of onAttachedToEngine or registerWith will be called
// depending on the user's project. onAttachedToEngine or registerWith must both be defined
// in the same class.
companion object {
@JvmStatic
fun registerWith(registrar: Registrar) {
val plugin = SoundStreamPlugin()
plugin.currentActivity = registrar.activity()
registrar.addRequestPermissionsResultListener(plugin)
plugin.onAttachedToEngine(registrar.context(), registrar.messenger())
}
}
override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
try {
when (call.method) {
"hasPermission" -> hasPermission(result)
"initializeRecorder" -> initializeRecorder(call, result)
"startRecording" -> startRecording(result)
"stopRecording" -> stopRecording(result)
"initializePlayer" -> initializePlayer(call, result)
"startPlayer" -> startPlayer(result)
"stopPlayer" -> stopPlayer(result)
"writeChunk" -> writeChunk(call, result)
else -> result.notImplemented()
}
} catch (e: Exception) {
Log.e(logTag, "Unexpected exception", e)
result.error(SoundStreamErrors.Unknown.name,
"Unexpected exception", e.localizedMessage)
}
}
private fun onAttachedToEngine(applicationContext: Context, messenger: BinaryMessenger) {
pluginContext = applicationContext
methodChannel = MethodChannel(messenger, methodChannelName)
methodChannel.setMethodCallHandler(this)
}
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
methodChannel.setMethodCallHandler(null)
mListener?.onMarkerReached(null)
mListener?.onPeriodicNotification(null)
mListener = null
mRecorder?.stop()
mRecorder?.release()
mRecorder = null
}
override fun onDetachedFromActivity() {
// currentActivity
}
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
currentActivity = binding.activity
binding.addRequestPermissionsResultListener(this)
}
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
currentActivity = binding.activity
binding.addRequestPermissionsResultListener(this)
}
override fun onDetachedFromActivityForConfigChanges() {
// currentActivity = null
}
/** ======== Plugin methods ======== **/
private fun hasRecordPermission(): Boolean {
if (permissionToRecordAudio) return true
val localContext = pluginContext
permissionToRecordAudio = localContext != null && ContextCompat.checkSelfPermission(localContext,
Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
return permissionToRecordAudio
}
private fun hasPermission(result: Result) {
result.success(hasRecordPermission())
}
private fun requestRecordPermission() {
val localActivity = currentActivity
if (!hasRecordPermission() && localActivity != null) {
debugLog("requesting RECORD_AUDIO permission")
ActivityCompat.requestPermissions(localActivity,
arrayOf(Manifest.permission.RECORD_AUDIO), audioRecordPermissionCode)
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>?,
grantResults: IntArray?): Boolean {
when (requestCode) {
audioRecordPermissionCode -> {
if (grantResults != null) {
permissionToRecordAudio = grantResults.isNotEmpty() &&
grantResults[0] == PackageManager.PERMISSION_GRANTED
}
completeInitializeRecorder()
return true
}
}
return false
}
private fun initializeRecorder(@NonNull call: MethodCall, @NonNull result: Result) {
mRecordSampleRate = call.argument<Int>("sampleRate") ?: mRecordSampleRate
debugLogging = call.argument<Boolean>("showLogs") ?: false
mPeriodFrames = AudioRecord.getMinBufferSize(mRecordSampleRate, AudioFormat.CHANNEL_IN_MONO, mRecordFormat)
mRecorderBufferSize = mPeriodFrames * 2
audioData = ShortArray(mPeriodFrames)
activeResult = result
val localContext = pluginContext
if (null == localContext) {
completeInitializeRecorder()
return
}
permissionToRecordAudio = ContextCompat.checkSelfPermission(localContext,
Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
if (!permissionToRecordAudio) {
requestRecordPermission()
} else {
debugLog("has permission, completing")
completeInitializeRecorder()
}
debugLog("leaving initializeIfPermitted")
}
private fun initRecorder() {
if (mRecorder?.state == AudioRecord.STATE_INITIALIZED) {
return
}
mRecorder = AudioRecord(MediaRecorder.AudioSource.MIC, mRecordSampleRate, AudioFormat.CHANNEL_IN_MONO, mRecordFormat, mRecorderBufferSize)
if (mRecorder != null) {
mListener = createRecordListener()
mRecorder?.positionNotificationPeriod = mPeriodFrames
mRecorder?.setRecordPositionUpdateListener(mListener)
}
}
private fun completeInitializeRecorder() {
debugLog("completeInitialize")
val initResult: HashMap<String, Any> = HashMap()
if (permissionToRecordAudio) {
mRecorder?.release()
initRecorder()
initResult["isMeteringEnabled"] = true
sendRecorderStatus(SoundStreamStatus.Initialized)
}
initResult["success"] = permissionToRecordAudio
debugLog("sending result")
activeResult?.success(initResult)
debugLog("leaving complete")
activeResult = null
}
private fun sendEventMethod(name: String, data: Any) {
val eventData: HashMap<String, Any> = HashMap()
eventData["name"] = name
eventData["data"] = data
methodChannel.invokeMethod("platformEvent", eventData)
}
private fun debugLog(msg: String) {
if (debugLogging) {
Log.d(logTag, msg)
}
}
private fun startRecording(result: Result) {
try {
if (mRecorder!!.recordingState == AudioRecord.RECORDSTATE_RECORDING) {
result.success(true)
return
}
initRecorder()
mRecorder!!.startRecording()
sendRecorderStatus(SoundStreamStatus.Playing)
result.success(true)
} catch (e: IllegalStateException) {
debugLog("record() failed")
result.error(SoundStreamErrors.FailedToRecord.name, "Failed to start recording", e.localizedMessage)
}
}
private fun stopRecording(result: Result) {
try {
if (mRecorder!!.recordingState == AudioRecord.RECORDSTATE_STOPPED) {
result.success(true)
return
}
mRecorder!!.stop()
sendRecorderStatus(SoundStreamStatus.Stopped)
result.success(true)
} catch (e: IllegalStateException) {
debugLog("record() failed")
result.error(SoundStreamErrors.FailedToRecord.name, "Failed to start recording", e.localizedMessage)
}
}
private fun sendRecorderStatus(status: SoundStreamStatus) {
sendEventMethod("recorderStatus", status.name)
}
private fun initializePlayer(@NonNull call: MethodCall, @NonNull result: Result) {
mPlayerSampleRate = call.argument<Int>("sampleRate") ?: mPlayerSampleRate
debugLogging = call.argument<Boolean>("showLogs") ?: false
mPlayerFormat = AudioFormat.Builder()
.setEncoding(AudioFormat.ENCODING_PCM_16BIT)
.setChannelMask(AudioFormat.CHANNEL_OUT_MONO)
.setSampleRate(mPlayerSampleRate)
.build()
mPlayerBufferSize = AudioTrack.getMinBufferSize(mPlayerSampleRate, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT)
if (mAudioTrack?.state == AudioTrack.STATE_INITIALIZED) {
mAudioTrack?.release()
}
val audioAttributes = AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_MEDIA)
.setFlags(AudioAttributes.FLAG_AUDIBILITY_ENFORCED)
.build()
mAudioTrack = AudioTrack(audioAttributes, mPlayerFormat, mPlayerBufferSize, AudioTrack.MODE_STREAM, AudioManager.AUDIO_SESSION_ID_GENERATE)
result.success(true)
sendPlayerStatus(SoundStreamStatus.Initialized)
}
private fun writeChunk(@NonNull call: MethodCall, @NonNull result: Result) {
val data = call.argument<ByteArray>("data")
if (data != null) {
pushPlayerChunk(data, result)
} else {
result.error(SoundStreamErrors.FailedToWriteBuffer.name, "Failed to write Player buffer", "'data' is null")
}
}
private fun pushPlayerChunk(chunk: ByteArray, result: Result) {
try {
val buffer = ByteBuffer.wrap(chunk)
val shortBuffer = ShortBuffer.allocate(chunk.size / 2)
shortBuffer.put(buffer.order(ByteOrder.LITTLE_ENDIAN).asShortBuffer())
val shortChunk = shortBuffer.array()
mAudioTrack?.write(shortChunk, 0, shortChunk.size)
result.success(true)
} catch (e: Exception) {
result.error(SoundStreamErrors.FailedToWriteBuffer.name, "Failed to write Player buffer", e.localizedMessage)
}
}
private fun startPlayer(result: Result) {
try {
if (mAudioTrack?.state == AudioTrack.PLAYSTATE_PLAYING) {
result.success(true)
return
}
mAudioTrack!!.play()
sendPlayerStatus(SoundStreamStatus.Playing)
result.success(true)
} catch (e: Exception) {
result.error(SoundStreamErrors.FailedToPlay.name, "Failed to start Player", e.localizedMessage)
}
}
private fun stopPlayer(result: Result) {
try {
if (mAudioTrack?.state == AudioTrack.STATE_INITIALIZED) {
mAudioTrack?.stop()
}
sendPlayerStatus(SoundStreamStatus.Stopped)
result.success(true)
} catch (e: Exception) {
result.error(SoundStreamErrors.FailedToStop.name, "Failed to stop Player", e.localizedMessage)
}
}
private fun sendPlayerStatus(status: SoundStreamStatus) {
sendEventMethod("playerStatus", status.name)
}
private fun createRecordListener(): OnRecordPositionUpdateListener? {
return object : OnRecordPositionUpdateListener {
override fun onMarkerReached(recorder: AudioRecord) {
recorder.read(audioData!!, 0, mRecorderBufferSize)
}
override fun onPeriodicNotification(recorder: AudioRecord) {
val data = audioData!!
val shortOut = recorder.read(data, 0, mPeriodFrames)
// https://flutter.io/platform-channels/#codec
// convert short to int because of platform-channel's limitation
val byteBuffer = ByteBuffer.allocate(shortOut * 2)
byteBuffer.order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(data)
sendEventMethod("dataPeriod", byteBuffer.array())
}
}
}
}