0

我在寻找使用 Kotlin 在 Android 上保存从 TarsosDSP 生成的音频数据的 FloatArray 缓冲区时遇到问题。目标是拥有一个 1 秒的音频缓冲区,该缓冲区会不断更新新的缓冲区数据,并丢弃旧数据。我希望在请求时保存此缓冲区。

我尝试使用 TarsosDSP 库找到解决方案,但它想将连续流写入 wav 文件;我需要它限制在一秒钟内,并按需保存。这个 WavFileWriter 看起来很有希望-> https://github.com/philburk/jsyn/blob/master/src/com/jsyn/util/WaveFileWriter.java但是当我将它添加到我的android项目中时,需要javax。直到查找 javax 是什么,我才知道它在 android 中不受支持。试图找到一个可以解决这个问题的库却收效甚微。

private val SAMPLE_RATE = 16000
private val BUFFER_SIZE = 1024
private val SECONDS = 1.0
private val sampleFileName: String = "audio_sample.wav"
private var audioBuffer = FloatArray(SAMPLE_RATE * SECONDS.toInt())

private var dispatcher =
        AudioDispatcherFactory.fromDefaultMicrophone(SAMPLE_RATE, BUFFER_SIZE, 128)
init {

blankProcessor = object : AudioProcessor {
   override fun processingFinished() {}

   override fun process(audioEvent: AudioEvent): Boolean {
      var buffer = audioEvent.floatBuffer
      val insertPoint = audioBuffer.lastIndex - buffer.lastIndex
      Arrays.copyOfRange(audioBuffer, insertPoint, audioBuffer.size)
                    .copyInto(audioBuffer, 0)
      buffer.copyInto(audioBuffer, insertPoint)
      return true
    }
}

dispatcher.addAudioProcessor(blankProcessor)

audioThread = Thread(dispatcher, "Audio Thread")
}


private fun writeWavFile() {
   val file = File(context.cacheDir.absolutePath + "/" + sampleFileName)
   // missing wav write code
}
4

1 回答 1

0

TarsosDSP 提供WriterProcessor类,用于将音频写入文件:

https://github.com/JorenSix/TarsosDSP/blob/c26e5004e203ee79be1ec25c2603b1f11b69d276/src/core/be/tarsos/dsp/writer/WriterProcessor.java

这是您修改后的示例:

private var dispatcher =
        AudioDispatcherFactory.fromDefaultMicrophone(SAMPLE_RATE, BUFFER_SIZE, 128)

init {

blankProcessor = object : AudioProcessor {
   override fun processingFinished() {}

   override fun process(audioEvent: AudioEvent): Boolean {
      var buffer = audioEvent.floatBuffer
      val insertPoint = audioBuffer.lastIndex - buffer.lastIndex
      Arrays.copyOfRange(audioBuffer, insertPoint, audioBuffer.size)
                    .copyInto(audioBuffer, 0)
      buffer.copyInto(audioBuffer, insertPoint)
      return true
    }
}

dispatcher.addAudioProcessor(blankProcessor)

// The important bit

val outputFile = File(context.filesDir, "file_name")
val randomAccessFile = RandomAccessFile(outputFile, "rw")
val fileWriter = WriterProcessor(audioFormat, randomAccessFile)

dispatcher.addAudioProcessor(fileWriter)

audioThread = Thread(dispatcher, "Audio Thread")
}
于 2019-09-19T11:52:53.493 回答