Skip to content

Instantly share code, notes, and snippets.

@whileloop99
Forked from niusounds/AudioInputStream.kt
Created December 20, 2020 02:29
Show Gist options
  • Save whileloop99/fe44033bc192f5eda6600f7b1cda5194 to your computer and use it in GitHub Desktop.
Save whileloop99/fe44033bc192f5eda6600f7b1cda5194 to your computer and use it in GitHub Desktop.
AudioInputStream and AudioOutputStream for Android. These wrap AudioRecord and AudioTrack.
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder
import java.io.IOException
import java.io.InputStream
class AudioInputStream(
audioSource: Int = MediaRecorder.AudioSource.DEFAULT,
sampleRate: Int = 44100,
channelConfig: Int = AudioFormat.CHANNEL_IN_MONO,
audioFormat: Int = AudioFormat.ENCODING_PCM_8BIT,
bufferSizeInBytes: Int = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat)) : InputStream() {
private val audioRecord = AudioRecord(audioSource, sampleRate, channelConfig, audioFormat, bufferSizeInBytes).apply {
startRecording()
}
@Deprecated("Use read(audioData, offset, length)")
@Throws(IOException::class)
override fun read(): Int {
val tmp = byteArrayOf(0)
read(tmp, 0, 1)
return tmp[0].toInt()
}
@Throws(IOException::class)
override fun read(audioData: ByteArray, offset: Int, length: Int): Int {
try {
return audioRecord.read(audioData, offset, length)
} catch (e: Exception) {
throw IOException(e)
}
}
override fun close() {
audioRecord.stop()
audioRecord.release()
super.close()
}
}
import android.media.AudioFormat
import android.media.AudioManager
import android.media.AudioTrack
import java.io.IOException
import java.io.OutputStream
class AudioOutputStream(
streamType: Int = AudioManager.STREAM_MUSIC,
sampleRate: Int = 44100,
channelConfig: Int = AudioFormat.CHANNEL_OUT_MONO,
audioFormat: Int = AudioFormat.ENCODING_PCM_8BIT,
bufferSizeInBytes: Int = AudioTrack.getMinBufferSize(sampleRate, channelConfig, audioFormat)) : OutputStream() {
private val audioTrack = AudioTrack(streamType, sampleRate, channelConfig, audioFormat, bufferSizeInBytes, AudioTrack.MODE_STREAM).apply {
play()
}
@Deprecated("Use write(audioData, offset, length)")
@Throws(IOException::class)
override fun write(b: Int) {
val tmp = byteArrayOf(0)
tmp[0] = b.toByte()
write(tmp, 0, 1)
}
@Throws(IOException::class)
override fun write(audioData: ByteArray, offset: Int, length: Int) {
try {
audioTrack.write(audioData, offset, length)
} catch (e: Exception) {
throw IOException(e)
}
}
override fun close() {
audioTrack.stop()
audioTrack.release()
super.close()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment