Android Studio:如何在等待AudioRecord初始化时暂停?

时间:2018-02-13 06:39:33

标签: java android initialization audiorecord

我有一个简单的录音应用程序,可以在录制时显示秒表。当我点击“开始录制”按钮时它开始,当我点击“停止录制”按钮时停止。但是,秒表上显示的时间与记录的时间量不同。这似乎是由于AudioRecord类的初始化时间。我想知道是否有人知道在课程初始化时延迟录音的方法。感谢。

1 个答案:

答案 0 :(得分:0)

在开始录制audioRecord.startRecording()之前先尝试一下:

 while (audioRecord.state != AudioRecord.STATE_INITIALIZED);

看这个例子:

class RxRecorder(sampleRate: Int, audioFormat: Int, private val bufferSize: Int) {
    var audioRecord: AudioRecord = AudioRecord(MediaRecorder.AudioSource.DEFAULT,
        sampleRate,
        AudioFormat.CHANNEL_IN_MONO,
        audioFormat,
        bufferSize)

    fun record() = Flowable.create<ShortArray>({ s ->
        android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_AUDIO)
        val audioBuffer = ShortArray(bufferSize / 2)

        while (audioRecord.state != AudioRecord.STATE_INITIALIZED);

        audioRecord.startRecording()

        Timber.d("Start recording")
        while (!s.isCancelled) {
            val numberOfShort = audioRecord.read(audioBuffer, 0, audioBuffer.size)

            if (numberOfShort > 0)
                s.onNext(audioBuffer.subArray(startIndex = 0, count = numberOfShort))
        }

        audioRecord.stop()
        audioRecord.release()
        s.onComplete()

    }, BackpressureStrategy.BUFFER)!!
}