Skip to content

Instantly share code, notes, and snippets.

@niusounds
Last active March 31, 2024 17:22
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save niusounds/3e49013a8e942cdba3fbfe1c336b61fc to your computer and use it in GitHub Desktop.
Save niusounds/3e49013a8e942cdba3fbfe1c336b61fc 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()
}
}
@Aleksandr-Melekhin
Copy link

Thanks a lot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment