Я работаю над речью в текст с функцией записи мультимедиа на android, Мой код отлично работает на android одной ОС, когда я запускаю на устройстве Oppo, RealMe или Vivo, я получаю ошибку. Пожалуйста, проверьте ниже исходный код, ошибка logcat. Я уже спросил необходимые разрешения. Похоже, политика устройства oppo останавливает запись.
- Намерение записи речи:
private fun setupSpeechRecognizer() {
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this)
mSpeechRecognizerIntent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, this.packageName)
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3)
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS, 10000)
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en_US")
// secret parameters that when added provide audio url in the result
//mSpeechRecognizerIntent.putExtra("android.speech.extra.GET_AUDIO_FORMAT", "audio/mp3")
//mSpeechRecognizerIntent.putExtra("android.speech.extra.GET_AUDIO", true)
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE, true)
mSpeechRecognizer?.setRecognitionListener(recognitionListener)
}
Распознаватель слушателя
private val recognitionListener = object : RecognitionListener {
override fun onReadyForSpeech(params: Bundle?) {}
override fun onRmsChanged(rmsdB: Float) {}
override fun onBufferReceived(buffer: ByteArray?) {
latestAudioFileOutputStream?.write(buffer)
}
override fun onPartialResults(partialResults: Bundle?) {}
override fun onEvent(eventType: Int, params: Bundle?) {
Logger.d(TAG + " onEvent : " + eventType)
}
override fun onBeginningOfSpeech() {
Logger.d(TAG + " onBeginningOfSpeech ")
}
override fun onEndOfSpeech() {
Logger.d(TAG + " onEndOfSpeech ")
}
override fun onError(error: Int) {
SpeechRecognitionUtil.getErrorMessage(error)
if (error == SpeechRecognizer.ERROR_SPEECH_TIMEOUT) {
} else {
if(isRecordingRunning) {
resetSpeechRecognizer()
mSpeechRecognizer?.startListening(mSpeechRecognizerIntent)
}
}
}
override fun onResults(results: Bundle?) {
val matches = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)
if (matches != null) {
val dateTime = DateTime()
voiceToTextListAdapter?.addData(VoiceToTextItem(0, matches.get(0), dateTime.toString(AppConstant.DDMMMYYYY_HHMMSS), dateTime.millis))
}
mSpeechRecognizer?.startListening(mSpeechRecognizerIntent)
}
}
медиа-рекордер с файлом
private fun setupMediaRecorder() {
setUpNotification()
mediaRecorder = MediaRecorder()
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_RECOGNITION)
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP)
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB)
mediaRecorder.setAudioSamplingRate(16000)
mediaRecorder.setOutputFile(latestAudioFile)
try {
mediaRecorder.prepare()
} catch (e: Exception) {
e.printStackTrace()
}
mediaRecorder.start()
}
private fun createNewAudioFile() {
val file = File(Environment.getExternalStorageDirectory(), "SpeechToText")
if (!file.exists()) {
file.mkdir()
}
latestAudioFile = File(file, "Audio_" + System.currentTimeMillis() + ".mp3")
latestAudioFile?.createNewFile()
latestAudioFileOutputStream = FileOutputStream(latestAudioFile)
}
Разрешение:
<uses-permission android:name="android.permission.CAPTURE_AUDIO_OUTPUT" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Ошибка Logcat:
31795-19037 W/MediaAnalyticsItem: Unable to record: [1:audiorecord:0:-1::0:-1:1:0:10:android.media.audiorecord.latency=20:android.media.audiorecord.samplerate=8000:android.media.audiorecord.channels=1:android.media.audiorecord.encoding=AUDIO_FORMAT_PCM_16_BIT:android.media.audiorecord.source=AUDIO_SOURCE_VOICE_RECOGNITION:android.media.audiorecord.durationMs=0:android.media.audiorecord.n=0:android.media.audiorecord.createdMs=1585372724093:android.media.audiorecord.errcode=-38:android.media.audiorecord.errfunc=start:] [forcenew=0]
31795-19037 I/MicrophoneInputStream: mic_close SR : 8000 CC : 16 SO : 6
31795-19409 E/native: google_recognizer_jni.cc:93 Exception thrown from GoogleRecognizer.read()
31795-19409 W/System.err: com.google.android.apps.gsa.shared.o.e: Error code: 458758 | Error code: 393237 | Error code: 393222 | couldn't start recording, state is:1
31795-19409 W/System.err: at com.google.android.apps.gsa.speech.e.c.k.read(SourceFile:36)
31795-19409 W/System.err: Caused by: com.google.android.apps.gsa.shared.o.e: Error code: 393237 | Error code: 393222 | couldn't start recording, state is:1
31795-19409 W/System.err: at com.google.android.apps.gsa.speech.audio.bi.read(SourceFile:63)
31795-19409 W/System.err: at java.io.InputStream.read(InputStream.java:101)
31795-19409 W/System.err: at com.google.android.apps.gsa.speech.audio.ay.b(SourceFile:15)
31795-19409 W/System.err: at com.google.android.apps.gsa.speech.audio.ax.run(SourceFile:2)
31795-19409 W/System.err: at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:458)
31795-19409 W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:266)
31795-19409 W/System.err: at com.google.android.apps.gsa.shared.util.c.b.h.run(Unknown Source:3)
31795-19409 W/System.err: at com.google.android.apps.gsa.shared.util.c.b.bl.run(SourceFile:3)
31795-19409 W/System.err: at com.google.android.apps.gsa.shared.util.c.b.bl.run(SourceFile:3)
31795-19409 W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
31795-19409 W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
31795-19409 W/System.err: at java.lang.Thread.run(Thread.java:764)
31795-19409 W/System.err: at com.google.android.apps.gsa.shared.util.c.b.k.run(SourceFile:6)
31795-19409 W/System.err: Caused by: com.google.android.apps.gsa.shared.o.e: Error code: 393222 | couldn't start recording, state is:1
31888-18908 W/MediaPlayer: Couldn't open content://0@settings/system/notification_sound_cache: java.io.FileNotFoundException: open failed: ENOENT (No such file or directory)
783-8189 W/MediaAnalyticsItem: Unable to record: [1:audiopolicy:0:-1::0:-1:1:0:6:android.media.audiopolicy.reason=none:android.media.audiopolicy.status=-38:android.media.audiopolicy.rqst.src=AUDIO_SOURCE_HOTWORD:android.media.audiopolicy.rqst.pkg=com.google.android.googlequicksearchbox:android.media.audiopolicy.rqst.session=23641:android.media.audiopolicy.rqst.device=AUDIO_DEVICE_IN_BUILTIN_MIC:] [forcenew=0]