suspend fun play()

in WearSpeakerSample/wear/src/main/java/com/example/android/wearable/speaker/SoundRecorder.kt [53:102]


    suspend fun play() {
        if (state != State.IDLE) {
            Log.w(TAG, "Requesting to play while state was not IDLE")
            return
        }

        // Check if there isn't a recording to play
        if (!File(context.filesDir, outputFileName).exists()) return

        state = State.PLAYING

        val intSize = AudioTrack.getMinBufferSize(RECORDING_RATE, CHANNELS_OUT, FORMAT)

        val audioTrack = AudioTrack.Builder()
            .setAudioAttributes(
                AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
                    .setUsage(AudioAttributes.USAGE_MEDIA)
                    .build()
            )
            .setBufferSizeInBytes(intSize)
            .setAudioFormat(
                AudioFormat.Builder()
                    .setSampleRate(RECORDING_RATE)
                    .setChannelMask(CHANNELS_OUT)
                    .setEncoding(FORMAT)
                    .build()
            )
            .setTransferMode(AudioTrack.MODE_STREAM)
            .build()

        audioTrack.setVolume(AudioTrack.getMaxVolume())
        audioTrack.play()

        try {
            withContext(Dispatchers.IO) {
                context.openFileInput(outputFileName).buffered().use { bufferedInputStream ->
                    val buffer = ByteArray(intSize * 2)
                    while (isActive) {
                        val read = bufferedInputStream.read(buffer, 0, buffer.size)
                        if (read < 0) break
                        audioTrack.write(buffer, 0, read)
                    }
                }
            }
        } finally {
            audioTrack.release()
            state = State.IDLE
        }
    }