expo-speech-recognition 0.0.1 → 0.0.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.eslintrc.js +12 -0
- package/.prettierignore +6 -0
- package/CHANGELOG.md +7 -0
- package/LICENSE +21 -0
- package/README.md +1092 -0
- package/android/build.gradle +43 -0
- package/android/src/main/AndroidManifest.xml +2 -0
- package/android/src/main/java/expo/modules/speechrecognition/DelayedFileStreamer.kt +232 -0
- package/android/src/main/java/expo/modules/speechrecognition/ExpoAudioRecorder.kt +217 -0
- package/android/src/main/java/expo/modules/speechrecognition/ExpoSpeechRecognitionModule.kt +447 -0
- package/android/src/main/java/expo/modules/speechrecognition/ExpoSpeechRecognitionOptions.kt +108 -0
- package/android/src/main/java/expo/modules/speechrecognition/ExpoSpeechService.kt +732 -0
- package/app.plugin.js +111 -0
- package/build/ExpoSpeechRecognitionModule.d.ts +5 -0
- package/build/ExpoSpeechRecognitionModule.d.ts.map +1 -0
- package/build/ExpoSpeechRecognitionModule.js +21 -0
- package/build/ExpoSpeechRecognitionModule.js.map +1 -0
- package/build/ExpoSpeechRecognitionModule.types.d.ts +668 -0
- package/build/ExpoSpeechRecognitionModule.types.d.ts.map +1 -0
- package/build/ExpoSpeechRecognitionModule.types.js +2 -0
- package/build/ExpoSpeechRecognitionModule.types.js.map +1 -0
- package/build/ExpoSpeechRecognitionModule.web.d.ts +12 -0
- package/build/ExpoSpeechRecognitionModule.web.d.ts.map +1 -0
- package/build/ExpoSpeechRecognitionModule.web.js +237 -0
- package/build/ExpoSpeechRecognitionModule.web.js.map +1 -0
- package/build/ExpoWebSpeechRecognition.d.ts +98 -0
- package/build/ExpoWebSpeechRecognition.d.ts.map +1 -0
- package/build/ExpoWebSpeechRecognition.js +387 -0
- package/build/ExpoWebSpeechRecognition.js.map +1 -0
- package/build/ExpoWebSpeechRecognition.web.d.ts +13 -0
- package/build/ExpoWebSpeechRecognition.web.d.ts.map +1 -0
- package/build/ExpoWebSpeechRecognition.web.js +17 -0
- package/build/ExpoWebSpeechRecognition.web.js.map +1 -0
- package/build/constants.d.ts +344 -0
- package/build/constants.d.ts.map +1 -0
- package/build/constants.js +344 -0
- package/build/constants.js.map +1 -0
- package/build/index.d.ts +39 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +22 -0
- package/build/index.js.map +1 -0
- package/build/useSpeechRecognitionEvent.d.ts +11 -0
- package/build/useSpeechRecognitionEvent.d.ts.map +1 -0
- package/build/useSpeechRecognitionEvent.js +20 -0
- package/build/useSpeechRecognitionEvent.js.map +1 -0
- package/expo-module.config.json +9 -0
- package/ios/EXSpeechRecognitionPermissionRequester.swift +42 -0
- package/ios/ExpoSpeechRecognition.podspec +27 -0
- package/ios/ExpoSpeechRecognitionException.swift +84 -0
- package/ios/ExpoSpeechRecognitionModule.swift +547 -0
- package/ios/ExpoSpeechRecognizer.swift +812 -0
- package/ios/SpeechRecognitionOptions.swift +194 -0
- package/package.json +48 -6
- package/src/ExpoSpeechRecognitionModule.ts +40 -0
- package/src/ExpoSpeechRecognitionModule.types.ts +722 -0
- package/src/ExpoSpeechRecognitionModule.web.ts +306 -0
- package/src/ExpoWebSpeechRecognition.ts +509 -0
- package/src/ExpoWebSpeechRecognition.web.ts +17 -0
- package/src/constants.ts +349 -0
- package/src/globals.d.ts +1 -0
- package/src/index.ts +90 -0
- package/src/useSpeechRecognitionEvent.ts +30 -0
- package/tsconfig.json +8 -0
- package/index.js +0 -0
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
apply plugin: 'com.android.library'
|
|
2
|
+
|
|
3
|
+
group = 'expo.modules.speechrecognition'
|
|
4
|
+
version = '0.1.0'
|
|
5
|
+
|
|
6
|
+
def expoModulesCorePlugin = new File(project(":expo-modules-core").projectDir.absolutePath, "ExpoModulesCorePlugin.gradle")
|
|
7
|
+
apply from: expoModulesCorePlugin
|
|
8
|
+
applyKotlinExpoModulesCorePlugin()
|
|
9
|
+
useCoreDependencies()
|
|
10
|
+
useExpoPublishing()
|
|
11
|
+
|
|
12
|
+
// If you want to use the managed Android SDK versions from expo-modules-core, set this to true.
|
|
13
|
+
// The Android SDK versions will be bumped from time to time in SDK releases and may introduce breaking changes in your module code.
|
|
14
|
+
// Most of the time, you may like to manage the Android SDK versions yourself.
|
|
15
|
+
def useManagedAndroidSdkVersions = false
|
|
16
|
+
if (useManagedAndroidSdkVersions) {
|
|
17
|
+
useDefaultAndroidSdkVersions()
|
|
18
|
+
} else {
|
|
19
|
+
buildscript {
|
|
20
|
+
// Simple helper that allows the root project to override versions declared by this library.
|
|
21
|
+
ext.safeExtGet = { prop, fallback ->
|
|
22
|
+
rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
project.android {
|
|
26
|
+
compileSdkVersion safeExtGet("compileSdkVersion", 34)
|
|
27
|
+
defaultConfig {
|
|
28
|
+
minSdkVersion safeExtGet("minSdkVersion", 21)
|
|
29
|
+
targetSdkVersion safeExtGet("targetSdkVersion", 34)
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
android {
|
|
35
|
+
namespace "expo.modules.speechrecognition"
|
|
36
|
+
defaultConfig {
|
|
37
|
+
versionCode 1
|
|
38
|
+
versionName "0.1.0"
|
|
39
|
+
}
|
|
40
|
+
lintOptions {
|
|
41
|
+
abortOnError false
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
package expo.modules.speechrecognition
|
|
2
|
+
|
|
3
|
+
import android.media.MediaCodec
|
|
4
|
+
import android.media.MediaExtractor
|
|
5
|
+
import android.media.MediaFormat
|
|
6
|
+
import android.os.ParcelFileDescriptor
|
|
7
|
+
import kotlinx.coroutines.CoroutineScope
|
|
8
|
+
import kotlinx.coroutines.Dispatchers
|
|
9
|
+
import kotlinx.coroutines.delay
|
|
10
|
+
import kotlinx.coroutines.launch
|
|
11
|
+
import java.io.File
|
|
12
|
+
import java.io.IOException
|
|
13
|
+
import java.io.OutputStream
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* This class is used to stream audio to the speech recognition service
|
|
17
|
+
*
|
|
18
|
+
* It adds an artifical delay between chunks of audio to simulate a real-time stream
|
|
19
|
+
*
|
|
20
|
+
* Important Note: if you're using network-based streaming,
|
|
21
|
+
* you may want to consider lengthening the delay to avoid any rate-limiting or other network issues
|
|
22
|
+
*/
|
|
23
|
+
class DelayedFileStreamer {
|
|
24
|
+
private var audioFile: File
|
|
25
|
+
private var pfd: ParcelFileDescriptor
|
|
26
|
+
private var sink: ParcelFileDescriptor.AutoCloseOutputStream
|
|
27
|
+
private var delayMillis: Long // Delay between the 4KB chunks
|
|
28
|
+
|
|
29
|
+
constructor(file: File, delayMillis: Long = 100L) {
|
|
30
|
+
audioFile = file
|
|
31
|
+
this.delayMillis = delayMillis
|
|
32
|
+
val pipe = ParcelFileDescriptor.createPipe()
|
|
33
|
+
val source = ParcelFileDescriptor.AutoCloseInputStream(pipe[0])
|
|
34
|
+
sink = ParcelFileDescriptor.AutoCloseOutputStream(pipe[1])
|
|
35
|
+
pfd = ParcelFileDescriptor.dup(source.fd)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
fun getParcel(): ParcelFileDescriptor = pfd
|
|
39
|
+
|
|
40
|
+
fun startStreaming() {
|
|
41
|
+
CoroutineScope(Dispatchers.IO).launch {
|
|
42
|
+
streamAudioContents(audioFile, sink)
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/*
|
|
47
|
+
// This works well with simple raw audio files
|
|
48
|
+
private suspend fun writeFileToStream(
|
|
49
|
+
file: File,
|
|
50
|
+
outputStream: OutputStream,
|
|
51
|
+
) {
|
|
52
|
+
val buffer = ByteArray(1024 * 4) // 4KB
|
|
53
|
+
var bytesRead: Int
|
|
54
|
+
|
|
55
|
+
FileInputStream(file).use { fis ->
|
|
56
|
+
try {
|
|
57
|
+
while (fis.read(buffer).also { bytesRead = it } > 0) {
|
|
58
|
+
delay(delayMillis)
|
|
59
|
+
outputStream.write(buffer, 0, bytesRead)
|
|
60
|
+
}
|
|
61
|
+
} catch (e: IOException) {
|
|
62
|
+
e.printStackTrace()
|
|
63
|
+
} finally {
|
|
64
|
+
try {
|
|
65
|
+
outputStream.close()
|
|
66
|
+
} catch (e: IOException) {
|
|
67
|
+
e.printStackTrace()
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
*/
|
|
73
|
+
|
|
74
|
+
private suspend fun streamAudioContents(
|
|
75
|
+
file: File,
|
|
76
|
+
outputStream: OutputStream,
|
|
77
|
+
) {
|
|
78
|
+
// val cacheFile = File(file.parentFile, "cached_audio.pcm")
|
|
79
|
+
// var cacheOutputStream: FileOutputStream? = null
|
|
80
|
+
|
|
81
|
+
try {
|
|
82
|
+
// cacheOutputStream = FileOutputStream(cacheFile)
|
|
83
|
+
val extractor = MediaExtractor()
|
|
84
|
+
extractor.setDataSource(file.absolutePath)
|
|
85
|
+
val format = extractor.getTrackFormat(0)
|
|
86
|
+
val mime = format.getString(MediaFormat.KEY_MIME) ?: return
|
|
87
|
+
if (!mime.startsWith("audio/")) throw IllegalArgumentException("Not an audio file")
|
|
88
|
+
|
|
89
|
+
extractor.selectTrack(0)
|
|
90
|
+
|
|
91
|
+
val codec = MediaCodec.createDecoderByType(mime)
|
|
92
|
+
codec.configure(format, null, null, 0)
|
|
93
|
+
codec.start()
|
|
94
|
+
val bufferInfo = MediaCodec.BufferInfo()
|
|
95
|
+
|
|
96
|
+
while (true) {
|
|
97
|
+
val inputBufferIndex = codec.dequeueInputBuffer(10000)
|
|
98
|
+
if (inputBufferIndex >= 0) {
|
|
99
|
+
val inputBuffer = codec.getInputBuffer(inputBufferIndex)
|
|
100
|
+
if (inputBuffer != null) {
|
|
101
|
+
inputBuffer.clear()
|
|
102
|
+
val sampleSize = extractor.readSampleData(inputBuffer, 0)
|
|
103
|
+
if (sampleSize < 0) {
|
|
104
|
+
codec.queueInputBuffer(
|
|
105
|
+
inputBufferIndex,
|
|
106
|
+
0,
|
|
107
|
+
0,
|
|
108
|
+
0L,
|
|
109
|
+
MediaCodec.BUFFER_FLAG_END_OF_STREAM,
|
|
110
|
+
)
|
|
111
|
+
} else {
|
|
112
|
+
codec.queueInputBuffer(
|
|
113
|
+
inputBufferIndex,
|
|
114
|
+
0,
|
|
115
|
+
sampleSize,
|
|
116
|
+
extractor.sampleTime,
|
|
117
|
+
0,
|
|
118
|
+
)
|
|
119
|
+
extractor.advance()
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
val outputBufferIndex = codec.dequeueOutputBuffer(bufferInfo, 10000)
|
|
125
|
+
if (outputBufferIndex >= 0) {
|
|
126
|
+
val outputBuffer = codec.getOutputBuffer(outputBufferIndex)
|
|
127
|
+
if (outputBuffer != null) {
|
|
128
|
+
val chunk = ByteArray(bufferInfo.size)
|
|
129
|
+
|
|
130
|
+
outputBuffer.get(chunk)
|
|
131
|
+
outputBuffer.clear()
|
|
132
|
+
if (chunk.isNotEmpty()) {
|
|
133
|
+
// Add an artificial delay between the chunks of audio
|
|
134
|
+
// As we're not playing-back the audio we're just delaying the output stream
|
|
135
|
+
// so the speech recognizer has some time to process the audio
|
|
136
|
+
// Especially important for network-based recognition (and potentially avoiding rate-limiting)
|
|
137
|
+
val delayMs = (chunk.size / 4192.0) * delayMillis
|
|
138
|
+
delay(delayMs.toLong())
|
|
139
|
+
try {
|
|
140
|
+
// Log.d(
|
|
141
|
+
// "ExpoSpeechService",
|
|
142
|
+
// "output write, size=" + chunk.size + ", delay=" + delayMs.toLong() + "ms with base delay of " +
|
|
143
|
+
// delayMillis,
|
|
144
|
+
// )
|
|
145
|
+
outputStream.write(chunk)
|
|
146
|
+
// outputStream.flush()
|
|
147
|
+
// cacheOutputStream?.write(chunk)
|
|
148
|
+
// cacheOutputStream?.flush()
|
|
149
|
+
} catch (e: IOException) {
|
|
150
|
+
e.printStackTrace()
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
codec.releaseOutputBuffer(outputBufferIndex, false)
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// If end of stream
|
|
158
|
+
if (bufferInfo.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) {
|
|
159
|
+
break
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
codec.stop()
|
|
164
|
+
codec.release()
|
|
165
|
+
extractor.release()
|
|
166
|
+
// val sampleRate = format.getInteger(MediaFormat.KEY_SAMPLE_RATE)
|
|
167
|
+
// val channelCount = format.getInteger(MediaFormat.KEY_CHANNEL_COUNT)
|
|
168
|
+
// val audioFormat =
|
|
169
|
+
// if (channelCount == 1) {
|
|
170
|
+
// AudioFormat.CHANNEL_OUT_MONO
|
|
171
|
+
// } else {
|
|
172
|
+
// AudioFormat.CHANNEL_OUT_STEREO
|
|
173
|
+
// }
|
|
174
|
+
|
|
175
|
+
// // Playback the cached file
|
|
176
|
+
// playbackCachedFile(cacheFile, sampleRate, audioFormat)
|
|
177
|
+
} catch (e: IOException) {
|
|
178
|
+
e.printStackTrace()
|
|
179
|
+
} finally {
|
|
180
|
+
outputStream.close()
|
|
181
|
+
// cacheOutputStream?.close()
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Ensure to close the descriptor when done to free resources.
|
|
187
|
+
*/
|
|
188
|
+
fun close() {
|
|
189
|
+
try {
|
|
190
|
+
pfd.close()
|
|
191
|
+
} catch (e: IOException) {
|
|
192
|
+
e.printStackTrace()
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
/*
|
|
196
|
+
private fun playbackCachedFile(
|
|
197
|
+
file: File,
|
|
198
|
+
sampleRate: Int,
|
|
199
|
+
audioFormat: Int,
|
|
200
|
+
) {
|
|
201
|
+
val bufferSize =
|
|
202
|
+
AudioTrack.getMinBufferSize(
|
|
203
|
+
sampleRate,
|
|
204
|
+
audioFormat,
|
|
205
|
+
AudioFormat.ENCODING_PCM_16BIT,
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
val audioTrack =
|
|
209
|
+
AudioTrack(
|
|
210
|
+
AudioManager.STREAM_MUSIC,
|
|
211
|
+
sampleRate,
|
|
212
|
+
audioFormat,
|
|
213
|
+
AudioFormat.ENCODING_PCM_16BIT,
|
|
214
|
+
bufferSize,
|
|
215
|
+
AudioTrack.MODE_STREAM,
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
val buffer = ByteArray(bufferSize)
|
|
219
|
+
|
|
220
|
+
Log.d("ExpoSpeechService", "file path: ${file.absolutePath}")
|
|
221
|
+
FileInputStream(file).use { fileInputStream ->
|
|
222
|
+
audioTrack.play()
|
|
223
|
+
var bytesRead: Int
|
|
224
|
+
while (fileInputStream.read(buffer).also { bytesRead = it } != -1) {
|
|
225
|
+
audioTrack.write(buffer, 0, bytesRead)
|
|
226
|
+
}
|
|
227
|
+
audioTrack.stop()
|
|
228
|
+
audioTrack.release()
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
*/
|
|
232
|
+
}
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
package expo.modules.speechrecognition
|
|
2
|
+
|
|
3
|
+
import android.annotation.SuppressLint
|
|
4
|
+
import android.content.Context
|
|
5
|
+
import android.media.AudioFormat
|
|
6
|
+
import android.media.AudioRecord
|
|
7
|
+
import android.media.MediaRecorder
|
|
8
|
+
import android.os.ParcelFileDescriptor
|
|
9
|
+
import android.os.ParcelFileDescriptor.AutoCloseOutputStream
|
|
10
|
+
import android.util.Log
|
|
11
|
+
import java.io.DataOutputStream
|
|
12
|
+
import java.io.File
|
|
13
|
+
import java.io.FileOutputStream
|
|
14
|
+
import java.io.IOException
|
|
15
|
+
import java.util.UUID
|
|
16
|
+
import kotlin.concurrent.thread
|
|
17
|
+
|
|
18
|
+
interface AudioRecorder {
|
|
19
|
+
fun start()
|
|
20
|
+
|
|
21
|
+
fun stop()
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* ExpoAudioRecorder allows us to record to a 16hz pcm stream for use in SpeechRecognition
|
|
26
|
+
*
|
|
27
|
+
* Once stopped, the recording stream is written to a wav file for external use
|
|
28
|
+
*/
|
|
29
|
+
class ExpoAudioRecorder(
|
|
30
|
+
private val context: Context,
|
|
31
|
+
// Optional output file path
|
|
32
|
+
private val outputFilePath: String?,
|
|
33
|
+
) : AudioRecorder {
|
|
34
|
+
private var audioRecorder: AudioRecord? = null
|
|
35
|
+
|
|
36
|
+
var outputFile: File? = null
|
|
37
|
+
var outputFileUri = "file://$outputFilePath"
|
|
38
|
+
|
|
39
|
+
/** The file where the mic stream is being output to */
|
|
40
|
+
private val tempPcmFile: File
|
|
41
|
+
val recordingParcel: ParcelFileDescriptor
|
|
42
|
+
private var outputStream: AutoCloseOutputStream?
|
|
43
|
+
|
|
44
|
+
init {
|
|
45
|
+
tempPcmFile = createTempPcmFile()
|
|
46
|
+
try {
|
|
47
|
+
val pipe = ParcelFileDescriptor.createPipe()
|
|
48
|
+
recordingParcel = pipe[0]
|
|
49
|
+
outputStream = AutoCloseOutputStream(pipe[1])
|
|
50
|
+
} catch (e: IOException) {
|
|
51
|
+
Log.e(TAG, "Failed to create pipe", e)
|
|
52
|
+
e.printStackTrace()
|
|
53
|
+
throw e
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
val sampleRateInHz = 16000
|
|
58
|
+
private val channelConfig = AudioFormat.CHANNEL_IN_MONO
|
|
59
|
+
val audioFormat = AudioFormat.ENCODING_PCM_16BIT
|
|
60
|
+
private val bufferSizeInBytes = AudioRecord.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat)
|
|
61
|
+
|
|
62
|
+
private var recordingThread: Thread? = null
|
|
63
|
+
private var isRecordingAudio = false
|
|
64
|
+
|
|
65
|
+
companion object {
|
|
66
|
+
private const val TAG = "ExpoAudioRecorder"
|
|
67
|
+
|
|
68
|
+
private fun shortReverseBytes(s: Short): Int =
|
|
69
|
+
java.lang.Short
|
|
70
|
+
.reverseBytes(s)
|
|
71
|
+
.toInt()
|
|
72
|
+
|
|
73
|
+
fun appendWavHeader(
|
|
74
|
+
outputFilePath: String,
|
|
75
|
+
pcmFile: File,
|
|
76
|
+
sampleRateInHz: Int,
|
|
77
|
+
): File {
|
|
78
|
+
val outputFile = File(outputFilePath)
|
|
79
|
+
val audioDataLength = pcmFile.length()
|
|
80
|
+
val numChannels = 1
|
|
81
|
+
val bitsPerSample = 16
|
|
82
|
+
|
|
83
|
+
DataOutputStream(FileOutputStream(outputFile)).use { out ->
|
|
84
|
+
val totalDataLen = 36 + audioDataLength
|
|
85
|
+
val byteRate = sampleRateInHz * numChannels * bitsPerSample / 8
|
|
86
|
+
val blockAlign = numChannels * bitsPerSample / 8
|
|
87
|
+
|
|
88
|
+
// Write the RIFF chunk descriptor
|
|
89
|
+
out.writeBytes("RIFF") // ChunkID
|
|
90
|
+
out.writeInt(Integer.reverseBytes(totalDataLen.toInt())) // ChunkSize
|
|
91
|
+
out.writeBytes("WAVE")
|
|
92
|
+
out.writeBytes("fmt ")
|
|
93
|
+
out.writeInt(Integer.reverseBytes(16)) // Subchunk1Size (16 for PCM)
|
|
94
|
+
out.writeShort(shortReverseBytes(1)) // AudioFormat (1 for PCM)
|
|
95
|
+
out.writeShort(shortReverseBytes(numChannels.toShort())) // NumChannels
|
|
96
|
+
out.writeInt(Integer.reverseBytes(sampleRateInHz)) // SampleRate
|
|
97
|
+
out.writeInt(Integer.reverseBytes(byteRate)) // ByteRate
|
|
98
|
+
out.writeShort(shortReverseBytes(blockAlign.toShort())) // BlockAlign
|
|
99
|
+
out.writeShort(shortReverseBytes(bitsPerSample.toShort())) // BitsPerSample
|
|
100
|
+
|
|
101
|
+
// Write the data sub-chunk
|
|
102
|
+
out.writeBytes("data")
|
|
103
|
+
out.writeInt(Integer.reverseBytes(audioDataLength.toInt()))
|
|
104
|
+
|
|
105
|
+
try {
|
|
106
|
+
val pcmData = pcmFile.readBytes()
|
|
107
|
+
out.write(pcmData)
|
|
108
|
+
pcmFile.delete()
|
|
109
|
+
} catch (e: IOException) {
|
|
110
|
+
Log.e(TAG, "Failed to read PCM file", e)
|
|
111
|
+
e.printStackTrace()
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return outputFile
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
private fun createTempPcmFile(): File {
|
|
120
|
+
val file = File(context.cacheDir, "temp_${UUID.randomUUID()}.pcm")
|
|
121
|
+
if (!file.exists()) {
|
|
122
|
+
try {
|
|
123
|
+
file.createNewFile()
|
|
124
|
+
} catch (e: IOException) {
|
|
125
|
+
e.printStackTrace()
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return file
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
@SuppressLint("MissingPermission")
|
|
132
|
+
private fun createRecorder(): AudioRecord =
|
|
133
|
+
AudioRecord(
|
|
134
|
+
MediaRecorder.AudioSource.DEFAULT,
|
|
135
|
+
sampleRateInHz,
|
|
136
|
+
channelConfig,
|
|
137
|
+
AudioFormat.ENCODING_PCM_16BIT,
|
|
138
|
+
bufferSizeInBytes,
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
override fun start() {
|
|
142
|
+
createRecorder().apply {
|
|
143
|
+
audioRecorder = this
|
|
144
|
+
|
|
145
|
+
// First check whether the above object actually initialized
|
|
146
|
+
if (this.state != AudioRecord.STATE_INITIALIZED) {
|
|
147
|
+
return
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
this.startRecording()
|
|
151
|
+
isRecordingAudio = true
|
|
152
|
+
|
|
153
|
+
// Start thread
|
|
154
|
+
recordingThread =
|
|
155
|
+
thread {
|
|
156
|
+
streamAudioToPipe()
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
override fun stop() {
|
|
162
|
+
isRecordingAudio = false
|
|
163
|
+
audioRecorder?.stop()
|
|
164
|
+
audioRecorder?.release()
|
|
165
|
+
audioRecorder = null
|
|
166
|
+
recordingThread = null
|
|
167
|
+
if (outputFilePath != null) {
|
|
168
|
+
try {
|
|
169
|
+
outputFile =
|
|
170
|
+
appendWavHeader(
|
|
171
|
+
outputFilePath,
|
|
172
|
+
tempPcmFile,
|
|
173
|
+
sampleRateInHz,
|
|
174
|
+
)
|
|
175
|
+
} catch (e: IOException) {
|
|
176
|
+
Log.e(TAG, "Failed to append WAV header", e)
|
|
177
|
+
e.printStackTrace()
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
// Close the ParcelFileDescriptor
|
|
181
|
+
try {
|
|
182
|
+
recordingParcel.close()
|
|
183
|
+
} catch (e: IOException) {
|
|
184
|
+
e.printStackTrace()
|
|
185
|
+
}
|
|
186
|
+
// And the output stream
|
|
187
|
+
try {
|
|
188
|
+
outputStream?.close()
|
|
189
|
+
outputStream = null
|
|
190
|
+
} catch (e: IOException) {
|
|
191
|
+
e.printStackTrace()
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
private fun streamAudioToPipe() {
|
|
196
|
+
val tempFileOutputStream = FileOutputStream(tempPcmFile)
|
|
197
|
+
val data = ByteArray(bufferSizeInBytes / 2)
|
|
198
|
+
|
|
199
|
+
while (isRecordingAudio) {
|
|
200
|
+
val read = audioRecorder!!.read(data, 0, data.size)
|
|
201
|
+
try {
|
|
202
|
+
outputStream?.write(data, 0, read)
|
|
203
|
+
outputStream?.flush()
|
|
204
|
+
|
|
205
|
+
// Write to the temp PCM file
|
|
206
|
+
if (outputFilePath != null) {
|
|
207
|
+
tempFileOutputStream.write(data, 0, read)
|
|
208
|
+
tempFileOutputStream.flush()
|
|
209
|
+
}
|
|
210
|
+
} catch (e: IOException) {
|
|
211
|
+
Log.e(TAG, "Failed to write to output stream", e)
|
|
212
|
+
e.printStackTrace()
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
tempFileOutputStream.close()
|
|
216
|
+
}
|
|
217
|
+
}
|