Created
April 8, 2020 08:49
-
-
Save SergeyBurlaka/ef832b25c5065901f9d4d47655c8035e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AudiTrackOutput(private val audioBuffer: AudioDataBuffer) : Thread() { | |
private lateinit var handler: Handler | |
fun play(from: Int) { | |
handler.removeCallbacksAndMessages(null) | |
val msg = handler.obtainMessage() | |
val bundle = Bundle() | |
bundle.putInt("FROM", from) | |
msg.data = bundle | |
handler.sendMessage(Message()) | |
} | |
private val player = AudioTrack( | |
AudioAttributes.Builder() | |
.setUsage(AudioAttributes.USAGE_MEDIA) | |
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC) | |
.build(), | |
AudioFormat.Builder() | |
.setSampleRate(SAMPLING_RATE) | |
.setEncoding(AudioFormat.ENCODING_PCM_16BIT) | |
.setChannelMask(AudioFormat.CHANNEL_OUT_MONO).build(), | |
playbackBufferSize, | |
AudioTrack.MODE_STREAM, | |
AudioManager.AUDIO_SESSION_ID_GENERATE | |
) | |
init { | |
player.play() | |
} | |
override fun run() { | |
Looper.prepare() | |
handler = Handler { msg -> | |
val bundle: Bundle = msg.data | |
val from = bundle.getInt("FROM") | |
audioBuffer.read(from).also { | |
while (it.isNotEmpty()) { | |
player.write(it.removeAt(0), 0, BUFFER_SIZE) | |
} | |
} | |
true | |
} | |
Looper.loop() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment