commit
dc48c72135
57 files changed
+8006
No files matched your search
@@ -0,0 +1,365 @@
|
||||
package com.oshicue.tempo.audio
|
||||
|
||||
import android.content.Context
|
||||
import android.media.AudioAttributes
|
||||
import android.media.AudioManager
|
||||
import android.media.MediaPlayer
|
||||
import android.media.RingtoneManager
|
||||
import android.net.Uri
|
||||
import com.oshicue.tempo.core.L10n
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
import java.io.File
|
||||
import java.util.UUID
|
||||
|
||||
/** One selectable end-of-round sound. */
|
||||
data class TempoSound(
|
||||
val id: String,
|
||||
val name: String,
|
||||
val subtitle: String,
|
||||
)
|
||||
|
||||
/** A sound the user imported from device storage. */
|
||||
@Serializable
|
||||
private data class ImportedRecord(
|
||||
val id: String,
|
||||
val name: String,
|
||||
val fileName: String,
|
||||
val duration: Double,
|
||||
)
|
||||
|
||||
/**
|
||||
* Foreground cues use a short-lived [MediaPlayer]; background cues belong to the
|
||||
* notification channel. Imported recordings are converted to 16-bit PCM WAV so the
|
||||
* system can read them from the app's private storage.
|
||||
*/
|
||||
class TempoAudio(private val context: Context) {
|
||||
enum class ImportFailure(val messageKey: String) {
|
||||
Unsupported("audio.import.unsupported"),
|
||||
Empty("audio.import.empty"),
|
||||
TooLong("audio.import.tooLong"),
|
||||
TooLarge("audio.import.tooLarge"),
|
||||
Unreadable("audio.import.unreadable"),
|
||||
}
|
||||
|
||||
class ImportException(val failure: ImportFailure) :
|
||||
Exception(L10n.text(failure.messageKey))
|
||||
|
||||
private val _importedSounds = MutableStateFlow<List<TempoSound>>(emptyList())
|
||||
val importedSounds: StateFlow<List<TempoSound>> = _importedSounds.asStateFlow()
|
||||
|
||||
private val _errorMessage = MutableStateFlow<String?>(null)
|
||||
val errorMessage: StateFlow<String?> = _errorMessage.asStateFlow()
|
||||
|
||||
private val records = mutableListOf<ImportedRecord>()
|
||||
/** Live players, so volume can be shared when several members finish together. */
|
||||
private val players = mutableListOf<MediaPlayer>()
|
||||
private var previewPlayer: MediaPlayer? = null
|
||||
|
||||
private val soundsDirectory: File
|
||||
get() = File(context.filesDir, "Sounds").apply { mkdirs() }
|
||||
private val metadataFile: File
|
||||
get() = File(soundsDirectory, "tempo-imports.json")
|
||||
|
||||
val builtInSounds: List<TempoSound>
|
||||
get() = listOf(
|
||||
TempoSound("chime", L10n.text("audio.chime.name"), L10n.text("audio.chime.subtitle")),
|
||||
TempoSound("pulse", L10n.text("audio.pulse.name"), L10n.text("audio.pulse.subtitle")),
|
||||
TempoSound("bell", L10n.text("audio.bell.name"), L10n.text("audio.bell.subtitle")),
|
||||
TempoSound("arcade", L10n.text("audio.arcade.name"), L10n.text("audio.arcade.subtitle")),
|
||||
)
|
||||
|
||||
val sounds: List<TempoSound>
|
||||
get() = builtInSounds + _importedSounds.value
|
||||
|
||||
init {
|
||||
runCatching {
|
||||
if (metadataFile.exists()) {
|
||||
records += decodeRecords(metadataFile.readText(Charsets.UTF_8))
|
||||
records.removeAll { !File(soundsDirectory, it.fileName).exists() }
|
||||
}
|
||||
publishImported()
|
||||
}.onFailure {
|
||||
_errorMessage.value = L10n.format("audio.importedReadFailed", it.localizedMessage ?: "")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: catalogue
|
||||
|
||||
fun title(soundId: String): String =
|
||||
sounds.firstOrNull { it.id == soundId }?.name ?: L10n.text("audio.systemSound")
|
||||
|
||||
fun subtitle(soundId: String): String =
|
||||
sounds.firstOrNull { it.id == soundId }?.subtitle ?: L10n.text("groupEditor.customSound")
|
||||
|
||||
fun isImported(soundId: String): Boolean = records.any { it.id == soundId }
|
||||
|
||||
/** Removes an imported recording. Members still pointing at it fall back to the chime. */
|
||||
fun deleteImported(soundId: String) {
|
||||
val record = records.firstOrNull { it.id == soundId } ?: return
|
||||
stopPreview()
|
||||
val updated = records.filterNot { it.id == soundId }
|
||||
runCatching {
|
||||
writeRecords(updated)
|
||||
File(soundsDirectory, record.fileName).delete()
|
||||
records.clear()
|
||||
records += updated
|
||||
publishImported()
|
||||
}.onFailure {
|
||||
_errorMessage.value = L10n.format("audio.deleteFailed", it.localizedMessage ?: "")
|
||||
}
|
||||
}
|
||||
|
||||
/** Path the system notification channel can play, or null for an unknown id. */
|
||||
fun soundUri(soundId: String): Uri? {
|
||||
records.firstOrNull { it.id == soundId }?.let {
|
||||
val file = File(soundsDirectory, it.fileName)
|
||||
return if (file.exists()) Uri.fromFile(file) else null
|
||||
}
|
||||
if (builtInSounds.none { it.id == soundId }) return null
|
||||
val resources = context.resources
|
||||
val identifier = resources.getIdentifier(soundId, "raw", context.packageName)
|
||||
if (identifier == 0) return null
|
||||
return Uri.parse("android.resource://${context.packageName}/$identifier")
|
||||
}
|
||||
|
||||
/** Sound URI used by a notification channel, falling back to the built-in chime. */
|
||||
fun notificationSoundUri(soundId: String): Uri? =
|
||||
soundUri(soundId) ?: soundUri(TempoSounds.FALLBACK)
|
||||
|
||||
// MARK: playback
|
||||
|
||||
/**
|
||||
* Plays a completion cue. Several rounds can end together, so each player is kept
|
||||
* alive and the group's gain is shared; that bounds the combined peak.
|
||||
*/
|
||||
fun play(soundId: String) {
|
||||
stopPreview()
|
||||
val uri = soundUri(soundId) ?: soundUri(TempoSounds.FALLBACK)
|
||||
if (uri == null) {
|
||||
_errorMessage.value = L10n.text("audio.fileNotFound")
|
||||
return
|
||||
}
|
||||
runCatching {
|
||||
val player = createPlayer(uri)
|
||||
players += player
|
||||
player.setOnCompletionListener { finish(player) }
|
||||
player.setOnErrorListener { _, _, _ ->
|
||||
finish(player, error = true)
|
||||
true
|
||||
}
|
||||
normalizeVolumes()
|
||||
player.start()
|
||||
}.onFailure {
|
||||
_errorMessage.value = L10n.format("audio.playbackError", it.localizedMessage ?: "")
|
||||
}
|
||||
}
|
||||
|
||||
fun preview(soundId: String) {
|
||||
stopPreview()
|
||||
// Timer completions take priority over a settings preview.
|
||||
if (players.isNotEmpty()) return
|
||||
val uri = soundUri(soundId) ?: return
|
||||
runCatching {
|
||||
val player = createPlayer(uri)
|
||||
previewPlayer = player
|
||||
player.setOnCompletionListener { finishPreview(player) }
|
||||
player.setOnErrorListener { _, _, _ ->
|
||||
finishPreview(player, error = true)
|
||||
true
|
||||
}
|
||||
player.start()
|
||||
}.onFailure {
|
||||
stopPreview()
|
||||
_errorMessage.value = L10n.format("audio.previewError", it.localizedMessage ?: "")
|
||||
}
|
||||
}
|
||||
|
||||
fun stopPreview() {
|
||||
previewPlayer?.let { player ->
|
||||
player.setOnCompletionListener(null)
|
||||
player.setOnErrorListener(null)
|
||||
if (player.isPlaying) player.stop()
|
||||
player.release()
|
||||
}
|
||||
previewPlayer = null
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
stopPreview()
|
||||
players.toList().forEach { player ->
|
||||
player.setOnCompletionListener(null)
|
||||
player.setOnErrorListener(null)
|
||||
if (player.isPlaying) player.stop()
|
||||
player.release()
|
||||
}
|
||||
players.clear()
|
||||
}
|
||||
|
||||
fun clearError() {
|
||||
_errorMessage.value = null
|
||||
}
|
||||
|
||||
fun reportError(message: String) {
|
||||
_errorMessage.value = message
|
||||
}
|
||||
|
||||
// MARK: import
|
||||
|
||||
/**
|
||||
* Imports an audio file chosen from the system picker. The caller supplies the bytes
|
||||
* through [open], so no storage permission is needed. The file is stored verbatim:
|
||||
* Android's media stack and notification channels handle m4a, mp3, ogg, flac and wav
|
||||
* natively, so re-encoding would only lose quality.
|
||||
*/
|
||||
@Throws(ImportException::class)
|
||||
fun import(displayName: String, open: () -> ByteArray?): String {
|
||||
val extension = displayName.substringAfterLast('.', "").lowercase()
|
||||
if (extension !in TempoSounds.SUPPORTED_EXTENSIONS) throw ImportException(ImportFailure.Unsupported)
|
||||
val bytes = open() ?: throw ImportException(ImportFailure.Unreadable)
|
||||
if (bytes.isEmpty()) throw ImportException(ImportFailure.Empty)
|
||||
if (bytes.size > TempoSounds.MAXIMUM_BYTES) throw ImportException(ImportFailure.TooLarge)
|
||||
val duration = TempoSounds.probeDuration(context, bytes, extension)
|
||||
?: throw ImportException(ImportFailure.Unreadable)
|
||||
if (duration <= 0) throw ImportException(ImportFailure.Empty)
|
||||
if (duration >= TempoSounds.MAXIMUM_SECONDS) throw ImportException(ImportFailure.TooLong)
|
||||
|
||||
val id = "import-${UUID.randomUUID().toString().lowercase()}"
|
||||
val fileName = "$id.$extension"
|
||||
val destination = File(soundsDirectory, fileName)
|
||||
return try {
|
||||
destination.writeBytes(bytes)
|
||||
val record = ImportedRecord(
|
||||
id = id,
|
||||
name = displayName.substringBeforeLast('.').ifBlank { L10n.text("audio.systemSound") },
|
||||
fileName = fileName,
|
||||
duration = duration,
|
||||
)
|
||||
val updated = records + record
|
||||
writeRecords(updated)
|
||||
records.clear()
|
||||
records += updated
|
||||
publishImported()
|
||||
id
|
||||
} catch (error: Exception) {
|
||||
destination.delete()
|
||||
throw ImportException(ImportFailure.Unreadable)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: plumbing
|
||||
|
||||
private fun createPlayer(uri: Uri): MediaPlayer = MediaPlayer().apply {
|
||||
setAudioAttributes(
|
||||
AudioAttributes.Builder()
|
||||
.setUsage(AudioAttributes.USAGE_MEDIA)
|
||||
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
|
||||
.build(),
|
||||
)
|
||||
setDataSource(context, uri)
|
||||
prepare()
|
||||
}
|
||||
|
||||
private fun finish(player: MediaPlayer, error: Boolean = false) {
|
||||
player.setOnCompletionListener(null)
|
||||
player.setOnErrorListener(null)
|
||||
if (player.isPlaying) runCatching { player.stop() }
|
||||
player.release()
|
||||
players.remove(player)
|
||||
if (error) _errorMessage.value = L10n.text("audio.playbackInterrupted")
|
||||
normalizeVolumes()
|
||||
}
|
||||
|
||||
private fun finishPreview(player: MediaPlayer, error: Boolean = false) {
|
||||
if (previewPlayer !== player) return
|
||||
previewPlayer?.release()
|
||||
previewPlayer = null
|
||||
if (error) _errorMessage.value = L10n.text("audio.previewInterrupted")
|
||||
}
|
||||
|
||||
/** Linear gain sharing bounds the combined peak, even for identical recordings. */
|
||||
private fun normalizeVolumes() {
|
||||
if (players.isEmpty()) return
|
||||
val gain = 1f / players.size
|
||||
players.forEach { player -> runCatching { player.setVolume(gain, gain) } }
|
||||
}
|
||||
|
||||
private fun publishImported() {
|
||||
_importedSounds.value = records.map {
|
||||
TempoSound(it.id, it.name, L10n.format("audio.importedSubtitle", it.duration))
|
||||
}
|
||||
}
|
||||
|
||||
/** Re-resolves the imported subtitles in the current language. */
|
||||
fun relocalizeImported() {
|
||||
publishImported()
|
||||
}
|
||||
|
||||
private fun writeRecords(values: List<ImportedRecord>) {
|
||||
val text = TempoRecordsCodec.encode(values)
|
||||
val temporary = File(soundsDirectory, "${metadataFile.name}.tmp")
|
||||
temporary.writeText(text, Charsets.UTF_8)
|
||||
if (!temporary.renameTo(metadataFile)) {
|
||||
metadataFile.writeText(text, Charsets.UTF_8)
|
||||
temporary.delete()
|
||||
}
|
||||
}
|
||||
|
||||
private fun decodeRecords(text: String): List<ImportedRecord> =
|
||||
runCatching { TempoRecordsCodec.decode(text) }.getOrDefault(emptyList())
|
||||
|
||||
/** The system default notification sound, used when a custom cue is unavailable. */
|
||||
fun defaultNotificationSound(): Uri =
|
||||
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
|
||||
|
||||
/** Media volume is user-controlled; expose it so the settings screen can explain state. */
|
||||
fun isSilentMode(): Boolean {
|
||||
val manager = context.getSystemService(Context.AUDIO_SERVICE) as? AudioManager ?: return false
|
||||
return manager.ringerMode != AudioManager.RINGER_MODE_NORMAL
|
||||
}
|
||||
}
|
||||
|
||||
private object TempoRecordsCodec {
|
||||
private val json = Json { ignoreUnknownKeys = true; prettyPrint = true }
|
||||
|
||||
fun encode(values: List<ImportedRecord>): String = json.encodeToString(
|
||||
kotlinx.serialization.builtins.ListSerializer(ImportedRecord.serializer()), values,
|
||||
)
|
||||
|
||||
fun decode(text: String): List<ImportedRecord> = json.decodeFromString(
|
||||
kotlinx.serialization.builtins.ListSerializer(ImportedRecord.serializer()), text,
|
||||
)
|
||||
}
|
||||
|
||||
/** Names, limits and probing shared by the import and playback paths. */
|
||||
object TempoSounds {
|
||||
const val FALLBACK = "chime"
|
||||
const val MAXIMUM_BYTES = 50_000_000L
|
||||
const val MAXIMUM_SECONDS = 30.0
|
||||
val SUPPORTED_EXTENSIONS = setOf("m4a", "wav", "aif", "aiff", "caf", "mp3", "aac", "ogg", "flac")
|
||||
|
||||
/** Duration in seconds, or null when the bytes are not decodable audio. */
|
||||
fun probeDuration(context: Context, bytes: ByteArray, extension: String): Double? {
|
||||
val staged = File.createTempFile("tempo-probe-", ".$extension", context.cacheDir)
|
||||
return try {
|
||||
staged.writeBytes(bytes)
|
||||
val retriever = android.media.MediaMetadataRetriever()
|
||||
try {
|
||||
retriever.setDataSource(staged.absolutePath)
|
||||
val millis = retriever
|
||||
.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_DURATION)
|
||||
?.toLongOrNull()
|
||||
if (millis != null && millis > 0) millis / 1000.0 else null
|
||||
} finally {
|
||||
retriever.release()
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
} finally {
|
||||
staged.delete()
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user