-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
WIP: Add playing demo at Android app
- Loading branch information
Showing
2 changed files
with
137 additions
and
0 deletions.
There are no files selected for viewing
58 changes: 58 additions & 0 deletions
58
juicy-noise-android/app/src/main/java/com/danand/juicynoise/AudioOutput.kt
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
package com.danand.juicynoise | ||
|
||
import android.media.AudioAttributes | ||
import android.media.AudioFormat | ||
import android.media.AudioTrack | ||
|
||
import kotlin.random.Random | ||
|
||
import kotlinx.coroutines.CoroutineScope | ||
import kotlinx.coroutines.Dispatchers | ||
import kotlinx.coroutines.SupervisorJob | ||
import kotlinx.coroutines.cancel | ||
import kotlinx.coroutines.isActive | ||
import kotlinx.coroutines.launch | ||
|
||
class AudioOutput { | ||
private lateinit var scope: CoroutineScope | ||
|
||
fun play( | ||
samplingRate: Int, | ||
bufferSize: Int, | ||
) { | ||
scope = CoroutineScope(Dispatchers.IO + SupervisorJob()) | ||
|
||
scope.launch(Dispatchers.IO) { | ||
val audioTrack = AudioTrack.Builder() | ||
.setAudioAttributes( | ||
AudioAttributes.Builder() | ||
.setUsage(AudioAttributes.USAGE_MEDIA) | ||
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC) | ||
.build() | ||
) | ||
.setAudioFormat( | ||
AudioFormat.Builder() | ||
.setEncoding(AudioFormat.ENCODING_PCM_FLOAT) | ||
.setSampleRate(samplingRate) | ||
.setChannelMask(AudioFormat.CHANNEL_OUT_STEREO) | ||
.build() | ||
) | ||
.setTransferMode(AudioTrack.MODE_STREAM) | ||
.setBufferSizeInBytes(bufferSize) | ||
.build() | ||
|
||
audioTrack.play() | ||
|
||
while (isActive) { | ||
val floatArray = FloatArray(bufferSize) { Random.Default.nextFloat() } | ||
audioTrack.write(floatArray, 0, bufferSize, AudioTrack.WRITE_NON_BLOCKING) | ||
} | ||
|
||
audioTrack.stop() | ||
} | ||
} | ||
|
||
fun stop() { | ||
scope.cancel() | ||
} | ||
} |
This file contains 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