package android.media class AudioAttributes { class Builder { fun setUsage(x: Int) = this; fun setContentType(x: Int) = this; fun build() = AudioAttributes() } companion object { const val USAGE_MEDIA = 1; const val CONTENT_TYPE_SPEECH = 1 } } class AudioFormat { class Builder { fun setSampleRate(x: Int) = this; fun setChannelMask(x: Int) = this; fun setEncoding(x: Int) = this; fun build() = AudioFormat() } companion object { const val CHANNEL_OUT_MONO = 1; const val ENCODING_PCM_16BIT = 2 } } class AudioTrack { companion object { const val STATE_INITIALIZED = 1; const val PLAYSTATE_PLAYING = 3; const val MODE_STREAM = 1; const val WRITE_NON_BLOCKING = 1 @Volatile var latest: AudioTrack? = null @Volatile var advanceHead = true @Volatile var rejectWrites = false fun getMinBufferSize(a: Int, b: Int, c: Int) = 320 } class Builder { fun setAudioAttributes(x: AudioAttributes) = this; fun setAudioFormat(x: AudioFormat) = this fun setTransferMode(x: Int) = this; fun setBufferSizeInBytes(x: Int) = this fun build() = AudioTrack().also { latest = it } } val state = STATE_INITIALIZED @Volatile var playState = 0 val bufferSizeInFrames = 320 @Volatile var samples = 0 @Volatile var flushes = 0 @Volatile var released = false @Volatile var attempts = 0 val underrunCount get() = attempts / 4 val playbackHeadPosition get() = if (advanceHead && samples >= bufferSizeInFrames) samples else 0 fun play() { playState = PLAYSTATE_PLAYING } fun pause() { playState = 0 } fun flush() { samples = 0; flushes++ } fun release() { released = true } fun write(bytes: ByteArray, offset: Int, size: Int, mode: Int): Int { attempts++ if (rejectWrites) return -3 if (attempts % 4 == 0) return 0 // native buffer temporarily full val written = minOf(128, size) // partial nonblocking writes samples += written / 2 return written } }