diff --git a/app/src/main/java/com/audio/vibe/common/text/MetadataTextRepair.kt b/app/src/main/java/com/audio/vibe/common/text/MetadataTextRepair.kt index 481e9f2..b7f164a 100644 --- a/app/src/main/java/com/audio/vibe/common/text/MetadataTextRepair.kt +++ b/app/src/main/java/com/audio/vibe/common/text/MetadataTextRepair.kt @@ -3,6 +3,7 @@ package com.audio.vibe.common.text import java.nio.charset.Charset import java.nio.charset.CodingErrorAction import java.nio.charset.StandardCharsets +import java.util.Locale import kotlin.math.max object MetadataTextRepair { @@ -20,7 +21,7 @@ object MetadataTextRepair { Charset.forName("Big5") ) - fun repair(value: String?): String? { + fun repair(value: String?, locale: Locale = Locale.getDefault()): String? { val original = value?.takeIf { it.isNotBlank() } ?: return null val trimmedOriginal = original.trim() if (looksClean(trimmedOriginal)) return trimmedOriginal @@ -51,7 +52,50 @@ object MetadataTextRepair { } } } - return candidates.maxByOrNull { score(it, original) } ?: original + return candidates.maxByOrNull { score(it, original) + languageBonus(it, locale) } ?: original + } + + fun repairBytes(bytes: ByteArray, locale: Locale = Locale.getDefault()): String? { + if (bytes.isEmpty()) return null + decodeBom(bytes)?.let { return repair(it, locale) ?: it.trim() } + bytes.decodeStrict(StandardCharsets.UTF_8) + ?.let { repair(it, locale) ?: it.trim() } + ?.takeIf { it.isNotBlank() && looksClean(it) } + ?.let { return it } + val candidates = buildList { + byteDecodeCharsets.forEachIndexed { index, charset -> + bytes.decodeStrict(charset) + ?.let { repair(it, locale) ?: it.trim() } + ?.takeIf { it.isNotBlank() } + ?.let { add(ByteDecodeCandidate(it, index)) } + } + }.distinctBy { it.value } + return candidates.maxByOrNull { scoreDecodedBytesCandidate(it, locale) }?.value?.trim() + } + + private fun decodeBom(bytes: ByteArray): String? { + return when { + bytes.size >= 3 && + bytes[0] == 0xEF.toByte() && + bytes[1] == 0xBB.toByte() && + bytes[2] == 0xBF.toByte() -> { + bytes.copyOfRange(3, bytes.size).decodeStrict(StandardCharsets.UTF_8) + } + + bytes.size >= 2 && + bytes[0] == 0xFF.toByte() && + bytes[1] == 0xFE.toByte() -> { + bytes.copyOfRange(2, bytes.size).decodeStrict(StandardCharsets.UTF_16LE) + } + + bytes.size >= 2 && + bytes[0] == 0xFE.toByte() && + bytes[1] == 0xFF.toByte() -> { + bytes.copyOfRange(2, bytes.size).decodeStrict(StandardCharsets.UTF_16BE) + } + + else -> null + } } private fun ByteArray.decodeStrict(charset: Charset): String? { @@ -117,6 +161,67 @@ object MetadataTextRepair { return score - markerPenalty - max(0, value.length - 120) } + private fun scoreDecodedBytesCandidate(candidate: ByteDecodeCandidate, locale: Locale): Int { + val value = candidate.value + val hasCjk = value.any { Character.UnicodeBlock.of(it) == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS } + val hasHangul = value.any { Character.UnicodeBlock.of(it) in hangulBlocks } + val mixedCjkHangulPenalty = if (hasCjk && hasHangul) 120 else 0 + val charsetOrderBonus = (byteDecodeCharsets.size - candidate.charsetIndex) * 6 + return score(value, value) - mixedCjkHangulPenalty + charsetOrderBonus + + languageBonus(value, locale) + charsetLanguageBonus(candidate, locale) + } + + private fun languageBonus(value: String, locale: Locale): Int { + val language = locale.language.lowercase(Locale.ROOT) + val script = locale.script.lowercase(Locale.ROOT) + val cjkCount = value.count { + Character.UnicodeBlock.of(it) == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS + } + val kanaCount = value.count { Character.UnicodeBlock.of(it) in kanaBlocks } + val hangulCount = value.count { Character.UnicodeBlock.of(it) in hangulBlocks } + val cyrillicCount = value.count { + Character.UnicodeBlock.of(it) == Character.UnicodeBlock.CYRILLIC + } + return when (language) { + "zh" -> if (cjkCount > 0) 160 + cjkCount * 18 else 0 + "ja" -> if (kanaCount + cjkCount > 0) 160 + kanaCount * 24 + cjkCount * 8 else 0 + "ko" -> if (hangulCount > 0) 160 + hangulCount * 24 else 0 + "ru", "uk" -> if (cyrillicCount > 0) 140 + cyrillicCount * 18 else 0 + else -> if (script == "hans" || script == "hant") { + if (cjkCount > 0) 140 + cjkCount * 16 else 0 + } else { + 0 + } + } + } + + private fun charsetLanguageBonus(candidate: ByteDecodeCandidate, locale: Locale): Int { + val language = locale.language.lowercase(Locale.ROOT) + val script = locale.script.lowercase(Locale.ROOT) + val hasCjk = candidate.value.any { + Character.UnicodeBlock.of(it) == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS + } + return when { + language == "zh" || script == "hans" || script == "hant" -> { + when { + candidate.charsetIndex in 1..2 && hasCjk -> 220 + candidate.charsetIndex > 2 && hasCjk -> -120 + else -> 0 + } + } + + language == "ja" -> if (candidate.charsetIndex in 3..4) 180 else 0 + language == "ko" -> if (candidate.charsetIndex == 5) 180 else 0 + language == "ru" || language == "uk" -> if (candidate.charsetIndex == 6) 160 else 0 + else -> 0 + } + } + + private data class ByteDecodeCandidate( + val value: String, + val charsetIndex: Int + ) + private val readableBlocks = setOf( Character.UnicodeBlock.BASIC_LATIN, Character.UnicodeBlock.LATIN_1_SUPPLEMENT, @@ -161,4 +266,16 @@ object MetadataTextRepair { "м§", "�" ) + + private val byteDecodeCharsets = listOf( + StandardCharsets.UTF_8, + Charset.forName("GB18030"), + Charset.forName("Big5"), + Charset.forName("Shift_JIS"), + Charset.forName("EUC-JP"), + Charset.forName("EUC-KR"), + Charset.forName("windows-1251"), + Charset.forName("windows-1252"), + StandardCharsets.ISO_8859_1 + ) } diff --git a/app/src/main/java/com/audio/vibe/data/playback/AudioPlaybackController.kt b/app/src/main/java/com/audio/vibe/data/playback/AudioPlaybackController.kt index 9c5445b..b3fbbc2 100644 --- a/app/src/main/java/com/audio/vibe/data/playback/AudioPlaybackController.kt +++ b/app/src/main/java/com/audio/vibe/data/playback/AudioPlaybackController.kt @@ -1,6 +1,7 @@ package com.audio.vibe.data.playback import android.content.Context +import android.content.ContentUris import android.media.AudioAttributes as PlatformAudioAttributes import android.media.AudioFormat import android.media.AudioManager @@ -10,6 +11,7 @@ import android.os.Build import android.os.ParcelFileDescriptor import android.os.SystemClock import android.provider.DocumentsContract +import android.provider.MediaStore import androidx.annotation.OptIn import androidx.media3.common.AudioAttributes import androidx.media3.common.C @@ -25,6 +27,7 @@ import com.arthenica.ffmpegkit.FFmpegKitConfig import com.arthenica.ffmpegkit.FFmpegSession import com.arthenica.ffmpegkit.Level import com.arthenica.ffmpegkit.LogCallback +import com.audio.vibe.data.repository.StoragePathResolver import com.audio.vibe.domain.model.PlayMode import com.audio.vibe.domain.model.PlaybackTrack import com.audio.vibe.domain.model.ScannedAudioTrack @@ -1095,7 +1098,7 @@ private class FfmpegPcmAudioTrackRenderer( minBufferSize, trackBufferSize ) - val input = openFfmpegInput(context, track.uri) + val input = openFfmpegInput(context, track) inputHandle = input val seekArgs = if (startPositionMs > 0L) { arrayOf("-ss", (startPositionMs / 1000.0).toString()) @@ -1277,7 +1280,7 @@ private class FfmpegPcmAudioTrackRenderer( writtenBytes, outputTrack.playState, outputTrack.playState.toAudioTrackPlayStateLabel(), - outputTrack.playbackHeadPosition + outputTrack.safePlaybackHeadPosition() ) } val positionMs = writtenBytes.toAudioDurationMs( @@ -1297,7 +1300,7 @@ private class FfmpegPcmAudioTrackRenderer( positionMs, outputTrack.playState, outputTrack.playState.toAudioTrackPlayStateLabel(), - outputTrack.playbackHeadPosition + outputTrack.safePlaybackHeadPosition() ) } if (positionMs - lastProgressPublishMs >= PROGRESS_UPDATE_INTERVAL_MS) { @@ -1314,7 +1317,7 @@ private class FfmpegPcmAudioTrackRenderer( track.id, outputTrack.playState, outputTrack.playState.toAudioTrackPlayStateLabel(), - outputTrack.playbackHeadPosition, + outputTrack.safePlaybackHeadPosition(), stopped.get() ) outputTrack.stop() @@ -1502,6 +1505,20 @@ private fun writePcm(track: AudioTrack, encoding: Int, buffer: ByteArray, read: } } +private fun AudioTrack.safePlaybackHeadPosition(): Int { + return runCatching { playbackHeadPosition } + .onFailure { error -> + Timber.w( + error, + "AudioTrack playback head read failed: playState=%d(%s) causeChain=%s", + playState, + playState.toAudioTrackPlayStateLabel(), + error.playbackCauseChain() + ) + } + .getOrDefault(-1) +} + private fun PlaybackAudioParameters.toLogString(): String { return "format=${format ?: "unknown"},sampleRate=${sampleRateHz ?: "unknown"}," + "bitDepth=${bitDepth ?: "unknown"},channels=${channelCount ?: "unknown"}," + @@ -1519,7 +1536,15 @@ private data class FfmpegInputHandle( } } -private fun openFfmpegInput(context: Context, uri: Uri): FfmpegInputHandle { +private fun openFfmpegInput(context: Context, track: PlaybackTrack): FfmpegInputHandle { + return openFfmpegInput(context, track.uri, track.sourcePath) +} + +private fun openFfmpegInput( + context: Context, + uri: Uri, + sourcePath: String? +): FfmpegInputHandle { return when (uri.scheme) { "file" -> FfmpegInputHandle( path = uri.path.orEmpty(), @@ -1527,21 +1552,7 @@ private fun openFfmpegInput(context: Context, uri: Uri): FfmpegInputHandle { sizeBytes = uri.path?.let { path -> File(path).length().takeIf { it > 0L } } ) "content" -> { - if (DocumentsContract.isDocumentUri(context, uri)) { - FfmpegInputHandle( - path = FFmpegKitConfig.getSafParameterForRead(context, uri), - kind = "saf-document" - ) - } else { - val descriptor = context.contentResolver.openFileDescriptor(uri, "r") - ?: error("Cannot open content uri for FFmpeg playback: $uri") - FfmpegInputHandle( - path = "/proc/self/fd/${descriptor.fd}", - kind = "content-fd", - sizeBytes = descriptor.safeStatSize(), - descriptor = descriptor - ) - } + openContentFfmpegInput(context, uri, sourcePath) } else -> FfmpegInputHandle( path = FFmpegKitConfig.getSafParameterForRead(context, uri), @@ -1550,6 +1561,151 @@ private fun openFfmpegInput(context: Context, uri: Uri): FfmpegInputHandle { } } +private fun openContentFfmpegInput( + context: Context, + uri: Uri, + sourcePath: String? +): FfmpegInputHandle { + if (DocumentsContract.isDocumentUri(context, uri)) { + openSafParameterInputSafely(context, uri)?.let { return it } + } + + openFileDescriptorSafely(context, uri)?.let { descriptor -> + return descriptor.toFfmpegInputHandle( + kind = if (DocumentsContract.isDocumentUri(context, uri)) { + "saf-document-fd" + } else { + "content-fd" + } + ) + } + + sourcePath + ?.let { findMediaStoreAudioUri(context, it) } + ?.let { mediaStoreUri -> + openFileDescriptorSafely(context, mediaStoreUri)?.let { descriptor -> + return descriptor.toFfmpegInputHandle(kind = "mediastore-fd") + } + } + + sourcePath + ?.let { StoragePathResolver(context).resolveFileCandidates(it) } + ?.firstOrNull { it.exists() && it.length() > 0L } + ?.let { file -> + return FfmpegInputHandle( + path = file.absolutePath, + kind = "resolved-file", + sizeBytes = file.length() + ) + } + + return FfmpegInputHandle( + path = FFmpegKitConfig.getSafParameterForRead(context, uri), + kind = if (DocumentsContract.isDocumentUri(context, uri)) { + "saf-document" + } else { + "content-saf" + } + ) +} + +private fun openSafParameterInputSafely( + context: Context, + uri: Uri +): FfmpegInputHandle? { + return runCatching { + FfmpegInputHandle( + path = FFmpegKitConfig.getSafParameterForRead(context, uri), + kind = "saf-document" + ) + }.onFailure { error -> + Timber.w( + error, + "Failed to create SAF parameter for FFmpeg input: uri=%s causeChain=%s", + uri, + error.playbackCauseChain() + ) + }.getOrNull() +} + +private fun openFileDescriptorSafely( + context: Context, + uri: Uri +): ParcelFileDescriptor? { + return runCatching { + context.contentResolver.openFileDescriptor(uri, "r") + }.onFailure { error -> + Timber.w( + error, + "Failed to open content fd for FFmpeg input: uri=%s causeChain=%s", + uri, + error.playbackCauseChain() + ) + }.getOrNull() +} + +private fun ParcelFileDescriptor.toFfmpegInputHandle(kind: String): FfmpegInputHandle { + return FfmpegInputHandle( + path = "/proc/self/fd/$fd", + kind = kind, + sizeBytes = safeStatSize(), + descriptor = this + ) +} + +private fun findMediaStoreAudioUri(context: Context, sourcePath: String): Uri? { + val pathResolver = StoragePathResolver(context) + val parts = pathResolver.sourcePathParts(sourcePath) ?: return null + val fileName = parts.relativePath.substringAfterLast('/').takeIf { it.isNotBlank() } + ?: return null + val collection = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + MediaStore.Audio.Media.getContentUri( + if (pathResolver.isPrimaryVolume(parts.volumeName)) { + MediaStore.VOLUME_EXTERNAL + } else { + parts.volumeName + } + ) + } else { + MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + } + val projection = arrayOf(MediaStore.Audio.Media._ID) + val selection: String + val args: Array + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + val parentPath = parts.relativePath.substringBeforeLast('/', missingDelimiterValue = "") + val relativePath = parentPath.takeIf { it.isNotBlank() }?.let { "$it/" } + selection = if (relativePath == null) { + "${MediaStore.Audio.Media.DISPLAY_NAME} = ? COLLATE NOCASE" + } else { + "${MediaStore.Audio.Media.DISPLAY_NAME} = ? COLLATE NOCASE AND " + + "(${MediaStore.Audio.Media.RELATIVE_PATH} = ? COLLATE NOCASE OR " + + "${MediaStore.Audio.Media.RELATIVE_PATH} = ? COLLATE NOCASE)" + } + args = if (relativePath == null) { + arrayOf(fileName) + } else { + arrayOf(fileName, relativePath, relativePath.trimEnd('/')) + } + } else { + selection = "${MediaStore.Audio.Media.DISPLAY_NAME} = ? COLLATE NOCASE" + args = arrayOf(fileName) + } + return runCatching { + context.contentResolver.query(collection, projection, selection, args, null)?.use { cursor -> + if (!cursor.moveToFirst()) return@use null + ContentUris.withAppendedId(collection, cursor.getLong(0)) + } + }.onFailure { error -> + Timber.w( + error, + "Failed to resolve MediaStore audio uri for FFmpeg input: sourcePath=%s causeChain=%s", + sourcePath, + error.playbackCauseChain() + ) + }.getOrNull() +} + private fun ParcelFileDescriptor.safeStatSize(): Long? { return runCatching { statSize.takeIf { it >= 0L } }.getOrNull() } @@ -1621,7 +1777,13 @@ private fun PlaybackException.canFallbackToFfmpeg(): Boolean { PlaybackException.ERROR_CODE_PARSING_CONTAINER_UNSUPPORTED, PlaybackException.ERROR_CODE_PARSING_MANIFEST_UNSUPPORTED, PlaybackException.ERROR_CODE_PARSING_CONTAINER_MALFORMED - ) + ) || ( + errorCode == PlaybackException.ERROR_CODE_IO_UNSPECIFIED && + hasCause() + ) || ( + errorCode == PlaybackException.ERROR_CODE_FAILED_RUNTIME_CHECK && + hasCause() + ) } internal fun isInvalidMedia3Duration(durationMs: Long): Boolean { @@ -1647,6 +1809,10 @@ private fun Throwable.playbackCauseChain(): String { } } +private inline fun Throwable.hasCause(): Boolean { + return generateSequence(this) { it.cause }.any { it is T } +} + private fun Int.toMedia3StateName(): String { return when (this) { Player.STATE_IDLE -> "IDLE" diff --git a/app/src/main/java/com/audio/vibe/data/repository/StoragePathResolver.kt b/app/src/main/java/com/audio/vibe/data/repository/StoragePathResolver.kt index 0a157dd..3ac441b 100644 --- a/app/src/main/java/com/audio/vibe/data/repository/StoragePathResolver.kt +++ b/app/src/main/java/com/audio/vibe/data/repository/StoragePathResolver.kt @@ -2,7 +2,9 @@ package com.audio.vibe.data.repository import android.content.Context import android.os.Build +import android.os.Environment import android.os.storage.StorageManager +import java.io.File /** * 把 MediaStore、SAF、raw 绝对路径统一成数据库使用的 sourcePath。 @@ -96,6 +98,43 @@ class StoragePathResolver(context: Context) { return normalized.takeIf { it.isNotBlank() } } + fun resolveFileCandidates(sourcePath: String): List { + val rawFile = File(sourcePath) + if (rawFile.isAbsolute) return listOf(rawFile) + + val parts = sourcePathParts(sourcePath) ?: return emptyList() + val candidates = linkedSetOf() + if (parts.volumeName == null || parts.volumeName.isPrimaryStorageVolume()) { + candidates += File(Environment.getExternalStorageDirectory(), parts.relativePath) + } else { + mountedVolumeRoots() + .filter { it.volumeName.equals(parts.volumeName, ignoreCase = true) } + .forEach { candidates += File("/${it.rootPath}", parts.relativePath) } + staticVolumeRoots.forEach { root -> + candidates += File("/$root", "${parts.volumeName}/${parts.relativePath}") + } + } + return candidates.toList() + } + + fun sourcePathParts(sourcePath: String): SourcePathParts? { + val normalized = sourcePath.normalizedPath() ?: return null + val volume = normalized.substringBefore(DOCUMENT_ID_SEPARATOR, missingDelimiterValue = "") + val relativePath = if (DOCUMENT_ID_SEPARATOR in normalized) { + normalized.substringAfter(DOCUMENT_ID_SEPARATOR).trim('/') + } else { + normalized + }.takeIf { it.isNotBlank() } ?: return null + return SourcePathParts( + volumeName = volume.takeIf { it.isNotBlank() }, + relativePath = relativePath + ) + } + + fun isPrimaryVolume(volumeName: String?): Boolean { + return volumeName == null || volumeName.isPrimaryStorageVolume() + } + private fun buildVolumeSourcePath( volumeName: String?, relativePath: String?, @@ -160,6 +199,11 @@ class StoragePathResolver(context: Context) { val rootPath: String ) + data class SourcePathParts( + val volumeName: String?, + val relativePath: String + ) + companion object { private const val RAW_DOCUMENT_PREFIX = "raw:" private const val DOCUMENT_ID_SEPARATOR = ':' diff --git a/app/src/main/java/com/audio/vibe/ui/components/ToastExt.kt b/app/src/main/java/com/audio/vibe/ui/components/ToastExt.kt new file mode 100644 index 0000000..5969eac --- /dev/null +++ b/app/src/main/java/com/audio/vibe/ui/components/ToastExt.kt @@ -0,0 +1,32 @@ +package com.audio.vibe.ui.components + +import android.content.Context +import android.text.TextUtils +import android.widget.TextView +import android.widget.Toast + +fun showPlaybackToast( + context: Context, + message: String, + maxLines: Int = 10 +) { + val text = message.limitLogicalLines(maxLines) + Toast.makeText(context, text, Toast.LENGTH_SHORT).apply { + limitTextLines(maxLines) + }.show() +} + +@Suppress("DEPRECATION") +private fun Toast.limitTextLines(maxLines: Int) { + view?.findViewById(android.R.id.message)?.let { textView -> + textView.maxLines = maxLines + textView.ellipsize = TextUtils.TruncateAt.END + } +} + +private fun String.limitLogicalLines(maxLines: Int): String { + if (maxLines <= 0) return "" + val lines = lines() + if (lines.size <= maxLines) return this + return lines.take(maxLines).joinToString("\n").trimEnd() + "..." +} diff --git a/app/src/main/java/com/audio/vibe/ui/musicmanager/MusicManagerScreen.kt b/app/src/main/java/com/audio/vibe/ui/musicmanager/MusicManagerScreen.kt index 4ac3bfe..9d1cb94 100644 --- a/app/src/main/java/com/audio/vibe/ui/musicmanager/MusicManagerScreen.kt +++ b/app/src/main/java/com/audio/vibe/ui/musicmanager/MusicManagerScreen.kt @@ -5,7 +5,6 @@ import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.os.Build -import android.widget.Toast import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.background @@ -80,6 +79,7 @@ import com.audio.vibe.ui.components.RoundIcon import com.audio.vibe.ui.components.SecondaryButton import com.audio.vibe.ui.components.VibeCard import com.audio.vibe.ui.components.VibeScreen +import com.audio.vibe.ui.components.showPlaybackToast import com.audio.vibe.ui.i18n.AppStrings import com.audio.vibe.ui.i18n.LocalAppStrings import com.audio.vibe.ui.player.MiniPlayerBar @@ -205,7 +205,7 @@ private fun MusicManagerContent( val trackListState = rememberLazyListState() LaunchedEffect(miniPlayerState.errorMessage) { miniPlayerState.errorMessage?.takeIf { it.isNotBlank() }?.let { message -> - Toast.makeText(context, message, Toast.LENGTH_SHORT).show() + showPlaybackToast(context, message) } } diff --git a/app/src/main/java/com/audio/vibe/ui/player/PlayerScreen.kt b/app/src/main/java/com/audio/vibe/ui/player/PlayerScreen.kt index 5d68f00..767cee7 100644 --- a/app/src/main/java/com/audio/vibe/ui/player/PlayerScreen.kt +++ b/app/src/main/java/com/audio/vibe/ui/player/PlayerScreen.kt @@ -3,7 +3,6 @@ package com.audio.vibe.ui.player import android.app.Activity import android.content.Context import android.content.ContextWrapper -import android.widget.Toast import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.Image import androidx.compose.foundation.basicMarquee @@ -68,6 +67,12 @@ import com.audio.vibe.data.playback.AudioPlaybackService import com.audio.vibe.data.playback.PlaybackServiceController import com.audio.vibe.domain.model.PlayMode import com.audio.vibe.ui.components.AudioVibeColors +import com.audio.vibe.ui.components.showPlaybackToast +import com.audio.vibe.ui.i18n.LocalResolvedLanguage +import com.audio.vibe.ui.i18n.resourceLocale +import com.audio.vibe.ui.player.lyrics.LyricLine +import com.audio.vibe.ui.player.lyrics.LyricLoader +import com.audio.vibe.ui.player.lyrics.LyricView import kotlin.math.abs @Composable @@ -93,28 +98,40 @@ private fun PlayerContent( onBack: () -> Unit, controller: PlaybackServiceController ) { + val context = LocalContext.current + val lyricLocale = LocalResolvedLanguage.current.resourceLocale() + val lyricLoader: (suspend (String?, android.net.Uri?) -> List?)? = remember( + context, + lyricLocale + ) { + { sourcePath, uri -> LyricLoader.load(sourcePath, uri, context, lyricLocale) } + } val viewModel: PlayerViewModel = viewModel( - factory = PlayerViewModelFactory(controller) + factory = PlayerViewModelFactory(controller, lyricLoader) ) val uiState by viewModel.uiState.collectAsState() var scrubStartedButtonState by remember { mutableStateOf(null) } var heldSeekButtonState by remember { mutableStateOf(null) } var heldSeekTargetMs by remember { mutableStateOf(null) } var heldSeekTrackId by remember { mutableStateOf(null) } + var lyricsFullscreen by remember { mutableStateOf(false) } val trackText = rememberStableTrackText( currentId = uiState.currentId, title = uiState.title, artist = uiState.artist, album = uiState.album ) - val context = LocalContext.current LaunchedEffect(uiState.errorMessage) { uiState.errorMessage?.takeIf { it.isNotBlank() }?.let { message -> - Toast.makeText(context, message, Toast.LENGTH_SHORT).show() + showPlaybackToast(context, message) } } + LaunchedEffect(uiState.currentId, uiState.sourcePath, uiState.uri) { + viewModel.loadLyrics(uiState.currentId, uiState.sourcePath, uiState.uri) + } + LaunchedEffect(uiState.currentId, uiState.progressMs, uiState.isPlaying, heldSeekTargetMs) { val target = heldSeekTargetMs ?: return@LaunchedEffect val expectedButtonState = heldSeekButtonState ?: return@LaunchedEffect @@ -131,6 +148,17 @@ private fun PlayerContent( } } + val lyricLines = uiState.lyricLines + val lyricsResolved = uiState.lyricTrackId == uiState.currentId + val hasLyrics = lyricsResolved && lyricLines.isNotEmpty() + val showLyricSlot = uiState.currentId != null + + LaunchedEffect(uiState.currentId, hasLyrics) { + if (!hasLyrics) { + lyricsFullscreen = false + } + } + Box(modifier = Modifier.fillMaxSize()) { PlayerBackdrop( trackId = uiState.currentId, @@ -140,98 +168,130 @@ private fun PlayerContent( modifier = Modifier.fillMaxSize() ) - Column( - modifier = Modifier - .fillMaxSize() - .statusBarsPadding() - .navigationBarsPadding() - .padding(horizontal = 24.dp), - horizontalAlignment = Alignment.CenterHorizontally - ) { - PlayerTopBar( - onBack = onBack, - onQueueClick = viewModel::onToggleQueueSheet + if (lyricsFullscreen && hasLyrics) { + FullscreenLyricsContent( + lyricLines = lyricLines, + currentPositionMs = uiState.progressMs, + isPlaying = uiState.isPlaying, + onSeekTo = viewModel::onSeekTo, + onBack = { lyricsFullscreen = false } ) - - Spacer(Modifier.weight(1f)) - - CoverImage( - trackId = uiState.currentId, - sourcePath = uiState.sourcePath, - uri = uiState.uri, - isCoverEdited = uiState.isCoverEdited, + } else { + Column( modifier = Modifier - .fillMaxWidth(0.82f) - .widthIn(max = 320.dp) - .aspectRatio(1f) - ) + .fillMaxSize() + .statusBarsPadding() + .navigationBarsPadding() + .padding(horizontal = 24.dp), + horizontalAlignment = Alignment.CenterHorizontally + ) { + PlayerTopBar( + onBack = onBack, + onQueueClick = viewModel::onToggleQueueSheet + ) - Spacer(Modifier.height(30.dp)) - - TrackInfoText( - text = trackText - ) - - Spacer(Modifier.height(32.dp)) - - ProgressSection( - positionMs = uiState.progressMs, - durationMs = uiState.durationMs, - canSeek = uiState.canSeek, - onScrubStart = { - scrubStartedButtonState = heldSeekButtonState ?: uiState.isPlaying - }, - onSeekTo = { target -> - heldSeekButtonState = scrubStartedButtonState ?: uiState.isPlaying - heldSeekTargetMs = target - heldSeekTrackId = uiState.currentId - scrubStartedButtonState = null - viewModel.onSeekTo(target) + if (!showLyricSlot) { + Spacer(Modifier.weight(1f)) } - ) - Spacer(Modifier.height(18.dp)) + CoverImage( + trackId = uiState.currentId, + sourcePath = uiState.sourcePath, + uri = uiState.uri, + isCoverEdited = uiState.isCoverEdited, + modifier = if (showLyricSlot) + Modifier + .fillMaxWidth(0.78f) + .widthIn(min = 220.dp, max = 300.dp) + .aspectRatio(1f) + else + Modifier + .fillMaxWidth(0.82f) + .widthIn(max = 320.dp) + .aspectRatio(1f) + ) - PlayControlRow( - showPause = heldSeekButtonState ?: uiState.isPlaying, - onSkipPrevious = viewModel::onSkipPrevious, - onPlayPause = { - heldSeekButtonState = null - heldSeekTargetMs = null - heldSeekTrackId = null - viewModel.onPlayPause() - }, - onSkipNext = viewModel::onSkipNext - ) + Spacer(Modifier.height(if (showLyricSlot) 20.dp else 30.dp)) - Spacer(Modifier.height(18.dp)) + TrackInfoText( + text = trackText + ) - PlaybackMetaRow( - queueLabel = uiState.queueLabel, - playMode = uiState.playMode, - onTogglePlayMode = viewModel::onTogglePlayMode - ) + if (showLyricSlot) { + Spacer(Modifier.height(16.dp)) + CompactLyricsSlot( + lyricLines = lyricLines, + lyricsResolved = lyricsResolved, + currentPositionMs = uiState.progressMs, + isPlaying = uiState.isPlaying, + onSeekTo = viewModel::onSeekTo, + onExpand = { lyricsFullscreen = true } + ) + } else { + Spacer(Modifier.height(32.dp)) + } - Spacer(Modifier.height(18.dp)) + ProgressSection( + positionMs = uiState.progressMs, + durationMs = uiState.durationMs, + canSeek = uiState.canSeek, + onScrubStart = { + scrubStartedButtonState = heldSeekButtonState ?: uiState.isPlaying + }, + onSeekTo = { target -> + heldSeekButtonState = scrubStartedButtonState ?: uiState.isPlaying + heldSeekTargetMs = target + heldSeekTrackId = uiState.currentId + scrubStartedButtonState = null + viewModel.onSeekTo(target) + } + ) - AudioChainInfoBar( - decodeLabel = uiState.decodeLabel, - audioChain = uiState.audioChain, - onClick = viewModel::onToggleBottomSheet - ) + Spacer(Modifier.height(18.dp)) - Spacer(Modifier.weight(1f)) + PlayControlRow( + showPause = heldSeekButtonState ?: uiState.isPlaying, + onSkipPrevious = viewModel::onSkipPrevious, + onPlayPause = { + heldSeekButtonState = null + heldSeekTargetMs = null + heldSeekTrackId = null + viewModel.onPlayPause() + }, + onSkipNext = viewModel::onSkipNext + ) + + Spacer(Modifier.height(18.dp)) + + PlaybackMetaRow( + queueLabel = uiState.queueLabel, + playMode = uiState.playMode, + onTogglePlayMode = viewModel::onTogglePlayMode + ) + + Spacer(Modifier.height(18.dp)) + + AudioChainInfoBar( + decodeLabel = uiState.decodeLabel, + audioChain = uiState.audioChain, + onClick = viewModel::onToggleBottomSheet + ) + + if (!showLyricSlot) { + Spacer(Modifier.weight(1f)) + } + } } } - if (uiState.showBottomSheet) { + if (!lyricsFullscreen && uiState.showBottomSheet) { PlayerBottomSheet( state = uiState, onDismiss = viewModel::onDismissBottomSheet ) } - if (uiState.showQueueSheet) { + if (!lyricsFullscreen && uiState.showQueueSheet) { PlayerQueueSheet( state = uiState, onTrackClick = viewModel::onPlayQueueItem, @@ -240,6 +300,85 @@ private fun PlayerContent( } } +@Composable +private fun CompactLyricsSlot( + lyricLines: List, + lyricsResolved: Boolean, + currentPositionMs: Long, + isPlaying: Boolean, + onSeekTo: (Long) -> Unit, + onExpand: () -> Unit +) { + Box( + modifier = Modifier + .fillMaxWidth() + .height(72.dp), + contentAlignment = Alignment.Center + ) { + if (lyricLines.isNotEmpty() || lyricsResolved) { + LyricView( + lyricLines = lyricLines, + currentPositionMs = currentPositionMs, + isPlaying = isPlaying, + onSeekTo = onSeekTo, + expanded = false, + onExpand = onExpand, + modifier = Modifier.fillMaxSize() + ) + } + } +} + +@Composable +private fun FullscreenLyricsContent( + lyricLines: List, + currentPositionMs: Long, + isPlaying: Boolean, + onSeekTo: (Long) -> Unit, + onBack: () -> Unit +) { + Column( + modifier = Modifier + .fillMaxSize() + .statusBarsPadding() + .navigationBarsPadding() + .padding(horizontal = 18.dp), + horizontalAlignment = Alignment.CenterHorizontally + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .height(58.dp), + verticalAlignment = Alignment.CenterVertically + ) { + IconButton( + onClick = onBack, + modifier = Modifier + .size(42.dp) + .clip(CircleShape) + .background(PlayerColors.chrome) + ) { + Icon( + Icons.AutoMirrored.Filled.ArrowBack, + contentDescription = "返回播放页", + tint = Color.White, + modifier = Modifier.size(22.dp) + ) + } + Spacer(Modifier.weight(1f)) + } + + LyricView( + lyricLines = lyricLines, + currentPositionMs = currentPositionMs, + isPlaying = isPlaying, + onSeekTo = onSeekTo, + expanded = true, + modifier = Modifier.weight(1f) + ) + } +} + private data class StableTrackText( val title: String, val subtitle: String diff --git a/app/src/main/java/com/audio/vibe/ui/player/PlayerUiState.kt b/app/src/main/java/com/audio/vibe/ui/player/PlayerUiState.kt index e9db471..ef1780a 100644 --- a/app/src/main/java/com/audio/vibe/ui/player/PlayerUiState.kt +++ b/app/src/main/java/com/audio/vibe/ui/player/PlayerUiState.kt @@ -5,6 +5,7 @@ import com.audio.vibe.data.playback.PlaybackAudioParameters import com.audio.vibe.data.playback.PlaybackBackend import com.audio.vibe.data.playback.PlaybackQueueItem import com.audio.vibe.domain.model.PlayMode +import com.audio.vibe.ui.player.lyrics.LyricLine @Immutable data class PlayerUiState( @@ -31,7 +32,9 @@ data class PlayerUiState( val uri: android.net.Uri? = null, val isCoverEdited: Boolean = false, val showBottomSheet: Boolean = false, - val showQueueSheet: Boolean = false + val showQueueSheet: Boolean = false, + val lyricLines: List = emptyList(), + val lyricTrackId: Long? = null ) { val hasError: Boolean get() = !errorMessage.isNullOrBlank() diff --git a/app/src/main/java/com/audio/vibe/ui/player/PlayerViewModel.kt b/app/src/main/java/com/audio/vibe/ui/player/PlayerViewModel.kt index 354742e..defc12c 100644 --- a/app/src/main/java/com/audio/vibe/ui/player/PlayerViewModel.kt +++ b/app/src/main/java/com/audio/vibe/ui/player/PlayerViewModel.kt @@ -6,17 +6,22 @@ import androidx.lifecycle.viewModelScope import com.audio.vibe.data.playback.PlaybackServiceController import com.audio.vibe.data.playback.PlaybackState import com.audio.vibe.domain.model.PlayMode +import com.audio.vibe.ui.player.lyrics.LyricLine +import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch class PlayerViewModel( - private val controller: PlaybackServiceController + private val controller: PlaybackServiceController, + private val lyricLoader: (suspend (String?, android.net.Uri?) -> List?)? = null ) : ViewModel() { private val _uiState = MutableStateFlow(PlayerUiState()) val uiState: StateFlow = _uiState + private var lyricLoadJob: Job? = null + private var lyricLoadGeneration = 0 init { viewModelScope.launch { @@ -67,15 +72,35 @@ class PlayerViewModel( fun onDismissQueueSheet() { _uiState.update { it.copy(showQueueSheet = false) } } + + fun loadLyrics(trackId: Long?, sourcePath: String?, uri: android.net.Uri?) { + val loader = lyricLoader ?: return + if (trackId == null || (sourcePath == null && uri == null)) { + lyricLoadJob?.cancel() + lyricLoadGeneration++ + _uiState.update { it.copy(lyricLines = emptyList(), lyricTrackId = trackId) } + return + } + + lyricLoadJob?.cancel() + val generation = ++lyricLoadGeneration + lyricLoadJob = viewModelScope.launch { + val lines = loader(sourcePath, uri) ?: emptyList() + if (generation == lyricLoadGeneration) { + _uiState.update { it.copy(lyricLines = lines, lyricTrackId = trackId) } + } + } + } } class PlayerViewModelFactory( - private val controller: PlaybackServiceController + private val controller: PlaybackServiceController, + private val lyricLoader: (suspend (String?, android.net.Uri?) -> List?)? = null ) : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun create(modelClass: Class): T { if (modelClass.isAssignableFrom(PlayerViewModel::class.java)) { - return PlayerViewModel(controller) as T + return PlayerViewModel(controller, lyricLoader) as T } throw IllegalArgumentException("Unknown ViewModel class: ${modelClass.name}") } @@ -83,6 +108,7 @@ class PlayerViewModelFactory( private fun PlayerUiState.fromPlaybackState(state: PlaybackState): PlayerUiState { val hasCurrentTrack = state.currentId != null || state.currentTrack != null + return copy( currentId = state.currentId, title = state.currentTitle.orEmpty().ifBlank { state.currentTrack?.title.orEmpty() }, diff --git a/app/src/main/java/com/audio/vibe/ui/player/lyrics/LyricLine.kt b/app/src/main/java/com/audio/vibe/ui/player/lyrics/LyricLine.kt new file mode 100644 index 0000000..63dd3ec --- /dev/null +++ b/app/src/main/java/com/audio/vibe/ui/player/lyrics/LyricLine.kt @@ -0,0 +1,15 @@ +package com.audio.vibe.ui.player.lyrics + +data class LyricLine( + val timeMs: Long, + val text: String, + val words: List = emptyList() +) { + val hasWords: Boolean + get() = words.isNotEmpty() +} + +data class LyricWord( + val timeMs: Long, + val text: String +) diff --git a/app/src/main/java/com/audio/vibe/ui/player/lyrics/LyricLoader.kt b/app/src/main/java/com/audio/vibe/ui/player/lyrics/LyricLoader.kt new file mode 100644 index 0000000..4ce67cb --- /dev/null +++ b/app/src/main/java/com/audio/vibe/ui/player/lyrics/LyricLoader.kt @@ -0,0 +1,213 @@ +package com.audio.vibe.ui.player.lyrics + +import android.content.ContentUris +import android.content.Context +import android.media.MediaMetadataRetriever +import android.net.Uri +import android.os.Build +import android.provider.DocumentsContract +import android.provider.MediaStore +import com.audio.vibe.common.text.MetadataTextRepair +import com.audio.vibe.data.repository.StoragePathResolver +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import timber.log.Timber +import java.io.File +import java.util.Locale + +object LyricLoader { + + private val lrcExtensions = listOf("lrc", "LRC") + + suspend fun load( + sourcePath: String?, + uri: Uri?, + context: Context, + locale: Locale = Locale.getDefault() + ): List? = withContext(Dispatchers.IO) { + if (sourcePath.isNullOrBlank() && uri == null) return@withContext null + + val externalRaw = loadExternalLrc(context, sourcePath, uri, locale) + if (externalRaw != null) { + Timber.i("Lyric: loaded external LRC for %s", sourcePath) + return@withContext LyricParser.parse(externalRaw) + } + + val embeddedRaw = uri?.let { loadEmbeddedLyrics(context, it, locale) } + if (embeddedRaw != null) { + Timber.i("Lyric: loaded embedded lyrics") + return@withContext LyricParser.parse(embeddedRaw) + } + + // For temporary word-timed lyric UI testing: + return@withContext null + } + + private fun loadExternalLrc( + context: Context, + sourcePath: String?, + uri: Uri?, + locale: Locale + ): String? { + sourcePath?.let { path -> + loadExternalLrcFromFiles(context, path, locale)?.let { return it } + } + loadExternalLrcFromDocumentSibling(context, uri, locale)?.let { return it } + if (sourcePath != null) { + loadExternalLrcFromMediaStore(context, sourcePath, locale)?.let { return it } + } + return null + } + + private fun loadExternalLrcFromFiles( + context: Context, + sourcePath: String, + locale: Locale + ): String? { + val pathResolver = StoragePathResolver(context) + for (audioFile in pathResolver.resolveFileCandidates(sourcePath)) { + val parent = audioFile.parentFile ?: continue + val baseName = audioFile.nameWithoutExtension + + for (ext in lrcExtensions) { + val lrcFile = File(parent, "$baseName.$ext") + if (lrcFile.exists() && lrcFile.length() > 0) { + return runCatching { + MetadataTextRepair.repairBytes( + lrcFile.readBytes(), + locale + ) + } + .getOrNull() + } + } + } + return null + } + + private fun loadExternalLrcFromDocumentSibling( + context: Context, + uri: Uri?, + locale: Locale + ): String? { + if (uri == null || !DocumentsContract.isDocumentUri(context, uri)) return null + val documentId = runCatching { DocumentsContract.getDocumentId(uri) }.getOrNull() + ?: return null + val parent = documentId.substringBeforeLast('/', missingDelimiterValue = "") + val audioName = documentId.substringAfterLast('/', missingDelimiterValue = documentId) + val baseName = audioName.substringBeforeLast('.', missingDelimiterValue = audioName) + if (baseName.isBlank()) return null + + for (ext in lrcExtensions) { + val siblingId = if (parent.isBlank()) "$baseName.$ext" else "$parent/$baseName.$ext" + val siblingUri = DocumentsContract.buildDocumentUriUsingTree(uri, siblingId) + readTextFromUri(context, siblingUri, locale)?.let { return it } + } + return null + } + + private fun loadExternalLrcFromMediaStore( + context: Context, + sourcePath: String, + locale: Locale + ): String? { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return null + val pathResolver = StoragePathResolver(context) + val parts = pathResolver.sourcePathParts(sourcePath) ?: return null + val parentPath = parts.relativePath.substringBeforeLast('/', missingDelimiterValue = "") + .takeIf { it.isNotBlank() } + ?: return null + val baseName = parts.relativePath.substringAfterLast('/') + .substringBeforeLast('.', missingDelimiterValue = "") + .takeIf { it.isNotBlank() } + ?: return null + val collection = runCatching { + MediaStore.Files.getContentUri( + if (pathResolver.isPrimaryVolume(parts.volumeName)) { + MediaStore.VOLUME_EXTERNAL + } else { + parts.volumeName + } + ) + }.getOrNull() ?: return null + val relativePath = "$parentPath/" + + for (ext in lrcExtensions) { + val displayName = "$baseName.$ext" + val lrcUri = queryMediaStoreFile(context, collection, displayName, relativePath) + if (lrcUri != null) { + readTextFromUri(context, lrcUri, locale)?.let { return it } + } + } + return null + } + + private fun queryMediaStoreFile( + context: Context, + collection: Uri, + displayName: String, + relativePath: String + ): Uri? { + val projection = arrayOf(MediaStore.Files.FileColumns._ID) + val selection = "${MediaStore.Files.FileColumns.DISPLAY_NAME} = ? AND " + + "(${MediaStore.Files.FileColumns.RELATIVE_PATH} = ? OR " + + "${MediaStore.Files.FileColumns.RELATIVE_PATH} = ?)" + val args = arrayOf(displayName, relativePath, relativePath.trimEnd('/')) + return runCatching { + context.contentResolver.query(collection, projection, selection, args, null) + ?.use { cursor -> + if (!cursor.moveToFirst()) return@use null + ContentUris.withAppendedId(collection, cursor.getLong(0)) + } + }.getOrNull() + } + + private fun readTextFromUri(context: Context, uri: Uri, locale: Locale): String? { + // For temporary word-timed lyric UI testing: + // return sampleWordTimedLyrics + return runCatching { + context.contentResolver.openInputStream(uri)?.use { input -> + MetadataTextRepair.repairBytes(input.readBytes(), locale) + } + }.getOrNull()?.takeIf { it.isNotBlank() } + } + + private fun loadEmbeddedLyrics(context: Context, uri: Uri, locale: Locale): String? { + return try { + val retriever = MediaMetadataRetriever() + retriever.setDataSource(context, uri) + val raw = extractLyricsFromRetriever(retriever, locale) + retriever.release() + raw + } catch (e: Exception) { + Timber.w("Lyric: failed to extract embedded lyrics: %s", e.message) + null + } + } + + private fun extractLyricsFromRetriever( + retriever: MediaMetadataRetriever, + locale: Locale + ): String? { + try { + val mediaMetadataClass = Class.forName("android.media.MediaMetadata") + val lyricsKeyField = mediaMetadataClass.getField("METADATA_KEY_LYRICS") + val lyricsKey = lyricsKeyField.get(null) as? Int + if (lyricsKey != null) { + val raw = retriever.extractMetadata(lyricsKey) + MetadataTextRepair.repair(raw, locale)?.let { return it } + } + } catch (_: Exception) { + } + return null + } + + @Suppress("unused") + private val sampleWordTimedLyrics = """ + [00:08.00]<00:08.00>静かに <00:08.60>流れる <00:09.20>夜の <00:09.80>メロディ + [00:11.00]<00:11.00>触れた <00:11.45>言葉が <00:11.95>光に <00:12.55>変わる + [00:14.00]<00:14.00>ひとつ <00:14.50>ひとつ <00:15.00>心で <00:15.55>ほどけて + [00:17.00]<00:17.00>きらめく <00:17.55>声だけ <00:18.10>残して + [00:20.00]<00:20.00>明日へ <00:20.55>続いて <00:21.10>いく + """.trimIndent() +} diff --git a/app/src/main/java/com/audio/vibe/ui/player/lyrics/LyricParser.kt b/app/src/main/java/com/audio/vibe/ui/player/lyrics/LyricParser.kt new file mode 100644 index 0000000..701268b --- /dev/null +++ b/app/src/main/java/com/audio/vibe/ui/player/lyrics/LyricParser.kt @@ -0,0 +1,106 @@ +package com.audio.vibe.ui.player.lyrics + +import timber.log.Timber + +object LyricParser { + + private val lineTagRegex = Regex("""\[(\d{1,3}):(\d{2})(?:[.:](\d{1,3}))?]""") + private val wordTagRegex = Regex("""<(\d{1,3}):(\d{2})(?:[.:](\d{1,3}))?>""") + private val metadataTagRegex = Regex("""\[(ti|ar|al|by|offset|length):(.*)]""") + + fun parse(raw: String): List { + val offsetMs = extractOffset(raw) + val lines = raw.lineSequence() + .map { it.trim() } + .filter { it.isNotEmpty() } + .flatMap { line -> parseLine(line) } + .toList() + .sortedBy { it.timeMs } + + if (lines.isEmpty()) return emptyList() + + return if (offsetMs != 0L) { + lines.map { line -> + line.copy( + timeMs = (line.timeMs + offsetMs).coerceAtLeast(0L), + words = line.words.map { word -> + word.copy(timeMs = (word.timeMs + offsetMs).coerceAtLeast(0L)) + } + ) + } + } else { + lines + } + } + + private fun extractOffset(raw: String): Long { + val match = metadataTagRegex.find(raw) ?: return 0L + if (match.groupValues[1] != "offset") return 0L + val value = match.groupValues[2].trim() + return value.toLongOrNull() ?: 0L + } + + private fun parseLine(line: String): List { + val timeMatches = lineTagRegex.findAll(line).toList() + if (timeMatches.isEmpty()) return emptyList() + + val lastMatch = timeMatches.last() + val textStart = lastMatch.range.last + 1 + val text = line.substring(textStart).trim() + + val cleanText = wordTagRegex.replace(text, "").trim() + + val words = if (wordTagRegex.containsMatchIn(text)) { + parseWords(text) + } else { + emptyList() + } + + return timeMatches.map { match -> + LyricLine( + timeMs = match.toTimeMs(), + text = cleanText, + words = words + ) + } + } + + private fun parseWords(lineText: String): List { + val wordMatches = wordTagRegex.findAll(lineText).toList() + if (wordMatches.isEmpty()) return emptyList() + + val words = mutableListOf() + + for (i in wordMatches.indices) { + val match = wordMatches[i] + val tagEnd = match.range.last + 1 + + val nextTagStart = if (i + 1 < wordMatches.size) { + wordMatches[i + 1].range.first + } else { + lineText.length + } + + val wordText = lineText.substring(tagEnd, nextTagStart).trim() + if (wordText.isNotEmpty()) { + words.add( + LyricWord( + timeMs = match.toTimeMs(), + text = wordText + ) + ) + } + } + + return words + } + + private fun MatchResult.toTimeMs(): Long { + val minutes = groupValues[1].toLong() + val seconds = groupValues[2].toLong() + val fraction = groupValues[3].takeIf { it.isNotEmpty() } + ?.let { it.padEnd(3, '0').take(3).toLong() } + ?: 0L + return minutes * 60_000L + seconds * 1_000L + fraction + } +} diff --git a/app/src/main/java/com/audio/vibe/ui/player/lyrics/LyricView.kt b/app/src/main/java/com/audio/vibe/ui/player/lyrics/LyricView.kt new file mode 100644 index 0000000..48a8fbf --- /dev/null +++ b/app/src/main/java/com/audio/vibe/ui/player/lyrics/LyricView.kt @@ -0,0 +1,473 @@ +package com.audio.vibe.ui.player.lyrics + +import androidx.compose.animation.animateColorAsState +import androidx.compose.animation.core.LinearEasing +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.core.tween +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.drawWithContent +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.drawscope.clipRect +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.TextUnit +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import kotlinx.coroutines.delay +import kotlin.math.abs + +@Composable +fun LyricView( + lyricLines: List, + currentPositionMs: Long, + isPlaying: Boolean, + onSeekTo: (Long) -> Unit, + expanded: Boolean = true, + onExpand: (() -> Unit)? = null, + modifier: Modifier = Modifier +) { + if (lyricLines.isEmpty()) { + EmptyLyricPlaceholder(modifier = modifier) + return + } + + val listState = rememberLazyListState() + var manualScrollTimeout by remember { mutableStateOf(false) } + val currentLineIndex = lyricLines.indexOfLast { it.timeMs <= currentPositionMs } + .coerceAtLeast(0) + .coerceAtMost(lyricLines.lastIndex) + val activeWordIndex = lyricLines.getOrNull(currentLineIndex) + ?.activeWordIndex(currentPositionMs) + + val isScrolling by remember { + derivedStateOf { listState.isScrollInProgress } + } + + if (!expanded) { + Box( + modifier = modifier + .fillMaxWidth() + .clickable { onExpand?.invoke() }, + contentAlignment = Alignment.Center + ) { + LyricLineText( + line = lyricLines[currentLineIndex], + nextLineTimeMs = lyricLines.getOrNull(currentLineIndex + 1)?.timeMs, + isCurrent = true, + activeWordIndex = activeWordIndex, + currentPositionMs = currentPositionMs, + onTap = { onExpand?.invoke() }, + compact = true + ) + } + return + } + + LaunchedEffect(isScrolling) { + if (isScrolling) { + manualScrollTimeout = true + } + } + + LaunchedEffect(manualScrollTimeout) { + if (manualScrollTimeout) { + delay(3000L) + manualScrollTimeout = false + } + } + + LaunchedEffect(currentLineIndex, manualScrollTimeout) { + if (!manualScrollTimeout) { + val targetIndex = (currentLineIndex - 2).coerceAtLeast(0) + listState.animateScrollToItem( + index = targetIndex, + scrollOffset = 0 + ) + } + } + + LaunchedEffect(lyricLines.size) { + if (lyricLines.isNotEmpty() && currentLineIndex >= 0) { + val targetIndex = (currentLineIndex - 2).coerceAtLeast(0) + listState.scrollToItem(targetIndex, 0) + } + } + + LazyColumn( + state = listState, + modifier = modifier.fillMaxSize(), + contentPadding = PaddingValues(vertical = 132.dp), + horizontalAlignment = Alignment.CenterHorizontally + ) { + itemsIndexed( + items = lyricLines, + key = { index, _ -> index } + ) { index, line -> + val isCurrent = index == currentLineIndex + + LyricLineText( + line = line, + nextLineTimeMs = lyricLines.getOrNull(index + 1)?.timeMs, + isCurrent = isCurrent, + activeWordIndex = if (isCurrent) activeWordIndex else null, + currentPositionMs = currentPositionMs, + distanceFromCurrent = abs(index - currentLineIndex), + onTap = { + val seekTime = if (line.hasWords && line.words.isNotEmpty()) { + line.words.first().timeMs + } else { + line.timeMs + } + onSeekTo(seekTime) + manualScrollTimeout = true + } + ) + } + } +} + +@Composable +private fun LyricLineText( + line: LyricLine, + nextLineTimeMs: Long?, + isCurrent: Boolean, + activeWordIndex: Int?, + currentPositionMs: Long, + onTap: () -> Unit, + compact: Boolean = false, + distanceFromCurrent: Int = 0 +) { + val visualSpec = lyricLineVisualSpec(compact, isCurrent, distanceFromCurrent) + val targetColor by animateColorAsState( + targetValue = visualSpec.color, + animationSpec = tween(durationMillis = 300), + label = "lyricColor" + ) + val targetSize = visualSpec.fontSizeSp.sp + val targetWeight = if (activeWordIndex != null && isCurrent) { + FontWeight.SemiBold + } else { + visualSpec.fontWeight + } + val targetLineHeight = visualSpec.lineHeightSp.sp + + val backgroundShape = RoundedCornerShape(if (compact) 24.dp else 12.dp) + val backgroundBrush = if (compact) { + Brush.horizontalGradient( + colorStops = arrayOf( + 0.00f to Color.Transparent, + 0.18f to visualSpec.backgroundEdgeColor, + 0.50f to visualSpec.backgroundCenterColor, + 0.82f to visualSpec.backgroundEdgeColor, + 1.00f to Color.Transparent + ) + ) + } else { + Brush.horizontalGradient(listOf(Color.Transparent, Color.Transparent)) + } + + Box( + modifier = Modifier + .fillMaxWidth() + .padding( + horizontal = if (compact) 6.dp else 28.dp, + vertical = if (compact) 4.dp else 12.dp + ) + .background(backgroundBrush, backgroundShape) + .clickable(onClick = onTap), + contentAlignment = Alignment.Center + ) { + if (line.hasWords) { + KaraokeLyricText( + line = line, + nextLineTimeMs = nextLineTimeMs, + isCurrent = isCurrent, + currentPositionMs = currentPositionMs, + baseColor = targetColor, + activeColor = if (compact) LyricColors.compactAccent else LyricColors.actionBlue, + fontSize = targetSize, + fontWeight = targetWeight, + lineHeight = targetLineHeight + ) + } else { + Text( + text = line.text, + color = targetColor, + fontSize = targetSize, + fontWeight = targetWeight, + lineHeight = targetLineHeight, + textAlign = TextAlign.Center, + modifier = Modifier.fillMaxWidth() + ) + } + } +} + +@Composable +private fun KaraokeLyricText( + line: LyricLine, + nextLineTimeMs: Long?, + isCurrent: Boolean, + currentPositionMs: Long, + baseColor: Color, + activeColor: Color, + fontSize: TextUnit, + fontWeight: FontWeight, + lineHeight: TextUnit +) { + val characters = buildLyricCharacters(line) + val flowPosition = if (isCurrent) { + line.flowCharacterPosition(currentPositionMs, nextLineTimeMs, characters) + } else { + null + } + val animatedFlowPosition by animateFloatAsState( + targetValue = flowPosition ?: -1f, + animationSpec = tween(durationMillis = 180, easing = LinearEasing), + label = "lyricFlowPosition" + ) + val highlightProgress = lyricHighlightProgress(animatedFlowPosition, characters.size) + var textWidthPx by remember(line.text) { mutableStateOf(0f) } + + Box( + modifier = Modifier.fillMaxWidth(), + contentAlignment = Alignment.Center + ) { + Text( + text = line.text, + color = baseColor, + fontSize = fontSize, + fontWeight = fontWeight, + lineHeight = lineHeight, + textAlign = TextAlign.Center, + modifier = Modifier.fillMaxWidth(), + onTextLayout = { result -> + textWidthPx = if (result.lineCount > 0) { + result.getLineRight(0) - result.getLineLeft(0) + } else { + 0f + } + } + ) + Text( + text = line.text, + color = activeColor, + fontSize = fontSize, + fontWeight = FontWeight.SemiBold, + lineHeight = lineHeight, + textAlign = TextAlign.Center, + modifier = Modifier + .fillMaxWidth() + .drawWithContent { + if (textWidthPx <= 0f || highlightProgress <= 0f) return@drawWithContent + val left = ((size.width - textWidthPx) / 2f).coerceAtLeast(0f) + val right = (left + textWidthPx * highlightProgress) + .coerceIn(left, size.width) + clipRect(left = left, top = 0f, right = right, bottom = size.height) { + this@drawWithContent.drawContent() + } + } + ) + } +} + +internal fun lyricHighlightProgress(flowPosition: Float, totalCharacters: Int): Float { + if (flowPosition < 0f || totalCharacters <= 0) return 0f + return (flowPosition / totalCharacters).coerceIn(0f, 1f) +} + +internal data class LyricLineVisualSpec( + val fontSizeSp: Int, + val lineHeightSp: Int, + val fontWeight: FontWeight, + val color: Color, + val backgroundCenterColor: Color = Color.Transparent, + val backgroundEdgeColor: Color = Color.Transparent +) + +internal fun LyricLine.activeWordIndex(currentPositionMs: Long): Int? { + if (!hasWords) return null + return words.indexOfLast { it.timeMs <= currentPositionMs }.coerceAtLeast(0) +} + +internal data class LyricCharacter( + val text: String, + val wordIndex: Int? +) + +internal fun buildLyricCharacters(line: LyricLine): List { + return buildList { + line.words.forEachIndexed { wordIndex, word -> + val leadingSpace = wordIndex > 0 && + !word.text.startsWith(" ") && + !word.text.startsWith(",") && + !word.text.startsWith(".") + if (leadingSpace) add(LyricCharacter(" ", wordIndex = null)) + word.text.toLyricCharacters().forEach { add(LyricCharacter(it, wordIndex)) } + } + } +} + +internal fun LyricLine.flowCharacterPosition( + currentPositionMs: Long, + nextLineTimeMs: Long?, + characters: List +): Float? { + if (!hasWords || characters.isEmpty()) return null + + val anchors = buildLyricAnchors(characters) + if (anchors.isEmpty()) return null + + if (currentPositionMs <= anchors.first().timeMs) return anchors.first().position + + val nextAnchorIndex = anchors.indexOfFirst { it.timeMs > currentPositionMs } + if (nextAnchorIndex > 0) { + return interpolatePosition( + start = anchors[nextAnchorIndex - 1], + end = anchors[nextAnchorIndex], + currentPositionMs = currentPositionMs + ) + } + + val lastAnchor = anchors.last() + val endTimeMs = nextLineTimeMs + ?.takeIf { it > lastAnchor.timeMs } + ?: estimateLineEndMs() + return interpolatePosition( + start = lastAnchor, + end = LyricAnchor( + timeMs = endTimeMs, + position = (characters.lastIndex + 1).toFloat() + ), + currentPositionMs = currentPositionMs + ) +} + +private fun LyricLine.estimateLineEndMs(): Long { + val lastWordMs = words.last().timeMs + val previousWordMs = words.getOrNull(words.lastIndex - 1)?.timeMs + val tailMs = previousWordMs + ?.let { (lastWordMs - it).coerceAtLeast(MinLineTailDurationMs) } + ?: DefaultLineTailDurationMs + return lastWordMs + tailMs +} + +private fun LyricLine.buildLyricAnchors(characters: List): List { + return words.mapIndexedNotNull { wordIndex, word -> + characters.indexOfFirst { it.wordIndex == wordIndex } + .takeIf { it >= 0 } + ?.let { charIndex -> + LyricAnchor( + timeMs = word.timeMs, + position = charIndex.toFloat() + ) + } + }.distinctBy { it.position } +} + +private data class LyricAnchor( + val timeMs: Long, + val position: Float +) + +private fun interpolatePosition( + start: LyricAnchor, + end: LyricAnchor, + currentPositionMs: Long +): Float { + val durationMs = (end.timeMs - start.timeMs).coerceAtLeast(1L) + val progress = ((currentPositionMs - start.timeMs).toFloat() / durationMs).coerceIn(0f, 1f) + return start.position + (end.position - start.position) * progress +} + +private fun String.toLyricCharacters(): List { + return codePoints() + .toArray() + .map { String(Character.toChars(it)) } +} + +private const val DefaultLineTailDurationMs = 650L +private const val MinLineTailDurationMs = 260L + +internal fun lyricLineVisualSpec( + compact: Boolean, + isCurrent: Boolean, + distanceFromCurrent: Int +): LyricLineVisualSpec { + return when { + compact -> LyricLineVisualSpec( + fontSizeSp = 16, + lineHeightSp = 24, + fontWeight = FontWeight.SemiBold, + color = LyricColors.compactText, + backgroundCenterColor = LyricColors.compactChromeCenter, + backgroundEdgeColor = LyricColors.compactChromeEdge + ) + + isCurrent -> LyricLineVisualSpec( + fontSizeSp = 25, + lineHeightSp = 36, + fontWeight = FontWeight.SemiBold, + color = Color.White + ) + + distanceFromCurrent <= 1 -> LyricLineVisualSpec( + fontSizeSp = 18, + lineHeightSp = 29, + fontWeight = FontWeight.Medium, + color = LyricColors.nearText + ) + + else -> LyricLineVisualSpec( + fontSizeSp = 15, + lineHeightSp = 25, + fontWeight = FontWeight.Normal, + color = LyricColors.dimmedText + ) + } +} + +@Composable +private fun EmptyLyricPlaceholder(modifier: Modifier = Modifier) { + Box( + modifier = modifier.fillMaxSize(), + contentAlignment = Alignment.Center + ) { + Text( + text = "暂无歌词", + color = LyricColors.dimmedText, + fontSize = 15.sp + ) + } +} + +internal object LyricColors { + val actionBlue = Color(0xFF2997FF).copy(alpha = 0.92f) + val compactAccent = Color(0xFF2997FF).copy(alpha = 0.78f) + val compactText = Color.White.copy(alpha = 0.70f) + val compactChromeCenter = Color.White.copy(alpha = 0.065f) + val compactChromeEdge = Color.White.copy(alpha = 0.018f) + val nearText = Color.White.copy(alpha = 0.54f) + val dimmedText = Color(0xFFCCCCCC).copy(alpha = 0.30f) +} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 3b5243d..5ae4f4f 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1,6 +1,6 @@ # AudioVibe 架构全景图 -> 更新于 2026-05-22 | 基于当前未提交代码的文字说明同步,图表未重新生成 +> 更新于 2026-05-24 | 基于当前未提交代码的文字说明同步,图表未重新生成 --- @@ -105,14 +105,15 @@ app/src/main/java/com/audio/vibe/ │ │ └── LazyPlaybackControllerProvider.kt # 播放控制器懒加载 │ │ │ ├── player/ -│ │ ├── PlayerScreen.kt # 完整播放页 + 进度拖动 + 模式/队列入口 -│ │ ├── PlayerViewModel.kt # PlaybackState -> PlayerUiState -│ │ ├── PlayerUiState.kt # 播放页 UI 状态模型 +│ │ ├── PlayerScreen.kt # 完整播放页 + 进度拖动 + 模式/队列/歌词入口 +│ │ ├── PlayerViewModel.kt # PlaybackState -> PlayerUiState + 歌词加载 +│ │ ├── PlayerUiState.kt # 播放页 UI 状态模型 + 歌词状态 │ │ ├── MiniPlayerBar.kt # 音乐管理页底部迷你播放条 │ │ ├── MiniPlayerState.kt # 迷你播放条状态映射 │ │ ├── PlayerQueueSheet.kt # 当前队列弹窗 │ │ ├── PlayerBottomSheet.kt # 播放链路/参数弹窗 -│ │ └── CoverImageLoader.kt # 封面加载与占位 +│ │ ├── CoverImageLoader.kt # 封面加载与占位 +│ │ └── lyrics/ # LRC/逐字歌词解析、加载和显示 │ │ │ ├── editor/ │ │ └── TagEditorScreen.kt # (Demo) 标签编辑 @@ -142,7 +143,7 @@ app/src/main/java/com/audio/vibe/ │ ├── repository/ │ │ ├── MediaStoreMusicScannerRepository.kt # 核心仓库实现 (~1560行) │ │ ├── MusicScannerRepositoryProvider.kt # 单例提供者 -│ │ ├── StoragePathResolver.kt # 路径标准化 +│ │ ├── StoragePathResolver.kt # 路径标准化 + 文件候选解析 │ │ └── AudioScanFingerprint.kt # 增量扫描指纹 │ │ │ └── playback/ @@ -153,7 +154,7 @@ app/src/main/java/com/audio/vibe/ │ └── common/ └── text/ - └── MetadataTextRepair.kt # 元数据乱码修复 (多编码探测+评分) + └── MetadataTextRepair.kt # 元数据/歌词乱码修复 (多编码探测+语言加权评分) ``` --- diff --git a/docs/CODEX_HANDOFF.md b/docs/CODEX_HANDOFF.md index 61aced1..1a8b042 100644 --- a/docs/CODEX_HANDOFF.md +++ b/docs/CODEX_HANDOFF.md @@ -1,6 +1,6 @@ # Codex 交接摘要 -最后更新:2026-05-22 +最后更新:2026-05-24 新开 Codex 会话时,优先把这个文件作为短上下文。 @@ -20,7 +20,8 @@ AudioVibe Android App。技术栈是 Kotlin + Compose + MVVM + Flow + Room/Pagin - `PlaybackTrack` 是通过 id 查询的轻量播放投影。 - `AudioPlaybackService` 持有唯一的 `AudioPlaybackController`。 - UI 只能通过 `PlaybackServiceController` 调用播放能力。 -- `ui/player` 已有完整播放页、当前队列弹窗、播放链路弹窗和迷你播放条。 +- `ui/player` 已有完整播放页、当前队列弹窗、播放链路弹窗、歌词显示和迷你播放条。 +- `ui/player/lyrics` 负责外置/内嵌歌词加载、LRC/逐字歌词解析和歌词 UI;歌词文本读取复用 `MetadataTextRepair` 的按字节乱码修复。 - 播放模式包括列表循环、顺序列表、单曲循环和随机播放;随机播放时当前列表 UI 应显示真实随机队列。 - 通知栏使用 MediaStyle,紧凑区 3 个按钮:上一曲、播放/暂停、下一曲。 @@ -35,6 +36,8 @@ AudioVibe Android App。技术栈是 Kotlin + Compose + MVVM + Flow + Room/Pagin - 自然切曲应参考手动切曲路径,避免先发布 `ENDED/isPlaying=false` 的 UI 中间态。 - 播放错误信息用 Toast 短暂提示,不要在播放页常驻展示错误条。 - 进度条拖动时,UI 层可以保持按钮显示稳定,但不要为了 UI 闪动修改播放 controller 的真实状态语义。 +- 歌词加载必须按当前歌曲异步更新,并丢弃旧歌曲的过期结果;切曲时不要先闪“无歌词”。 +- 歌词乱码修复应传入当前 App 语言环境,让中文、日文、韩文、俄文等候选编码按语言加权。 - 清空曲库前必须等待旧扫描任务真正取消。 - 通知栏不要因为播放进度 tick 每秒刷新。 - 不要对所有普通文件都跑 FFprobe,只有必要时再用。 @@ -60,6 +63,10 @@ AudioVibe Android App。技术栈是 Kotlin + Compose + MVVM + Flow + Room/Pagin - `app/src/main/java/com/audio/vibe/ui/player/PlayerScreen.kt` - `app/src/main/java/com/audio/vibe/ui/player/PlayerViewModel.kt` - `app/src/main/java/com/audio/vibe/ui/player/MiniPlayerBar.kt` +- `app/src/main/java/com/audio/vibe/ui/player/lyrics/LyricLoader.kt` +- `app/src/main/java/com/audio/vibe/ui/player/lyrics/LyricParser.kt` +- `app/src/main/java/com/audio/vibe/ui/player/lyrics/LyricView.kt` +- `app/src/main/java/com/audio/vibe/common/text/MetadataTextRepair.kt` ## 当前验证命令 diff --git a/docs/MUSIC_SCAN_FLOW.md b/docs/MUSIC_SCAN_FLOW.md index c6b638e..3b94e34 100644 --- a/docs/MUSIC_SCAN_FLOW.md +++ b/docs/MUSIC_SCAN_FLOW.md @@ -1,6 +1,6 @@ # 音乐扫描流程 -最后更新:2026-05-22 +最后更新:2026-05-24 ## 入口 @@ -71,7 +71,7 @@ UI 应该在扫描过程中继续展示已有音乐库。扫描进度和分页 - DSD128:5644800 - DSD256:11289600 - DSD512:22579200 -5. 元数据文本经过 `MetadataTextRepair` 修复,重点覆盖日语、韩语、俄语和 Google Play 常见国家语言。 +5. 元数据文本经过 `MetadataTextRepair` 修复,重点覆盖中文、日语、韩语、俄语和 Google Play 常见国家语言;文本候选评分应参考当前语言环境,避免把正确中文误判成其他可解码字符集。 ## 能力标识 @@ -117,4 +117,5 @@ UI 应该在扫描过程中继续展示已有音乐库。扫描进度和分页 - SAF 遍历 SD 卡或 U 盘时可能较慢,并发数需要受控。 - 过多并行 FFmpeg 任务会影响存储、CPU 和电量。 - MediaStore 与 SAF 的路径规范化必须保持一致。 +- `StoragePathResolver` 已被播放和歌词读取复用,调整 sourcePath 规则时要同时验证 MediaStore、SAF、SD 卡、U 盘和真实文件路径候选。 - DAO 写入策略变化时,需要重新确认 FTS 是否保持同步。 diff --git a/docs/PLAYBACK_FLOW.md b/docs/PLAYBACK_FLOW.md index ccc8222..22bb7ec 100644 --- a/docs/PLAYBACK_FLOW.md +++ b/docs/PLAYBACK_FLOW.md @@ -1,6 +1,6 @@ # 播放流程 -最后更新:2026-05-22 +最后更新:2026-05-24 ## 当前方向 @@ -157,10 +157,16 @@ FFmpeg 链路: - `MiniPlayerBar.kt` - `PlayerViewModel.kt` - `MiniPlayerState.kt` +- `ui/player/lyrics/*` 重要行为: - 播放页展示封面、歌曲名、歌手、专辑、播放进度、播放模式、当前队列、解码方式和播放链路。 +- 播放页支持歌词占位、紧凑歌词和全屏歌词;点击歌词区域进入全屏,全屏只保留返回入口和歌词主体。 +- 歌词加载由 `PlayerViewModel` 按当前歌曲异步触发,使用 generation 丢弃过期结果,切曲期间不应短暂闪出“无歌词”。 +- 歌词来源优先查找同目录外置 `.lrc/.LRC`,包括真实文件路径、SAF Document sibling 和 MediaStore sibling;找不到时尝试读取内嵌歌词。 +- 歌词文本读取必须按字节进入 `MetadataTextRepair.repairBytes(...)`,不能直接 `readText()`;乱码修复根据当前 App 语言环境加权,中文环境优先中文编码,日文/韩文/俄文环境分别偏向对应编码和字符块。 +- 支持普通 LRC 行级时间和 `word` 逐字时间;逐字歌词当前按歌词文件时间线推进高亮,已播放字符保持亮色。 - 歌曲名、歌手名和封面区域需要保持稳定占位,切曲时不能因为占位图或文本高度变化造成页面跳动。 - 歌曲名、歌手名在播放页和迷你播放条中显示不全时使用走马灯。 - 进度条支持拖动 seek;拖动过程中 UI 进度不受后台播放进度覆盖,松手后 seek 到目标位置。 @@ -168,6 +174,15 @@ FFmpeg 链路: - 播放失败信息通过 Toast 短暂提示,不在播放页常驻展示错误条。 - 解码参数加载前保留上一帧参数,避免播放链路信息闪为空或短暂闪成错误链路。 +## 文件访问兜底 + +播放和歌词读取都需要兼容内置存储、SD 卡、U 盘和 SAF 文档 URI。 + +- `StoragePathResolver` 负责把数据库里的 `sourcePath` 拆成 volume 和 relative path,并生成可能的真实文件候选。 +- FFmpeg 播放 content URI 时优先尝试 `openFileDescriptor` + `/proc/self/fd`,避免 `FFmpegKitConfig.getSafParameterForRead()` 遇到部分 SAF tree/document 组合抛 `SecurityException`。 +- 如果原始 content URI 无法打开,会按 `sourcePath` 反查 MediaStore URI,再尝试真实文件路径候选,最后才回退到 FFmpegKit SAF 参数。 +- Media3 遇到 SAF `SecurityException` 或设备不支持的 AudioTrack runtime check 时允许进入 FFmpeg fallback。 + ## 已知风险 - FFmpeg PCM 链路当前使用 AudioTrack,不是 Oboe。 diff --git a/docs/PROJECT_CONTEXT.md b/docs/PROJECT_CONTEXT.md index 7f57fca..25e9728 100644 --- a/docs/PROJECT_CONTEXT.md +++ b/docs/PROJECT_CONTEXT.md @@ -1,6 +1,6 @@ # AudioVibe 项目上下文 -最后更新:2026-05-22 +最后更新:2026-05-24 ## 产品定位 @@ -23,7 +23,7 @@ AudioVibe 是面向海外用户的 Android 音频编辑与变声 App。当前重 ## 主要模块 - `common/text` - - `MetadataTextRepair.kt`:修复歌曲标题、歌手、专辑等元数据乱码。 + - `MetadataTextRepair.kt`:修复歌曲标题、歌手、专辑、歌词等文本乱码;支持按字节多编码探测,并根据当前语言环境做候选加权。 - `data/local` - `MusicLibraryDatabase.kt`:Room 数据库、`MusicTrackEntity`、FTS 表、DAO 查询、PagingSource、播放投影、实体映射。 @@ -31,7 +31,7 @@ AudioVibe 是面向海外用户的 Android 音频编辑与变声 App。当前重 - `data/repository` - `MediaStoreMusicScannerRepository.kt`:音乐扫描、MediaStore 扫描、SAF 文件夹扫描、歌曲信息解析、能力标识、Room 写入。 - - `StoragePathResolver.kt`:统一解析内置存储、SD 卡、U 盘等路径。 + - `StoragePathResolver.kt`:统一解析内置存储、SD 卡、U 盘等路径,并为播放/歌词读取提供真实文件候选。 - `AudioScanFingerprint.kt`:判断文件是否需要重新扫描的纯函数。 - `MusicScannerRepositoryProvider.kt`:音乐库仓库单例入口。 @@ -56,10 +56,11 @@ AudioVibe 是面向海外用户的 Android 音频编辑与变声 App。当前重 - `LazyPlaybackControllerProvider.kt`:只有真正播放时才启动并绑定播放服务。 - `ui/player` - - `PlayerScreen.kt`:完整播放页,包含封面、播放控制、可拖动进度条、播放模式、当前队列入口和播放链路入口。 - - `PlayerViewModel.kt`:把 `PlaybackState` 映射为播放页 UI 状态,并转发播放控制事件。 + - `PlayerScreen.kt`:完整播放页,包含封面、播放控制、可拖动进度条、播放模式、当前队列入口、播放链路入口和歌词显示。 + - `PlayerViewModel.kt`:把 `PlaybackState` 映射为播放页 UI 状态,转发播放控制事件,并按当前歌曲异步加载歌词。 - `MiniPlayerBar.kt` / `MiniPlayerState.kt`:音乐管理页底部迷你播放条和状态映射。 - `PlayerQueueSheet.kt` / `PlayerBottomSheet.kt`:当前队列弹窗和播放链路弹窗。 + - `lyrics/`:LRC 外置/内嵌歌词加载、行级/逐字歌词解析和歌词 UI。 ## 当前数据模型方向 @@ -80,6 +81,8 @@ AudioVibe 是面向海外用户的 Android 音频编辑与变声 App。当前重 - 播放应通过服务和通知栏延续,不应因为退出音乐管理页就停止。 - 播放错误在 UI 上用 Toast 短暂提示,不在播放页常驻展示错误条。 - 播放页当前队列应跟真实播放顺序一致,随机播放时显示随机队列。 +- 播放页歌词区域保持稳定占位;有歌词时可进入全屏歌词,切曲时只有确认无歌词后才展示空歌词状态。 +- 外置歌词读取需兼容真实路径、SAF Document sibling 和 MediaStore sibling,文本按字节修复编码,不能依赖平台默认字符集。 ## 重要约束 @@ -103,6 +106,7 @@ AudioVibe 是面向海外用户的 Android 音频编辑与变声 App。当前重 近期重点测试覆盖: - 歌曲信息乱码修复 +- 歌词乱码修复、LRC 解析和逐字歌词高亮 - 音频格式能力标识 - 播放状态和系统状态映射 - 播放服务懒绑定 diff --git a/docs/REVIEW_CHECKLIST.md b/docs/REVIEW_CHECKLIST.md index 547ef4a..171084a 100644 --- a/docs/REVIEW_CHECKLIST.md +++ b/docs/REVIEW_CHECKLIST.md @@ -1,6 +1,6 @@ # Review 检查清单 -最后更新:2026-05-22 +最后更新:2026-05-24 检查扫描、播放、Room 或音乐管理相关改动时使用此清单。 @@ -15,7 +15,8 @@ - 歌曲信息解析失败不会直接让受支持格式变成不可播放。 - DSD 位深按 `1-bit DSD` 处理。 - DSD 采样率能映射到真实 DSD 采样率。 -- 乱码修复覆盖日语、韩语、俄语和 Google Play 常见语言样本。 +- 乱码修复覆盖中文、日语、韩语、俄语和 Google Play 常见语言样本,并按当前 App/系统语言给对应候选编码加权。 +- `StoragePathResolver` 的 sourcePath 拆分和真实文件候选会影响扫描、播放和歌词读取,改动时需要三处一起验证。 ## Room / Paging / FTS @@ -67,3 +68,6 @@ - 播放页和迷你播放条的长歌曲名/歌手名使用走马灯或稳定占位,切曲不应导致布局跳动。 - 播放错误信息使用 Toast 短暂提示,不在播放页常驻展示错误条。 - 进度条拖动时,拖动中的显示进度不被后台进度覆盖;松手后按钮显示稳定,不通过修改播放层真实状态来遮蔽 UI 闪动。 +- 歌词区域保持稳定占位;切曲时旧歌词不能错误落到新歌曲,也不能在新歌词加载前闪出“无歌词”。 +- 外置歌词读取覆盖真实文件、SAF Document sibling、MediaStore sibling;文本读取按字节修复编码,不使用默认 `readText()`。 +- 逐字歌词高亮按歌词文件时间线推进,已播放字符保持亮色,普通 LRC 行级歌词仍能正常显示。 diff --git a/docs/海外音频编辑+变声App PRD(产品需求文档).md b/docs/海外音频编辑+变声App PRD(产品需求文档).md index 4c23f39..ca03465 100644 --- a/docs/海外音频编辑+变声App PRD(产品需求文档).md +++ b/docs/海外音频编辑+变声App PRD(产品需求文档).md @@ -159,7 +159,7 @@ AI轻量化:本地AI变声(低延迟、保护隐私)+ 本地多格式播 底部播放条:音乐管理页底部固定展示迷你播放条,显示封面缩略图、歌曲名、歌手、播放/暂停按钮和基础进度;没有当前歌曲时隐藏;只要播放服务仍有当前歌曲,不论播放或暂停,退出音乐管理页后再次进入都应恢复展示;点击播放条进入完整播放页 -完整播放页:播放页展示大封面、歌曲名、歌手、专辑、格式、采样率、位深、码率、时长、播放链路(Media3 直出、Media3 系统解码、FFmpeg PCM 兜底、重采样/位深转换等);支持进度拖动、播放/暂停、上一曲、下一曲、播放模式切换和当前队列弹窗;播放失败时使用短暂 Toast 提示失败原因,不在页面中常驻错误条 +完整播放页:播放页展示大封面、歌曲名、歌手、专辑、格式、采样率、位深、码率、时长、播放链路(Media3 直出、Media3 系统解码、FFmpeg PCM 兜底、重采样/位深转换等);支持进度拖动、播放/暂停、上一曲、下一曲、播放模式切换、当前队列弹窗和歌词显示;歌词支持外置 LRC 与内嵌歌词,需兼容普通行级歌词和逐字歌词,歌词乱码修复应参考当前 App 语言环境;播放失败时使用短暂 Toast 提示失败原因,不在页面中常驻错误条 通知栏与锁屏控制:播放时需要显示系统媒体通知,包含封面、歌曲名、歌手,以及上一曲、播放/暂停、下一曲三个核心控制按钮;必要时可通过删除通知或系统入口停止播放;通知栏、锁屏媒体控件、底部播放条和完整播放页必须共享同一播放状态;Android 13+ 需适配通知权限,Android 8.0+ 需使用前台服务通知渠道,用户拒绝通知权限时仍允许前台播放页控制,但后台播放能力需给出清晰提示