This commit is contained in:
2024-08-27 17:19:52 -04:00
commit 30de189e27
69 changed files with 2054 additions and 0 deletions

1
wear/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
/build

75
wear/build.gradle.kts Normal file
View File

@@ -0,0 +1,75 @@
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.android)
alias(libs.plugins.kotlin.compose)
}
android {
namespace = "com.birdsounds.identify"
compileSdk = 34
defaultConfig {
applicationId = "com.birdsounds.identify"
minSdk = 34
targetSdk = 34
versionCode = 1
versionName = "1.0"
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
buildFeatures {
compose = true
}
}
dependencies {
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.8.4")
implementation("androidx.compose.ui:ui-tooling:1.3.1")
implementation("androidx.navigation:navigation-compose:2.8.0-rc01")
implementation("androidx.wear.compose:compose-navigation:1.3.1")
implementation("com.google.android.horologist:horologist-audio-ui:0.6.18")
implementation("com.google.android.horologist:horologist-audio:0.6.18")
implementation("com.google.android.horologist:horologist-compose-tools:0.6.18")
implementation("com.google.android.horologist:horologist-compose-tools:0.6.18")
implementation("com.google.android.horologist:horologist-compose-layout:0.6.18")
implementation("androidx.compose.material:material-icons-core:1.6.8")
implementation("androidx.compose.material:material-icons-extended:1.6.8")
implementation("com.google.android.horologist:horologist-compose-material:0.6.8")
implementation("com.google.android.horologist:horologist-media-ui:0.6.8")
implementation("com.google.android.horologist:horologist-media-data:0.6.8")
implementation("androidx.media3:media3-exoplayer:1.4.0")
implementation(libs.play.services.wearable)
implementation(platform(libs.androidx.compose.bom))
implementation(libs.androidx.ui)
implementation(libs.androidx.ui.graphics)
implementation(libs.androidx.ui.tooling.preview)
implementation(libs.androidx.compose.material)
implementation(libs.androidx.compose.foundation)
implementation(libs.androidx.wear.tooling.preview)
implementation(libs.androidx.activity.compose)
implementation(libs.androidx.core.splashscreen)
implementation(libs.androidx.compose.navigation)
implementation(libs.androidx.media3.common)
// androidTestImplementation(platform(libs.androidx.compose.bom))
// androidTestImplementation(libs.androidx.ui.test.junit4)
// debugImplementation(libs.androidx.ui.tooling)
// debugImplementation(libs.androidx.ui.test.manifest)
wearApp(project(":wear"))
}

8
wear/lint.xml Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<lint>
<!-- Ignore the IconLocation for the Tile preview images -->
<issue id="IconLocation">
<ignore path="res/drawable/tile_preview.png" />
<ignore path="res/drawable-round/tile_preview.png" />
</issue>
</lint>

21
wear/proguard-rules.pro vendored Normal file
View File

@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

View File

@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-feature android:name="android.hardware.type.watch" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@android:style/Theme.DeviceDefault">
<uses-library
android:name="com.google.android.wearable"
android:required="true" />
<!--
Set to true if your app is Standalone, that is, it does not require the handheld
app to run.
-->
<meta-data
android:name="com.google.android.wearable.standalone"
android:value="true" />
<activity
android:name=".presentation.MainActivity"
android:exported="true"
android:taskAffinity=""
android:theme="@style/MainActivityTheme.Starting">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

View File

@@ -0,0 +1,122 @@
package com.birdsounds.identify.presentation
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Mic
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import com.birdsounds.identify.R
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.wear.compose.material.Button
import androidx.wear.compose.material.CircularProgressIndicator
import androidx.wear.compose.material.Icon
import com.google.android.horologist.annotations.ExperimentalHorologistApi
/**
* The component responsible for drawing the main 3 controls, with their expanded and minimized
* states.
*
* The state for this class is driven by a [ControlDashboardUiState], which contains a
* [ControlDashboardButtonUiState] for each of the three buttons.
*/
@Composable
fun ControlDashboard(
controlDashboardUiState: ControlDashboardUiState,
onMicClicked: () -> Unit,
onPlayClicked: () -> Unit,
recordingProgress: Float,
modifier: Modifier = Modifier
) {
Box(
contentAlignment = Alignment.Center,
modifier = modifier.fillMaxSize()
) {
// Show the progress indicator only when recording
if (controlDashboardUiState.micState.expanded) {
CircularProgressIndicator(
progress = recordingProgress,
modifier = modifier.fillMaxSize()
)
}
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
ControlDashboardButton(
buttonState = controlDashboardUiState.micState,
onClick = onMicClicked,
imageVector = Icons.Filled.Mic,
contentDescription = if (controlDashboardUiState.micState.expanded) {
stringResource(id = R.string.stop_recording)
} else {
stringResource(id = R.string.record)
}
)
ControlDashboardButton(
buttonState = controlDashboardUiState.playState,
onClick = onPlayClicked,
imageVector = Icons.Filled.PlayArrow,
contentDescription = stringResource(id = R.string.play_recording)
)
}
}
}
/**
* A single control dashboard button
*/
@Composable
private fun ControlDashboardButton(
buttonState: ControlDashboardButtonUiState,
onClick: () -> Unit,
imageVector: ImageVector,
contentDescription: String,
modifier: Modifier = Modifier
) {
Button(
modifier = modifier,
enabled = buttonState.enabled && buttonState.visible,
onClick = onClick
) {
Icon(
imageVector = imageVector,
contentDescription = contentDescription
)
}
}
/**
* The state for a single [ControlDashboardButton].
*/
data class ControlDashboardButtonUiState(
val expanded: Boolean,
val enabled: Boolean,
val visible: Boolean
)
/**
* The state for a [ControlDashboard].
*/
data class ControlDashboardUiState(
val micState: ControlDashboardButtonUiState,
val playState: ControlDashboardButtonUiState
) {
init {
// Check that at most one of the buttons is expanded
require(
listOf(
micState.expanded,
playState.expanded
).count { it } <= 1
)
}
}

View File

@@ -0,0 +1,201 @@
/* While this template provides a good starting point for using Wear Compose, you can always
* take a look at https://github.com/android/wear-os-samples/tree/main/ComposeStarter to find the
* most up to date changes to the libraries and their usages.
*/
package com.birdsounds.identify.presentation
import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.ManagedActivityResultLauncher
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts.RequestPermission
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.lifecycle.viewmodel.compose.viewModel
import com.google.android.horologist.audio.ui.VolumeViewModel
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import com.google.android.horologist.compose.layout.AppScaffold
import com.google.android.horologist.compose.layout.ScreenScaffold
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.wear.compose.material.MaterialTheme
import androidx.wear.compose.material.Text
import androidx.wear.compose.material.TimeText
import androidx.wear.compose.material.dialog.Confirmation
import androidx.wear.compose.navigation.SwipeDismissableNavHost
import androidx.wear.compose.navigation.composable
import androidx.wear.compose.navigation.rememberSwipeDismissableNavController
import androidx.wear.tooling.preview.devices.WearDevices
import com.birdsounds.identify.R
import com.birdsounds.identify.presentation.theme.IdentifyTheme
import com.google.android.horologist.annotations.ExperimentalHorologistApi
import com.google.android.horologist.audio.ui.VolumeScreen
import com.google.android.horologist.compose.material.AlertContent
import kotlinx.coroutines.launch
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
installSplashScreen()
super.onCreate(savedInstanceState)
setTheme(android.R.style.Theme_DeviceDefault)
setContent {
WearApp("Android")
}
}
}
@OptIn(ExperimentalHorologistApi::class)
@Composable
fun WearApp(greetingName: String) {
IdentifyTheme {
lateinit var requestPermissionLauncher: ManagedActivityResultLauncher<String, Boolean>
val context = LocalContext.current
val activity = context.findActivity()
val scope = rememberCoroutineScope()
val volumeViewModel: VolumeViewModel = viewModel(factory = VolumeViewModel.Factory)
val navController = rememberSwipeDismissableNavController()
val mainState = remember(activity) {
MainState(
activity = activity,
requestPermission = {
requestPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
}
)
}
requestPermissionLauncher = rememberLauncherForActivityResult(RequestPermission()) {
// We ignore the direct result here, since we're going to check anyway.
scope.launch {
mainState.permissionResultReturned()
}
}
val lifecycleOwner = androidx.lifecycle.compose.LocalLifecycleOwner.current
AppScaffold {
// Notify the state holder whenever we become stopped to reset the state
DisposableEffect(mainState, scope, lifecycleOwner) {
val lifecycleObserver = object : DefaultLifecycleObserver {
override fun onStop(owner: LifecycleOwner) {
super.onStop(owner)
scope.launch { mainState.onStopped() }
}
}
lifecycleOwner.lifecycle.addObserver(lifecycleObserver)
onDispose {
lifecycleOwner.lifecycle.removeObserver(lifecycleObserver)
}
}
SwipeDismissableNavHost(navController = navController, startDestination = "speaker") {
composable("speaker") {
SpeakerRecordingScreen(
playbackState = mainState.playbackState,
isPermissionDenied = mainState.isPermissionDenied,
recordingProgress = mainState.recordingProgress,
onMicClicked = {
scope.launch {
mainState.onMicClicked()
}
},
onPlayClicked = {
navController.navigate("player")
}
)
if (mainState.showPermissionRationale) {
AlertContent(
onOk = {
requestPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
mainState.showPermissionRationale = false
},
onCancel = {
mainState.showPermissionRationale = false
},
title = stringResource(
id = R.string.rationale_for_microphone_permission
)
)
}
if (mainState.showSpeakerNotSupported) {
Confirmation(
onTimeout = { mainState.showSpeakerNotSupported = false }
) {
Text(text = stringResource(id = R.string.no_speaker_supported))
}
}
}
composable("player") {
SpeakerPlayerScreen(
volumeViewModel = volumeViewModel,
onVolumeClick = { navController.navigate("volume") }
)
}
composable("volume") {
ScreenScaffold(timeText = {}) {
VolumeScreen(volumeViewModel = volumeViewModel)
}
}
}
}
}
}
@Composable
fun Greeting(greetingName: String) {
Text(
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Center,
color = MaterialTheme.colors.primary,
text = stringResource(R.string.hello_world, greetingName)
)
}
@Preview(device = WearDevices.SMALL_ROUND, showSystemUi = true)
@Composable
fun DefaultPreview() {
WearApp("Preview Android")
}
tailrec fun Context.findActivity(): Activity =
when (this) {
is Activity -> this
is ContextWrapper -> baseContext.findActivity()
else -> throw IllegalStateException(
"findActivity should be called in the context of an Activity"
)
}

View File

@@ -0,0 +1,215 @@
package com.birdsounds.identify.presentation
import android.Manifest
import android.app.Activity
import android.content.pm.PackageManager
import android.media.AudioDeviceInfo
import android.media.AudioManager
import androidx.annotation.RequiresPermission
import androidx.compose.foundation.MutatorMutex
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.core.content.ContextCompat
import androidx.core.content.getSystemService
import java.time.Duration
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class MainState(
private val activity: Activity,
private val requestPermission: () -> Unit
) {
/**
* The [MutatorMutex] that guards the playback state of the app.
*
* Due to being a [MutatorMutex], this automatically handles cleanup of any ongoing asynchronous
* work, like playing music or recording, ensuring that only one operation is occurring at a
* time.
*
* For example, if the user is currently recording, and they hit the mic button again, the
* second [onMicClicked] will cancel the previous [onMicClicked] that was doing the recording,
* waiting for everything to be cleaned up, before running its own code.
*/
private val playbackStateMutatorMutex = MutatorMutex()
/**
* The primary playback state.
*/
var playbackState by mutableStateOf<PlaybackState>(PlaybackState.Ready)
private set
/**
* The progress of an ongoing recording.
*
* Note that this value can be read even when recording is not occurring, in which case it
* corresponds to the last known value of recording progress (or 0), where that value is useful
* for animations.
*/
var recordingProgress by mutableStateOf(0f)
private set
/**
* `true` if we know the user has denied the record audio permission.
*/
var isPermissionDenied by mutableStateOf(false)
private set
/**
* `true` if we the permission rationale should be shown.
*/
var showPermissionRationale by mutableStateOf(false)
/**
* `true` if we the speaker not supported rationale should be shown.
*/
var showSpeakerNotSupported by mutableStateOf(false)
/**
* The [SoundRecorder] for recording and playing audio captured on-device.
*/
private val soundRecorder = SoundRecorder(activity, "audiorecord.opus")
suspend fun onStopped() {
playbackStateMutatorMutex.mutate {
playbackState = PlaybackState.Ready
}
}
suspend fun onMicClicked() {
playbackStateMutatorMutex.mutate {
when (playbackState) {
is PlaybackState.Ready,
PlaybackState.PlayingVoice ->
// If we weren't recording, check our permission to start recording.
when {
ContextCompat.checkSelfPermission(
activity,
Manifest.permission.RECORD_AUDIO
) == PackageManager.PERMISSION_GRANTED -> {
// We have the permission, we can start recording now
playbackState = PlaybackState.Recording
record(
soundRecorder = soundRecorder,
setProgress = { progress ->
recordingProgress = progress
}
)
playbackState = PlaybackState.Ready
}
activity.shouldShowRequestPermissionRationale(
Manifest.permission.RECORD_AUDIO
) -> {
// If we should show the rationale prior to requesting the permission,
// send that event
showPermissionRationale = true
playbackState = PlaybackState.Ready
}
else -> {
// Request the permission
requestPermission()
playbackState = PlaybackState.Ready
}
}
// If we were already recording, transition back to ready
PlaybackState.Recording -> {
playbackState = PlaybackState.Ready
}
}
}
}
suspend fun permissionResultReturned() {
playbackStateMutatorMutex.mutate {
// Check if the user granted the permission
if (
ContextCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO) ==
PackageManager.PERMISSION_GRANTED
) {
// The user granted the permission, continue on to start recording
playbackState = PlaybackState.Recording
record(
soundRecorder = soundRecorder,
setProgress = { progress ->
recordingProgress = progress
}
)
playbackState = PlaybackState.Ready
} else {
// We have confirmation now that the user denied the permission
isPermissionDenied = true
playbackState = PlaybackState.Ready
}
}
}
}
/**
* The three playback states of the application.
*/
sealed class PlaybackState {
object Ready : PlaybackState()
object PlayingVoice : PlaybackState()
object Recording : PlaybackState()
}
/**
* Determines if the device has a way to output audio and if it is supported.
*
* This could be an on-device speaker, or a connected bluetooth device.
*/
private fun speakerIsSupported(activity: Activity): Boolean {
val hasAudioOutputFeature =
activity.packageManager.hasSystemFeature(PackageManager.FEATURE_AUDIO_OUTPUT)
val devices = activity.getSystemService<AudioManager>()!!
.getDevices(AudioManager.GET_DEVICES_OUTPUTS)
// We can only trust AudioDeviceInfo.TYPE_BUILTIN_SPEAKER if the device advertises
// FEATURE_AUDIO_OUTPUT
val hasBuiltInSpeaker = devices.any { it.type == AudioDeviceInfo.TYPE_BUILTIN_SPEAKER } &&
hasAudioOutputFeature
// Check all the Wear supported BT devices
// https://developer.android.com/training/wearables/apps/audio
val hasBluetoothSpeaker = devices.any {
it.type == AudioDeviceInfo.TYPE_BLUETOOTH_A2DP ||
it.type == AudioDeviceInfo.TYPE_BLE_BROADCAST ||
it.type == AudioDeviceInfo.TYPE_BLE_SPEAKER ||
it.type == AudioDeviceInfo.TYPE_BLE_HEADSET
}
return hasBuiltInSpeaker || hasBluetoothSpeaker
}
/**
* A helper function to record, updating the progress state while recording.
*
* This requires the [Manifest.permission.RECORD_AUDIO] permission to run.
*/
@RequiresPermission(Manifest.permission.RECORD_AUDIO)
private suspend fun record(
soundRecorder: SoundRecorder,
setProgress: (progress: Float) -> Unit,
maxRecordingDuration: Duration = Duration.ofSeconds(10),
numberTicks: Int = 10
) {
coroutineScope {
// Kick off a parallel job to record
val recordingJob = launch { soundRecorder.record() }
val delayPerTickMs = maxRecordingDuration.toMillis() / numberTicks
val startTime = System.currentTimeMillis()
repeat(numberTicks) { index ->
setProgress(index.toFloat() / numberTicks)
delay(startTime + delayPerTickMs * (index + 1) - System.currentTimeMillis())
}
// Update the progress to be complete
setProgress(1f)
// Stop recording
recordingJob.cancel()
}
}

View File

@@ -0,0 +1,69 @@
package com.birdsounds.identify.presentation
import android.Manifest
import android.content.Context
import android.media.MediaRecorder
import android.util.Log
import androidx.annotation.RequiresPermission
import java.io.File
import kotlinx.coroutines.suspendCancellableCoroutine
/**
* A helper class to provide methods to record audio input from the MIC to the internal storage.
*/
class SoundRecorder(
context: Context,
outputFileName: String
) {
private val audioFile = File(context.filesDir, outputFileName)
private var state = State.IDLE
private enum class State {
IDLE, RECORDING
}
/**
* Records from the microphone.
*
* This method is cancellable, and cancelling it will stop recording.
*/
@RequiresPermission(Manifest.permission.RECORD_AUDIO)
suspend fun record() {
if (state != State.IDLE) {
Log.w(TAG, "Requesting to start recording while state was not IDLE")
return
}
suspendCancellableCoroutine<Unit> { cont ->
@Suppress("DEPRECATION")
val mediaRecorder = MediaRecorder().apply {
setAudioSource(MediaRecorder.AudioSource.MIC)
setOutputFormat(MediaRecorder.OutputFormat.OGG)
setAudioEncoder(MediaRecorder.AudioEncoder.OPUS)
setOutputFile(audioFile.path)
setOnInfoListener { mr, what, extra ->
println("info: $mr $what $extra")
}
setOnErrorListener { mr, what, extra ->
println("error: $mr $what $extra")
}
}
cont.invokeOnCancellation {
mediaRecorder.stop()
state = State.IDLE
}
mediaRecorder.prepare()
mediaRecorder.start()
state = State.RECORDING
}
}
companion object {
private const val TAG = "SoundRecorder"
}
}

View File

@@ -0,0 +1,69 @@
package com.birdsounds.identify.presentation
import androidx.activity.compose.ReportDrawnAfter
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.media3.common.util.UnstableApi
import com.google.android.horologist.annotations.ExperimentalHorologistApi
import com.google.android.horologist.audio.ui.VolumeViewModel
import com.google.android.horologist.audio.ui.components.actions.SetVolumeButton
import com.google.android.horologist.media.ui.components.PodcastControlButtons
import com.google.android.horologist.media.ui.screens.player.DefaultMediaInfoDisplay
import com.google.android.horologist.media.ui.screens.player.PlayerScreen
import com.google.android.horologist.media.ui.state.PlayerUiController
import com.google.android.horologist.media.ui.state.PlayerUiState
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
@androidx.annotation.OptIn(UnstableApi::class)
@OptIn(ExperimentalHorologistApi::class)
@Composable
fun SpeakerPlayerScreen(
onVolumeClick: () -> Unit,
volumeViewModel: VolumeViewModel = viewModel(factory = VolumeViewModel.Factory),
playerViewModel: SpeakerPlayerViewModel = viewModel(factory = SpeakerPlayerViewModel.Factory),
modifier: Modifier = Modifier
) {
val volumeUiState by volumeViewModel.volumeUiState.collectAsStateWithLifecycle()
PlayerScreen(
modifier = modifier,
background = {},
playerViewModel = playerViewModel,
volumeViewModel = volumeViewModel,
mediaDisplay = { playerUiState ->
DefaultMediaInfoDisplay(playerUiState)
},
buttons = { state ->
SetVolumeButton(
volumeUiState = volumeUiState,
onVolumeClick = onVolumeClick,
enabled = state.connected && state.media != null
)
},
controlButtons = { playerUiController, playerUiState ->
PlayerScreenPodcastControlButtons(playerUiController, playerUiState)
}
)
ReportDrawnAfter {
playerViewModel.playerState.filterNotNull().first()
}
}
@OptIn(ExperimentalHorologistApi::class)
@Composable
fun PlayerScreenPodcastControlButtons(
playerUiController: PlayerUiController,
playerUiState: PlayerUiState,
modifier: Modifier = Modifier
) {
PodcastControlButtons(
modifier = modifier,
playerController = playerUiController,
playerUiState = playerUiState
)
}

View File

@@ -0,0 +1,72 @@
package com.birdsounds.identify.presentation
import androidx.compose.runtime.getValue
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import androidx.media3.common.Player
import androidx.media3.common.util.UnstableApi
import androidx.media3.exoplayer.ExoPlayer
import com.google.android.horologist.annotations.ExperimentalHorologistApi
import com.google.android.horologist.media.data.repository.PlayerRepositoryImpl
import com.google.android.horologist.media.model.Media
import com.google.android.horologist.media.ui.state.PlayerViewModel
import java.io.File
import kotlinx.coroutines.launch
@UnstableApi
@OptIn(ExperimentalHorologistApi::class)
class SpeakerPlayerViewModel(
playerRepository: PlayerRepositoryImpl,
player: Player,
audioFile: File,
audioFileUri: String
) : PlayerViewModel(playerRepository) {
init {
viewModelScope.launch {
playerRepository.connect(player) {}
if (audioFile.exists()) {
val media = Media(
id = "",
uri = audioFileUri,
title = "Recorded audio",
artist = ""
)
playerRepository.setMedia(media)
}
}
}
val playerState = playerRepository.player
@ExperimentalHorologistApi
public companion object {
private const val TAG = "SpeakerPlayerViewModel"
public val Factory: ViewModelProvider.Factory = viewModelFactory {
initializer {
val application = this[APPLICATION_KEY]!!
val outputFileName = "audiorecord.opus"
val audioFile = File(application.filesDir, outputFileName)
val audioFileUri = application.filesDir.path + "/" + outputFileName
val player = ExoPlayer.Builder(application)
.setSeekForwardIncrementMs(5000L)
.setSeekBackIncrementMs(5000L)
.build()
SpeakerPlayerViewModel(
PlayerRepositoryImpl(),
player,
audioFile,
audioFileUri
)
}
}
}
}

View File

@@ -0,0 +1,104 @@
package com.birdsounds.identify.presentation
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.PreviewParameter
import androidx.compose.ui.tooling.preview.datasource.CollectionPreviewParameterProvider
import androidx.wear.compose.ui.tooling.preview.WearPreviewDevices
import androidx.wear.compose.ui.tooling.preview.WearPreviewFontScales
import com.google.android.horologist.compose.layout.ScreenScaffold
/**
* The composable responsible for displaying the main UI.
*
* This composable is stateless, and simply displays the state given to it.
*/
@Composable
fun SpeakerRecordingScreen(
playbackState: PlaybackState,
isPermissionDenied: Boolean,
recordingProgress: Float,
onMicClicked: () -> Unit,
onPlayClicked: () -> Unit
) {
ScreenScaffold {
// Determine the control dashboard state.
// This converts the main app state into a control dashboard state for rendering
val controlDashboardUiState = computeControlDashboardUiState(
playbackState = playbackState,
isPermissionDenied = isPermissionDenied
)
ControlDashboard(
controlDashboardUiState = controlDashboardUiState,
onMicClicked = onMicClicked,
onPlayClicked = onPlayClicked,
recordingProgress = recordingProgress
)
}
}
private fun computeControlDashboardUiState(
playbackState: PlaybackState,
isPermissionDenied: Boolean
): ControlDashboardUiState =
when (playbackState) {
PlaybackState.PlayingVoice -> ControlDashboardUiState(
micState = ControlDashboardButtonUiState(
expanded = false,
enabled = false,
visible = false
),
playState = ControlDashboardButtonUiState(
expanded = true,
enabled = true,
visible = true
)
)
PlaybackState.Ready -> ControlDashboardUiState(
micState = ControlDashboardButtonUiState(
expanded = false,
enabled = !isPermissionDenied,
visible = true
),
playState = ControlDashboardButtonUiState(
expanded = false,
enabled = true,
visible = true
)
)
PlaybackState.Recording -> ControlDashboardUiState(
micState = ControlDashboardButtonUiState(
expanded = true,
enabled = true,
visible = true
),
playState = ControlDashboardButtonUiState(
expanded = false,
enabled = false,
visible = false
)
)
}
private class PlaybackStatePreviewProvider : CollectionPreviewParameterProvider<PlaybackState>(
listOf(
PlaybackState.Ready,
PlaybackState.Recording,
PlaybackState.PlayingVoice
)
)
@WearPreviewDevices
@WearPreviewFontScales
@Composable
fun SpeakerScreenPreview(
@PreviewParameter(PlaybackStatePreviewProvider::class) playbackState: PlaybackState
) {
SpeakerRecordingScreen(
playbackState = playbackState,
isPermissionDenied = true,
recordingProgress = 0.25f,
onMicClicked = {},
onPlayClicked = {}
)
}

View File

@@ -0,0 +1,17 @@
package com.birdsounds.identify.presentation.theme
import androidx.compose.runtime.Composable
import androidx.wear.compose.material.MaterialTheme
@Composable
fun IdentifyTheme(
content: @Composable () -> Unit
) {
/**
* Empty theme to customize for your app.
* See: https://developer.android.com/jetpack/compose/designsystems/custom
*/
MaterialTheme(
content = content
)
}

View File

@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:width="48dp"
android:height="48dp"
android:gravity="center">
<shape android:shape="oval">
<solid android:color="#FFFFFF" />
</shape>
</item>
<item
android:width="40dp"
android:height="40dp"
android:gravity="center">
<vector
android:width="24dp"
android:height="24dp"
android:tint="#000000"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FF000000"
android:pathData="M17.6,11.48 L19.44,8.3a0.63,0.63 0,0 0,-1.09 -0.63l-1.88,3.24a11.43,11.43 0,0 0,-8.94 0L5.65,7.67a0.63,0.63 0,0 0,-1.09 0.63L6.4,11.48A10.81,10.81 0,0 0,1 20L23,20A10.81,10.81 0,0 0,17.6 11.48ZM7,17.25A1.25,1.25 0,1 1,8.25 16,1.25 1.25,0 0,1 7,17.25ZM17,17.25A1.25,1.25 0,1 1,18.25 16,1.25 1.25,0 0,1 17,17.25Z" />
</vector>
</item>
</layer-list>

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 982 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

@@ -0,0 +1,3 @@
<resources>
<string name="hello_world">From the Round world,\nHello, %1$s!</string>
</resources>

View File

@@ -0,0 +1,18 @@
<resources>
<string name="app_name">identify</string>
<!--
This string is used for square devices and overridden by hello_world in
values-round/strings.xml for round devices.
-->
<string name="rationale_for_microphone_permission">Recording requires permission to access the microphone</string>
<string name="ok">OK</string>
<string name="cancel">Cancel</string>
<string name="no_speaker_supported">No speaker available</string>
<string name="record">Record</string>
<string name="play_recording">Play Recording</string>
<string name="play_music">Play Music</string>
<string name="stop_recording">Stop Recording</string>
<string name="stop_playing_recording">Stop Playing Recording</string>
<string name="stop_playing_music">Stop Playing Music</string>
<string name="hello_world">From the Square world,\nHello, %1$s!</string>
</resources>

View File

@@ -0,0 +1,8 @@
<resources>
<style name="MainActivityTheme.Starting" parent="Theme.SplashScreen">
<item name="windowSplashScreenBackground">@android:color/black</item>
<item name="windowSplashScreenAnimatedIcon">@drawable/splash_icon</item>
<item name="postSplashScreenTheme">@android:style/Theme.DeviceDefault</item>
</style>
</resources>