完善歌曲解析和播放链路,补充说明知识库文档
113
CLAUDE.md
@ -1,6 +1,91 @@
|
||||
# 超级能力设定
|
||||
你是资深 Android 高级开发工程师,精通 Kotlin、Jetpack Compose 现代开发。
|
||||
你拥有权限:
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## Project Overview
|
||||
|
||||
AudioVibe is an Android audio editing and voice changer app targeting international markets. Built with Kotlin and Jetpack Compose, it provides audio tag editing, voice changing, audio cutting, and a music library manager with support for 100+ audio formats.
|
||||
|
||||
## Build & Test Commands
|
||||
|
||||
```bash
|
||||
# Build the project
|
||||
./gradlew assembleDebug
|
||||
|
||||
# Run all unit tests (JVM, no device needed)
|
||||
./gradlew test
|
||||
|
||||
# Run a single test class
|
||||
./gradlew test --tests "com.audio.vibe.data.repository.MediaStoreMusicSelectionTest"
|
||||
|
||||
# Run a single test method
|
||||
./gradlew test --tests "com.audio.vibe.data.repository.AudioScanFingerprintTest.someMethod"
|
||||
|
||||
# Run instrumented tests (requires connected device/emulator)
|
||||
./gradlew connectedAndroidTest
|
||||
|
||||
# Run lint checks
|
||||
./gradlew lint
|
||||
|
||||
# Clean build
|
||||
./gradlew clean assembleDebug
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
Single-module project (`app/`) following MVVM with clean architecture layers:
|
||||
|
||||
```
|
||||
ui/ — Compose screens & ViewModels (state: sealed interface + @Immutable data class)
|
||||
domain/ — Models (ScannedAudioTrack, PlaybackTrack) + repository interfaces
|
||||
data/ — Repository impls, Room DB, ExoPlayer/FFmpeg playback, DataStore preferences
|
||||
common/ — Shared utilities (MetadataTextRepair, etc.)
|
||||
```
|
||||
|
||||
### Key Layers
|
||||
|
||||
**Navigation** (`MainActivity.kt`): Single-Activity, NavHost-based routing with 6 destinations: home, editor, voice, cutter, music, settings, premium.
|
||||
|
||||
**i18n** (`ui/i18n/AppLanguage.kt`): 23 languages via Android string resources. `AppStrings` data class holds all translatable strings, provided through `CompositionLocal`. Language selection persisted in DataStore (`LanguagePreferences`).
|
||||
|
||||
**Music Scanner** (`data/repository/MediaStoreMusicScannerRepository.kt`):
|
||||
- Scans via MediaStore API (Android 10+) and SAF `OpenDocumentTree` for external storage
|
||||
- Dual-metadata pipeline: jaudiotagger for common formats, FFprobe for exotic formats (WV, APE, DSD, etc.) with automatic fallback merging
|
||||
- Producer-worker-collector coroutine pattern with configurable parallelism for metadata parsing
|
||||
- Room FTS4 for full-text search with prefix-matching
|
||||
- Fingerprint-based incremental scanning (size + dateModified comparison)
|
||||
|
||||
**Room Database** (`data/local/MusicLibraryDatabase.kt`):
|
||||
- `music_tracks` table indexed by source_path (unique), title, artist, album, format, date_modified
|
||||
- `music_tracks_fts` FTS4 virtual table for searching
|
||||
- Paging 3 integration via `PagingSource` DAO methods
|
||||
- `fallbackToDestructiveMigration(true)` — schema at version 3
|
||||
|
||||
**Playback** (`data/playback/`):
|
||||
- `AudioPlaybackService` — foreground service for background playback
|
||||
- `AudioPlaybackController` — dual-backend: Media3 ExoPlayer (primary) + FFmpeg PCM → AudioTrack (fallback for exotic formats, 8/24/64-bit PCM, non-standard sample rates)
|
||||
- `PlaybackServiceController` interface decouples ViewModel from the service
|
||||
|
||||
**State Management**: ViewModel exposes `StateFlow<UiState>`, UI collects via `collectAsState()`. Events dispatched through sealed interface `MusicManagerEvent`. Unidirectional data flow strictly enforced.
|
||||
|
||||
### Tech Stack
|
||||
|
||||
| Component | Library |
|
||||
|-----------|---------|
|
||||
| UI | Jetpack Compose + Material 3 (BOM 2026.02.01) |
|
||||
| Navigation | Navigation Compose 2.9.8 |
|
||||
| Database | Room 2.8.3 + KSP |
|
||||
| Paging | Paging 3 + Paging Compose |
|
||||
| Preferences | DataStore Preferences |
|
||||
| Playback | Media3 ExoPlayer 1.10.0 |
|
||||
| FFmpeg | ffmpeg-kit-min 6.0.1 |
|
||||
| Metadata | jaudiotagger 3.0.1 |
|
||||
| Logging | Timber 5.0.1 |
|
||||
| Min SDK / Target SDK | 26 / 36 |
|
||||
| Kotlin / AGP | 2.2.10 / 9.1.1 |
|
||||
|
||||
## Coding Rules
|
||||
|
||||
1. 输出生产级高质量代码,严格遵循官方 MVVM 干净架构。
|
||||
2. 强制使用协程、Flow、StateFlow,全程禁止使用 LiveData。
|
||||
3. 严格遵守 Compose 状态提升、UiState 不可变、密封类管理页面状态。
|
||||
@ -10,18 +95,10 @@
|
||||
7. 统一编码风格与命名规范,只允许使用 Timber 日志,禁用原生 Log。
|
||||
8. 禁止使用废弃 API,全程纯 Compose,不生成 XML 布局。
|
||||
9. 遵循最小改动原则,不擅自大规模重构原有项目结构和代码风格。
|
||||
|
||||
# Android 项目开发规范
|
||||
## 目录结构
|
||||
ui(页面/组件)、feature(业务)、domain(模型/用例)、data(仓库/远程/本地)、di、common(工具扩展)
|
||||
|
||||
## 编码补充规则
|
||||
1. 单向数据流:UI → 事件 → ViewModel → 状态 → UI
|
||||
2. ViewModel 不持有 Context、不直接操作视图
|
||||
3. 仓库为唯一数据源,UI 不直连网络/数据库
|
||||
4. 耗时操作统一 Dispatchers.IO,使用 viewModelScope
|
||||
5. 严格空安全,禁止滥用 !!
|
||||
6. 禁止硬编码文字、尺寸、颜色,统一引用资源
|
||||
|
||||
## AI 生成约束
|
||||
遵循现有代码风格,最小改动不随意大重构;只用稳定新API,复用已有工具类和组件。
|
||||
10. 单向数据流:UI → 事件 → ViewModel → 状态 → UI
|
||||
11. ViewModel 不持有 Context、不直接操作视图
|
||||
12. 仓库为唯一数据源,UI 不直连网络/数据库
|
||||
13. 耗时操作统一 Dispatchers.IO,使用 viewModelScope
|
||||
14. 严格空安全,禁止滥用 !!
|
||||
15. 禁止硬编码文字、尺寸、颜色,统一引用资源
|
||||
16. 所有对话中文回答,遵循现有代码风格
|
||||
|
||||
@ -15,7 +15,7 @@ android {
|
||||
versionCode = 1
|
||||
versionName = "1.0"
|
||||
|
||||
// testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
|
||||
}
|
||||
|
||||
@ -34,6 +34,7 @@ android {
|
||||
|
||||
}
|
||||
buildFeatures {
|
||||
buildConfig = true
|
||||
compose = true
|
||||
}
|
||||
}
|
||||
@ -64,6 +65,8 @@ dependencies {
|
||||
implementation(libs.androidx.paging.compose)
|
||||
implementation(libs.jaudiotagger)
|
||||
implementation(libs.ffmpeg.kit.min)
|
||||
implementation(libs.androidx.media3.exoplayer)
|
||||
implementation(libs.timber)
|
||||
ksp(libs.androidx.room.compiler)
|
||||
testImplementation(libs.junit)
|
||||
androidTestImplementation(platform(libs.androidx.compose.bom))
|
||||
|
||||
@ -6,8 +6,12 @@
|
||||
android:name="android.permission.READ_EXTERNAL_STORAGE"
|
||||
android:maxSdkVersion="32" />
|
||||
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
|
||||
|
||||
<application
|
||||
android:name=".AudioVibeApp"
|
||||
android:allowBackup="true"
|
||||
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||
android:fullBackupContent="@xml/backup_rules"
|
||||
@ -18,6 +22,12 @@
|
||||
android:testOnly="false"
|
||||
android:theme="@style/Theme.AudioVibe"
|
||||
tools:ignore="GoogleAppIndexingWarning">
|
||||
<service
|
||||
android:name=".data.playback.AudioPlaybackService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="mediaPlayback"
|
||||
android:stopWithTask="true" />
|
||||
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
|
||||
@ -1,9 +1,20 @@
|
||||
package com.audio.vibe
|
||||
|
||||
import android.app.Application
|
||||
import com.arthenica.ffmpegkit.FFmpegKitConfig
|
||||
import com.arthenica.ffmpegkit.Level
|
||||
import com.arthenica.ffmpegkit.LogRedirectionStrategy
|
||||
import java.util.logging.Level as JavaLogLevel
|
||||
import java.util.logging.Logger
|
||||
|
||||
class AudioVibeApp : Application() {
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
Logger.getLogger("org.jaudiotagger").apply {
|
||||
level = JavaLogLevel.OFF
|
||||
useParentHandlers = false
|
||||
}
|
||||
FFmpegKitConfig.setLogLevel(Level.AV_LOG_QUIET)
|
||||
FFmpegKitConfig.setLogRedirectionStrategy(LogRedirectionStrategy.NEVER_PRINT_LOGS)
|
||||
}
|
||||
}
|
||||
|
||||
@ -4,6 +4,7 @@ import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import com.audio.vibe.BuildConfig
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
@ -33,10 +34,14 @@ import com.audio.vibe.ui.settings.SettingsScreen
|
||||
import com.audio.vibe.ui.theme.AudioVibeTheme
|
||||
import com.audio.vibe.ui.voicechanger.VoiceChangerScreen
|
||||
import kotlinx.coroutines.launch
|
||||
import timber.log.Timber
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
if (BuildConfig.DEBUG && Timber.treeCount == 0) {
|
||||
Timber.plant(Timber.DebugTree())
|
||||
}
|
||||
enableEdgeToEdge()
|
||||
setContent {
|
||||
AudioVibeTheme {
|
||||
|
||||
@ -16,11 +16,12 @@ import androidx.room.Room
|
||||
import androidx.room.RoomDatabase
|
||||
import androidx.room.Transaction
|
||||
import androidx.room.Upsert
|
||||
import com.audio.vibe.domain.model.PlaybackTrack
|
||||
import com.audio.vibe.domain.model.ScannedAudioTrack
|
||||
|
||||
@Database(
|
||||
entities = [MusicTrackEntity::class, MusicTrackFtsEntity::class],
|
||||
version = 2,
|
||||
version = 3,
|
||||
exportSchema = false
|
||||
)
|
||||
abstract class MusicLibraryDatabase : RoomDatabase() {
|
||||
@ -73,6 +74,24 @@ interface MusicTrackDao {
|
||||
)
|
||||
fun searchPagedByTrack(query: String): PagingSource<Int, MusicTrackEntity>
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT id FROM music_tracks
|
||||
ORDER BY title COLLATE NOCASE ASC
|
||||
"""
|
||||
)
|
||||
suspend fun playbackIdsByTrack(): List<Long>
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT music_tracks.id FROM music_tracks
|
||||
INNER JOIN music_tracks_fts ON music_tracks.source_path = music_tracks_fts.source_path
|
||||
WHERE music_tracks_fts MATCH :query
|
||||
ORDER BY music_tracks.title COLLATE NOCASE ASC
|
||||
"""
|
||||
)
|
||||
suspend fun searchPlaybackIdsByTrack(query: String): List<Long>
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT * FROM music_tracks
|
||||
@ -91,6 +110,24 @@ interface MusicTrackDao {
|
||||
)
|
||||
fun searchPagedByAlbum(query: String): PagingSource<Int, MusicTrackEntity>
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT id FROM music_tracks
|
||||
ORDER BY album COLLATE NOCASE ASC, title COLLATE NOCASE ASC
|
||||
"""
|
||||
)
|
||||
suspend fun playbackIdsByAlbum(): List<Long>
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT music_tracks.id FROM music_tracks
|
||||
INNER JOIN music_tracks_fts ON music_tracks.source_path = music_tracks_fts.source_path
|
||||
WHERE music_tracks_fts MATCH :query
|
||||
ORDER BY music_tracks.album COLLATE NOCASE ASC, music_tracks.title COLLATE NOCASE ASC
|
||||
"""
|
||||
)
|
||||
suspend fun searchPlaybackIdsByAlbum(query: String): List<Long>
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT * FROM music_tracks
|
||||
@ -109,6 +146,24 @@ interface MusicTrackDao {
|
||||
)
|
||||
fun searchPagedByArtist(query: String): PagingSource<Int, MusicTrackEntity>
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT id FROM music_tracks
|
||||
ORDER BY artist COLLATE NOCASE ASC, title COLLATE NOCASE ASC
|
||||
"""
|
||||
)
|
||||
suspend fun playbackIdsByArtist(): List<Long>
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT music_tracks.id FROM music_tracks
|
||||
INNER JOIN music_tracks_fts ON music_tracks.source_path = music_tracks_fts.source_path
|
||||
WHERE music_tracks_fts MATCH :query
|
||||
ORDER BY music_tracks.artist COLLATE NOCASE ASC, music_tracks.title COLLATE NOCASE ASC
|
||||
"""
|
||||
)
|
||||
suspend fun searchPlaybackIdsByArtist(query: String): List<Long>
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT * FROM music_tracks
|
||||
@ -127,6 +182,24 @@ interface MusicTrackDao {
|
||||
)
|
||||
fun searchPagedByRecent(query: String): PagingSource<Int, MusicTrackEntity>
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT id FROM music_tracks
|
||||
ORDER BY date_modified_seconds DESC, title COLLATE NOCASE ASC
|
||||
"""
|
||||
)
|
||||
suspend fun playbackIdsByRecent(): List<Long>
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT music_tracks.id FROM music_tracks
|
||||
INNER JOIN music_tracks_fts ON music_tracks.source_path = music_tracks_fts.source_path
|
||||
WHERE music_tracks_fts MATCH :query
|
||||
ORDER BY music_tracks.date_modified_seconds DESC, music_tracks.title COLLATE NOCASE ASC
|
||||
"""
|
||||
)
|
||||
suspend fun searchPlaybackIdsByRecent(query: String): List<Long>
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT * FROM music_tracks
|
||||
@ -145,6 +218,35 @@ interface MusicTrackDao {
|
||||
)
|
||||
fun searchPagedByFormat(query: String): PagingSource<Int, MusicTrackEntity>
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT id FROM music_tracks
|
||||
ORDER BY format COLLATE NOCASE ASC, title COLLATE NOCASE ASC
|
||||
"""
|
||||
)
|
||||
suspend fun playbackIdsByFormat(): List<Long>
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT music_tracks.id FROM music_tracks
|
||||
INNER JOIN music_tracks_fts ON music_tracks.source_path = music_tracks_fts.source_path
|
||||
WHERE music_tracks_fts MATCH :query
|
||||
ORDER BY music_tracks.format COLLATE NOCASE ASC, music_tracks.title COLLATE NOCASE ASC
|
||||
"""
|
||||
)
|
||||
suspend fun searchPlaybackIdsByFormat(query: String): List<Long>
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT id, uri, title, artist, album, mime_type, format, sample_rate_hz, bitrate,
|
||||
bit_depth, duration_ms, source_path, is_playable, requires_ffmpeg, unavailable_reason
|
||||
FROM music_tracks
|
||||
WHERE id = :id
|
||||
LIMIT 1
|
||||
"""
|
||||
)
|
||||
suspend fun playbackTrackById(id: Long): PlaybackTrackEntity?
|
||||
|
||||
@Query("SELECT COUNT(*) FROM music_tracks")
|
||||
suspend fun trackCount(): Int
|
||||
|
||||
@ -196,7 +298,21 @@ interface MusicTrackDao {
|
||||
suspend fun searchFormats(query: String): List<String>
|
||||
|
||||
@Upsert
|
||||
suspend fun upsertTracks(tracks: List<MusicTrackEntity>)
|
||||
suspend fun upsertTracksInternal(tracks: List<MusicTrackEntity>)
|
||||
|
||||
@Transaction
|
||||
suspend fun upsertTracks(tracks: List<MusicTrackEntity>) {
|
||||
if (tracks.isEmpty()) return
|
||||
val existingTracks = tracksBySourcePaths(tracks.map { it.sourcePath })
|
||||
.associateBy { it.sourcePath }
|
||||
upsertTracksInternal(
|
||||
tracks.map { track ->
|
||||
existingTracks[track.sourcePath]?.let { existing ->
|
||||
track.copy(id = existing.id)
|
||||
} ?: track
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@Query("DELETE FROM music_tracks")
|
||||
suspend fun clearTracks()
|
||||
@ -210,6 +326,7 @@ interface MusicTrackDao {
|
||||
@Entity(
|
||||
tableName = "music_tracks",
|
||||
indices = [
|
||||
Index(value = ["source_path"], unique = true),
|
||||
Index(value = ["title"]),
|
||||
Index(value = ["artist"]),
|
||||
Index(value = ["album"]),
|
||||
@ -218,7 +335,8 @@ interface MusicTrackDao {
|
||||
]
|
||||
)
|
||||
data class MusicTrackEntity(
|
||||
@PrimaryKey
|
||||
@PrimaryKey(autoGenerate = true)
|
||||
val id: Long = 0L,
|
||||
@ColumnInfo(name = "source_path")
|
||||
val sourcePath: String,
|
||||
val uri: String,
|
||||
@ -234,7 +352,13 @@ data class MusicTrackEntity(
|
||||
val bitrate: Int?,
|
||||
@ColumnInfo(name = "bit_depth") val bitDepth: String?,
|
||||
@ColumnInfo(name = "relative_path") val relativePath: String?,
|
||||
@ColumnInfo(name = "date_modified_seconds") val dateModifiedSeconds: Long
|
||||
@ColumnInfo(name = "date_modified_seconds") val dateModifiedSeconds: Long,
|
||||
@ColumnInfo(name = "is_playable") val isPlayable: Boolean = true,
|
||||
@ColumnInfo(name = "requires_ffmpeg") val requiresFfmpeg: Boolean = false,
|
||||
@ColumnInfo(name = "is_tag_readable") val isTagReadable: Boolean = true,
|
||||
@ColumnInfo(name = "is_tag_writable") val isTagWritable: Boolean = false,
|
||||
@ColumnInfo(name = "unavailable_reason") val unavailableReason: String? = null,
|
||||
@ColumnInfo(name = "parse_failure_reason") val parseFailureReason: String? = null
|
||||
)
|
||||
|
||||
@Fts4(
|
||||
@ -251,9 +375,35 @@ data class MusicTrackFtsEntity(
|
||||
val format: String
|
||||
)
|
||||
|
||||
data class PlaybackTrackEntity(
|
||||
val id: Long,
|
||||
val uri: String,
|
||||
val title: String,
|
||||
val artist: String,
|
||||
val album: String,
|
||||
@ColumnInfo(name = "mime_type")
|
||||
val mimeType: String,
|
||||
val format: String,
|
||||
@ColumnInfo(name = "sample_rate_hz")
|
||||
val sampleRateHz: Int?,
|
||||
val bitrate: Int?,
|
||||
@ColumnInfo(name = "bit_depth")
|
||||
val bitDepth: String?,
|
||||
@ColumnInfo(name = "duration_ms")
|
||||
val durationMs: Long,
|
||||
@ColumnInfo(name = "source_path")
|
||||
val sourcePath: String,
|
||||
@ColumnInfo(name = "is_playable")
|
||||
val isPlayable: Boolean,
|
||||
@ColumnInfo(name = "requires_ffmpeg")
|
||||
val requiresFfmpeg: Boolean,
|
||||
@ColumnInfo(name = "unavailable_reason")
|
||||
val unavailableReason: String?
|
||||
)
|
||||
|
||||
fun MusicTrackEntity.toDomain(): ScannedAudioTrack {
|
||||
return ScannedAudioTrack(
|
||||
id = mediaId,
|
||||
id = id,
|
||||
uri = Uri.parse(uri),
|
||||
title = title,
|
||||
artist = artist,
|
||||
@ -267,12 +417,39 @@ fun MusicTrackEntity.toDomain(): ScannedAudioTrack {
|
||||
bitDepth = bitDepth,
|
||||
relativePath = relativePath,
|
||||
sourcePath = sourcePath,
|
||||
dateModifiedSeconds = dateModifiedSeconds
|
||||
dateModifiedSeconds = dateModifiedSeconds,
|
||||
isPlayable = isPlayable,
|
||||
requiresFfmpeg = requiresFfmpeg,
|
||||
isTagReadable = isTagReadable,
|
||||
isTagWritable = isTagWritable,
|
||||
unavailableReason = unavailableReason,
|
||||
parseFailureReason = parseFailureReason
|
||||
)
|
||||
}
|
||||
|
||||
fun PlaybackTrackEntity.toDomain(): PlaybackTrack {
|
||||
return PlaybackTrack(
|
||||
id = id,
|
||||
uri = Uri.parse(uri),
|
||||
title = title,
|
||||
artist = artist,
|
||||
album = album,
|
||||
mimeType = mimeType,
|
||||
format = format,
|
||||
sampleRateHz = sampleRateHz,
|
||||
bitrate = bitrate,
|
||||
bitDepth = bitDepth,
|
||||
durationMs = durationMs.takeIf { it > 0L },
|
||||
sourcePath = sourcePath,
|
||||
isPlayable = isPlayable,
|
||||
requiresFfmpeg = requiresFfmpeg,
|
||||
unavailableReason = unavailableReason
|
||||
)
|
||||
}
|
||||
|
||||
fun ScannedAudioTrack.toEntity(): MusicTrackEntity {
|
||||
return MusicTrackEntity(
|
||||
id = scannedTrackIdToNewEntityPrimaryKey(id),
|
||||
sourcePath = libraryPath(),
|
||||
uri = uri.toString(),
|
||||
mediaId = id,
|
||||
@ -287,10 +464,18 @@ fun ScannedAudioTrack.toEntity(): MusicTrackEntity {
|
||||
bitrate = bitrate,
|
||||
bitDepth = bitDepth,
|
||||
relativePath = relativePath,
|
||||
dateModifiedSeconds = dateModifiedSeconds
|
||||
dateModifiedSeconds = dateModifiedSeconds,
|
||||
isPlayable = isPlayable,
|
||||
requiresFfmpeg = requiresFfmpeg,
|
||||
isTagReadable = isTagReadable,
|
||||
isTagWritable = isTagWritable,
|
||||
unavailableReason = unavailableReason,
|
||||
parseFailureReason = parseFailureReason
|
||||
)
|
||||
}
|
||||
|
||||
internal fun scannedTrackIdToNewEntityPrimaryKey(scannedTrackId: Long): Long = 0L
|
||||
|
||||
fun ScannedAudioTrack.libraryPath(): String {
|
||||
return sourcePath?.normalizedForKey()
|
||||
?.takeIf { it.isNotBlank() }
|
||||
|
||||
@ -0,0 +1,373 @@
|
||||
package com.audio.vibe.data.playback
|
||||
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.app.Service
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.ServiceConnection
|
||||
import android.content.pm.ServiceInfo
|
||||
import android.media.MediaMetadata
|
||||
import android.media.session.MediaSession
|
||||
import android.media.session.PlaybackState as PlatformPlaybackState
|
||||
import android.os.Build
|
||||
import android.os.Binder
|
||||
import android.os.IBinder
|
||||
import com.audio.vibe.MainActivity
|
||||
import com.audio.vibe.R
|
||||
import com.audio.vibe.domain.model.PlaybackTrack
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.filter
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import kotlin.coroutines.resume
|
||||
|
||||
class AudioPlaybackService : Service() {
|
||||
private val binder = LocalBinder()
|
||||
private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
private var isForeground = false
|
||||
private lateinit var mediaSession: MediaSession
|
||||
private lateinit var controller: AudioPlaybackController
|
||||
private val serviceController = object : PlaybackServiceController {
|
||||
override val state
|
||||
get() = controller.state
|
||||
|
||||
override fun toggleCurrent(): Boolean {
|
||||
return controller.toggleCurrent()
|
||||
}
|
||||
|
||||
override fun playQueue(
|
||||
queueIds: LongArray,
|
||||
startTrackId: Long,
|
||||
trackResolver: suspend (Long) -> PlaybackTrack?
|
||||
) {
|
||||
controller.playQueue(
|
||||
queueIds = queueIds,
|
||||
startTrackId = startTrackId,
|
||||
trackResolver = trackResolver
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
controller = AudioPlaybackController(this)
|
||||
mediaSession = MediaSession(this, MEDIA_SESSION_TAG).apply {
|
||||
setCallback(
|
||||
object : MediaSession.Callback() {
|
||||
override fun onPlay() {
|
||||
if (!this@AudioPlaybackService.controller.state.value.isPlaying) {
|
||||
this@AudioPlaybackService.controller.toggleCurrent()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
if (this@AudioPlaybackService.controller.state.value.isPlaying) {
|
||||
this@AudioPlaybackService.controller.toggleCurrent()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onSkipToNext() {
|
||||
this@AudioPlaybackService.controller.playNext()
|
||||
}
|
||||
|
||||
override fun onSkipToPrevious() {
|
||||
this@AudioPlaybackService.controller.playPrevious()
|
||||
}
|
||||
|
||||
override fun onSeekTo(pos: Long) {
|
||||
this@AudioPlaybackService.controller.seekTo(pos)
|
||||
}
|
||||
|
||||
override fun onStop() {
|
||||
this@AudioPlaybackService.controller.stop()
|
||||
}
|
||||
}
|
||||
)
|
||||
isActive = true
|
||||
}
|
||||
observePlaybackState(controller)
|
||||
}
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder {
|
||||
return binder
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
when (intent?.action) {
|
||||
ACTION_TOGGLE -> controller.toggleCurrent()
|
||||
ACTION_NEXT -> controller.playNext()
|
||||
ACTION_PREVIOUS -> controller.playPrevious()
|
||||
ACTION_STOP -> {
|
||||
controller.stop()
|
||||
}
|
||||
}
|
||||
return if (controller.state.value.hasQueue) START_STICKY else START_NOT_STICKY
|
||||
}
|
||||
|
||||
override fun onTaskRemoved(rootIntent: Intent?) {
|
||||
if (::controller.isInitialized) {
|
||||
controller.stop()
|
||||
}
|
||||
stopSelf()
|
||||
super.onTaskRemoved(rootIntent)
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
serviceScope.cancel()
|
||||
if (::mediaSession.isInitialized) {
|
||||
mediaSession.isActive = false
|
||||
mediaSession.release()
|
||||
}
|
||||
if (::controller.isInitialized) {
|
||||
controller.release()
|
||||
}
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
inner class LocalBinder : Binder() {
|
||||
fun controller(): PlaybackServiceController = serviceController
|
||||
}
|
||||
|
||||
private fun observePlaybackState(controller: AudioPlaybackController) {
|
||||
val mediaSessionUpdateGate = MediaSessionUpdateGate()
|
||||
serviceScope.launch {
|
||||
controller.state
|
||||
.map { state -> state.toMediaSessionState() }
|
||||
.filter { state -> mediaSessionUpdateGate.shouldUpdate(state) }
|
||||
.collect { state ->
|
||||
updateMediaSession(state)
|
||||
}
|
||||
}
|
||||
serviceScope.launch {
|
||||
controller.state
|
||||
.map { state -> state.toNotificationVisibleState() }
|
||||
.distinctUntilChanged()
|
||||
.collect { state ->
|
||||
if (state.hasQueue) {
|
||||
enterForeground(state)
|
||||
} else {
|
||||
leaveForeground()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun enterForeground(state: PlaybackNotificationVisibleState) {
|
||||
if (!isForeground) {
|
||||
createNotificationChannel()
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
startForeground(
|
||||
PLAYBACK_NOTIFICATION_ID,
|
||||
buildNotification(state),
|
||||
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK
|
||||
)
|
||||
} else {
|
||||
startForeground(PLAYBACK_NOTIFICATION_ID, buildNotification(state))
|
||||
}
|
||||
isForeground = true
|
||||
} else {
|
||||
notificationManager().notify(PLAYBACK_NOTIFICATION_ID, buildNotification(state))
|
||||
}
|
||||
}
|
||||
|
||||
private fun leaveForeground() {
|
||||
if (!isForeground) return
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
stopForeground(true)
|
||||
}
|
||||
isForeground = false
|
||||
}
|
||||
|
||||
private fun buildNotification(state: PlaybackNotificationVisibleState): Notification {
|
||||
val contentIntent = PendingIntent.getActivity(
|
||||
this,
|
||||
0,
|
||||
Intent(this, MainActivity::class.java),
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
val title = state.currentTitle?.takeIf { it.isNotBlank() } ?: getString(R.string.app_name)
|
||||
val text = state.errorMessage
|
||||
?: state.currentArtist?.takeIf { it.isNotBlank() }
|
||||
?: getString(R.string.playback_notification_text)
|
||||
return Notification.Builder(this, PLAYBACK_CHANNEL_ID)
|
||||
.setSmallIcon(R.drawable.ic_notification_audio)
|
||||
.setContentTitle(title)
|
||||
.setContentText(text)
|
||||
.setContentIntent(contentIntent)
|
||||
.setDeleteIntent(servicePendingIntent(ACTION_STOP, REQUEST_STOP))
|
||||
.setOngoing(state.isPlaying)
|
||||
.setOnlyAlertOnce(true)
|
||||
.setShowWhen(false)
|
||||
.setVisibility(Notification.VISIBILITY_PUBLIC)
|
||||
.setCategory(Notification.CATEGORY_TRANSPORT)
|
||||
.setStyle(
|
||||
Notification.MediaStyle()
|
||||
.setMediaSession(mediaSession.sessionToken)
|
||||
.setShowActionsInCompactView(0, 1, 2)
|
||||
)
|
||||
.addAction(
|
||||
Notification.Action.Builder(
|
||||
R.drawable.ic_notification_audio,
|
||||
ACTION_LABEL_PREVIOUS,
|
||||
servicePendingIntent(ACTION_PREVIOUS, REQUEST_PREVIOUS)
|
||||
).build()
|
||||
)
|
||||
.addAction(
|
||||
Notification.Action.Builder(
|
||||
R.drawable.ic_notification_audio,
|
||||
if (state.isPlaying) ACTION_LABEL_PAUSE else ACTION_LABEL_PLAY,
|
||||
servicePendingIntent(ACTION_TOGGLE, REQUEST_TOGGLE)
|
||||
).build()
|
||||
)
|
||||
.addAction(
|
||||
Notification.Action.Builder(
|
||||
R.drawable.ic_notification_audio,
|
||||
ACTION_LABEL_NEXT,
|
||||
servicePendingIntent(ACTION_NEXT, REQUEST_NEXT)
|
||||
).build()
|
||||
)
|
||||
.addAction(
|
||||
Notification.Action.Builder(
|
||||
R.drawable.ic_notification_audio,
|
||||
getString(R.string.stop),
|
||||
servicePendingIntent(ACTION_STOP, REQUEST_STOP)
|
||||
).build()
|
||||
)
|
||||
.build()
|
||||
}
|
||||
|
||||
private fun updateMediaSession(state: PlaybackMediaSessionState) {
|
||||
if (!::mediaSession.isInitialized) return
|
||||
val actions = (PlatformPlaybackState.ACTION_PLAY or
|
||||
PlatformPlaybackState.ACTION_PAUSE or
|
||||
PlatformPlaybackState.ACTION_PLAY_PAUSE or
|
||||
PlatformPlaybackState.ACTION_SKIP_TO_NEXT or
|
||||
PlatformPlaybackState.ACTION_SKIP_TO_PREVIOUS or
|
||||
PlatformPlaybackState.ACTION_STOP) or
|
||||
(if (state.canSeek) PlatformPlaybackState.ACTION_SEEK_TO else 0L)
|
||||
val playbackStateCode = when {
|
||||
!state.errorMessage.isNullOrBlank() -> PlatformPlaybackState.STATE_ERROR
|
||||
state.isPlaying -> PlatformPlaybackState.STATE_PLAYING
|
||||
state.hasQueue -> PlatformPlaybackState.STATE_PAUSED
|
||||
else -> PlatformPlaybackState.STATE_STOPPED
|
||||
}
|
||||
val playbackState = PlatformPlaybackState.Builder()
|
||||
.setActions(actions)
|
||||
.setState(
|
||||
playbackStateCode,
|
||||
state.positionMs,
|
||||
if (state.isPlaying) 1f else 0f
|
||||
)
|
||||
.apply {
|
||||
if (!state.errorMessage.isNullOrBlank()) {
|
||||
setErrorMessage(state.errorMessage)
|
||||
}
|
||||
}
|
||||
.build()
|
||||
val metadata = MediaMetadata.Builder()
|
||||
.putString(MediaMetadata.METADATA_KEY_TITLE, state.currentTitle.orEmpty())
|
||||
.putString(MediaMetadata.METADATA_KEY_ARTIST, state.currentArtist.orEmpty())
|
||||
.apply {
|
||||
state.durationMs?.let { putLong(MediaMetadata.METADATA_KEY_DURATION, it) }
|
||||
}
|
||||
.build()
|
||||
mediaSession.setPlaybackState(playbackState)
|
||||
mediaSession.setMetadata(metadata)
|
||||
mediaSession.isActive = state.hasQueue
|
||||
}
|
||||
|
||||
private fun servicePendingIntent(action: String, requestCode: Int): PendingIntent {
|
||||
val intent = Intent(this, AudioPlaybackService::class.java).setAction(action)
|
||||
return PendingIntent.getService(
|
||||
this,
|
||||
requestCode,
|
||||
intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
}
|
||||
|
||||
private fun createNotificationChannel() {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
|
||||
val channel = NotificationChannel(
|
||||
PLAYBACK_CHANNEL_ID,
|
||||
getString(R.string.app_name),
|
||||
NotificationManager.IMPORTANCE_LOW
|
||||
)
|
||||
notificationManager().createNotificationChannel(channel)
|
||||
}
|
||||
|
||||
private fun notificationManager(): NotificationManager {
|
||||
return getSystemService(NotificationManager::class.java)
|
||||
}
|
||||
|
||||
companion object {
|
||||
suspend fun startAndBindController(context: Context): PlaybackServiceController? {
|
||||
val appContext = context.applicationContext
|
||||
val intent = Intent(appContext, AudioPlaybackService::class.java)
|
||||
appContext.startService(intent)
|
||||
return suspendCancellableCoroutine { continuation ->
|
||||
var connection: ServiceConnection? = null
|
||||
connection = object : ServiceConnection {
|
||||
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
|
||||
val controller = (service as? LocalBinder)?.controller()
|
||||
runCatching { appContext.unbindService(this) }
|
||||
if (continuation.isActive) {
|
||||
continuation.resume(controller)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onServiceDisconnected(name: ComponentName?) = Unit
|
||||
|
||||
override fun onBindingDied(name: ComponentName?) {
|
||||
runCatching { appContext.unbindService(this) }
|
||||
if (continuation.isActive) {
|
||||
continuation.resume(null)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onNullBinding(name: ComponentName?) {
|
||||
runCatching { appContext.unbindService(this) }
|
||||
if (continuation.isActive) {
|
||||
continuation.resume(null)
|
||||
}
|
||||
}
|
||||
}
|
||||
val bound = appContext.bindService(intent, connection, BIND_AUTO_CREATE)
|
||||
if (!bound && continuation.isActive) {
|
||||
continuation.resume(null)
|
||||
}
|
||||
continuation.invokeOnCancellation {
|
||||
connection?.let { runCatching { appContext.unbindService(it) } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private const val MEDIA_SESSION_TAG = "AudioVibePlayback"
|
||||
private const val PLAYBACK_CHANNEL_ID = "audio_vibe_playback"
|
||||
private const val PLAYBACK_NOTIFICATION_ID = 1001
|
||||
private const val ACTION_TOGGLE = "com.audio.vibe.data.playback.action.TOGGLE"
|
||||
private const val ACTION_NEXT = "com.audio.vibe.data.playback.action.NEXT"
|
||||
private const val ACTION_PREVIOUS = "com.audio.vibe.data.playback.action.PREVIOUS"
|
||||
private const val ACTION_STOP = "com.audio.vibe.data.playback.action.STOP"
|
||||
private const val ACTION_LABEL_PLAY = "Play"
|
||||
private const val ACTION_LABEL_PAUSE = "Pause"
|
||||
private const val ACTION_LABEL_NEXT = "Next"
|
||||
private const val ACTION_LABEL_PREVIOUS = "Previous"
|
||||
private const val REQUEST_TOGGLE = 1
|
||||
private const val REQUEST_NEXT = 2
|
||||
private const val REQUEST_PREVIOUS = 3
|
||||
private const val REQUEST_STOP = 4
|
||||
@ -0,0 +1,16 @@
|
||||
package com.audio.vibe.data.playback
|
||||
|
||||
import com.audio.vibe.domain.model.PlaybackTrack
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
|
||||
interface PlaybackServiceController {
|
||||
val state: StateFlow<PlaybackState>
|
||||
|
||||
fun toggleCurrent(): Boolean
|
||||
|
||||
fun playQueue(
|
||||
queueIds: LongArray,
|
||||
startTrackId: Long,
|
||||
trackResolver: suspend (Long) -> PlaybackTrack?
|
||||
)
|
||||
}
|
||||
@ -0,0 +1,109 @@
|
||||
package com.audio.vibe.data.playback
|
||||
|
||||
import kotlin.math.abs
|
||||
|
||||
internal data class PlaybackMediaSessionState(
|
||||
val currentId: Long?,
|
||||
val hasQueue: Boolean,
|
||||
val currentTitle: String?,
|
||||
val currentArtist: String?,
|
||||
val isPlaying: Boolean,
|
||||
val positionMs: Long,
|
||||
val durationMs: Long?,
|
||||
val canSeek: Boolean,
|
||||
val errorMessage: String?
|
||||
)
|
||||
|
||||
internal data class PlaybackNotificationVisibleState(
|
||||
val hasQueue: Boolean,
|
||||
val currentTitle: String?,
|
||||
val currentArtist: String?,
|
||||
val isPlaying: Boolean,
|
||||
val errorMessage: String?
|
||||
)
|
||||
|
||||
internal fun PlaybackState.toMediaSessionState(): PlaybackMediaSessionState {
|
||||
return PlaybackMediaSessionState(
|
||||
currentId = currentId,
|
||||
hasQueue = hasQueue,
|
||||
currentTitle = currentTitle,
|
||||
currentArtist = currentArtist,
|
||||
isPlaying = isPlaying,
|
||||
positionMs = positionMs,
|
||||
durationMs = durationMs,
|
||||
canSeek = canSeek,
|
||||
errorMessage = errorMessage
|
||||
)
|
||||
}
|
||||
|
||||
internal fun PlaybackState.toNotificationVisibleState(): PlaybackNotificationVisibleState {
|
||||
return PlaybackNotificationVisibleState(
|
||||
hasQueue = hasQueue,
|
||||
currentTitle = currentTitle,
|
||||
currentArtist = currentArtist,
|
||||
isPlaying = isPlaying,
|
||||
errorMessage = errorMessage
|
||||
)
|
||||
}
|
||||
|
||||
internal class MediaSessionUpdateGate(
|
||||
private val positionJumpThresholdMs: Long = DEFAULT_POSITION_JUMP_THRESHOLD_MS,
|
||||
private val nowMs: () -> Long = { System.nanoTime() / NANOS_PER_MILLI }
|
||||
) {
|
||||
private var lastAnchor: MediaSessionAnchor? = null
|
||||
|
||||
fun shouldUpdate(next: PlaybackMediaSessionState): Boolean {
|
||||
return shouldUpdate(next, nowMs())
|
||||
}
|
||||
|
||||
fun shouldUpdate(next: PlaybackMediaSessionState, nowMs: Long): Boolean {
|
||||
val previous = lastAnchor
|
||||
if (previous == null) {
|
||||
lastAnchor = MediaSessionAnchor(next, nowMs)
|
||||
return true
|
||||
}
|
||||
|
||||
val shouldUpdate = previous.state.hasBoundaryChange(next) ||
|
||||
previous.positionDriftMs(next, nowMs) > positionJumpThresholdMs
|
||||
if (shouldUpdate) {
|
||||
lastAnchor = MediaSessionAnchor(next, nowMs)
|
||||
}
|
||||
return shouldUpdate
|
||||
}
|
||||
|
||||
private fun PlaybackMediaSessionState.hasBoundaryChange(
|
||||
next: PlaybackMediaSessionState
|
||||
): Boolean {
|
||||
return currentId != next.currentId ||
|
||||
hasQueue != next.hasQueue ||
|
||||
currentTitle != next.currentTitle ||
|
||||
currentArtist != next.currentArtist ||
|
||||
isPlaying != next.isPlaying ||
|
||||
durationMs != next.durationMs ||
|
||||
canSeek != next.canSeek ||
|
||||
errorMessage != next.errorMessage
|
||||
}
|
||||
|
||||
private fun MediaSessionAnchor.positionDriftMs(
|
||||
next: PlaybackMediaSessionState,
|
||||
nowMs: Long
|
||||
): Long {
|
||||
val elapsedMs = (nowMs - updatedAtMs).coerceAtLeast(0L)
|
||||
val expectedPosition = if (state.isPlaying) {
|
||||
state.positionMs + elapsedMs
|
||||
} else {
|
||||
state.positionMs
|
||||
}
|
||||
return abs(next.positionMs - expectedPosition)
|
||||
}
|
||||
|
||||
private data class MediaSessionAnchor(
|
||||
val state: PlaybackMediaSessionState,
|
||||
val updatedAtMs: Long
|
||||
)
|
||||
|
||||
private companion object {
|
||||
private const val DEFAULT_POSITION_JUMP_THRESHOLD_MS = 1_500L
|
||||
private const val NANOS_PER_MILLI = 1_000_000L
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,26 @@
|
||||
package com.audio.vibe.data.repository
|
||||
|
||||
internal data class AudioScanFingerprint(
|
||||
val uri: String,
|
||||
val relativePath: String?,
|
||||
val sourcePath: String?,
|
||||
val sizeBytes: Long,
|
||||
val dateModifiedSeconds: Long
|
||||
) {
|
||||
fun needsScan(cached: CachedAudioScanFingerprint?): Boolean {
|
||||
if (cached == null) return true
|
||||
return cached.sizeBytes != sizeBytes ||
|
||||
cached.dateModifiedSeconds != dateModifiedSeconds ||
|
||||
cached.uri != uri ||
|
||||
cached.relativePath != relativePath ||
|
||||
cached.sourcePath != sourcePath
|
||||
}
|
||||
}
|
||||
|
||||
internal data class CachedAudioScanFingerprint(
|
||||
val uri: String,
|
||||
val relativePath: String?,
|
||||
val sourcePath: String?,
|
||||
val sizeBytes: Long,
|
||||
val dateModifiedSeconds: Long
|
||||
)
|
||||
@ -6,6 +6,7 @@ import android.net.Uri
|
||||
import android.provider.DocumentsContract
|
||||
import android.os.Build
|
||||
import android.provider.MediaStore
|
||||
import android.util.Log
|
||||
import androidx.paging.Pager
|
||||
import androidx.paging.PagingConfig
|
||||
import androidx.paging.PagingData
|
||||
@ -16,6 +17,8 @@ import com.audio.vibe.data.local.MusicLibraryDatabase
|
||||
import com.audio.vibe.data.local.MusicTrackEntity
|
||||
import com.audio.vibe.data.local.toDomain
|
||||
import com.audio.vibe.data.local.toEntity
|
||||
import com.audio.vibe.domain.model.AudioFormatCapability
|
||||
import com.audio.vibe.domain.model.PlaybackTrack
|
||||
import com.audio.vibe.domain.model.ScannedAudioTrack
|
||||
import com.audio.vibe.domain.repository.MusicLibrarySort
|
||||
import com.audio.vibe.domain.repository.MusicLibrarySummary
|
||||
@ -23,6 +26,7 @@ import com.audio.vibe.domain.repository.MusicScanProgress
|
||||
import com.audio.vibe.domain.repository.MusicScannerRepository
|
||||
import com.arthenica.ffmpegkit.FFmpegKitConfig
|
||||
import com.arthenica.ffmpegkit.FFprobeKit
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@ -40,6 +44,7 @@ import kotlinx.coroutines.withContext
|
||||
import org.json.JSONObject
|
||||
import org.jaudiotagger.audio.AudioFileIO
|
||||
import org.jaudiotagger.tag.FieldKey
|
||||
import timber.log.Timber
|
||||
import java.io.File
|
||||
import kotlin.coroutines.coroutineContext
|
||||
|
||||
@ -108,26 +113,70 @@ class MediaStoreMusicScannerRepository(
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun playbackQueueIds(
|
||||
query: String,
|
||||
sort: MusicLibrarySort
|
||||
): LongArray = withContext(Dispatchers.IO) {
|
||||
val ftsQuery = query.trim().toFtsQuery()
|
||||
val ids = when (sort) {
|
||||
MusicLibrarySort.Tracks -> if (ftsQuery == null) {
|
||||
musicTrackDao.playbackIdsByTrack()
|
||||
} else {
|
||||
musicTrackDao.searchPlaybackIdsByTrack(ftsQuery)
|
||||
}
|
||||
|
||||
MusicLibrarySort.Albums -> if (ftsQuery == null) {
|
||||
musicTrackDao.playbackIdsByAlbum()
|
||||
} else {
|
||||
musicTrackDao.searchPlaybackIdsByAlbum(ftsQuery)
|
||||
}
|
||||
|
||||
MusicLibrarySort.Artists -> if (ftsQuery == null) {
|
||||
musicTrackDao.playbackIdsByArtist()
|
||||
} else {
|
||||
musicTrackDao.searchPlaybackIdsByArtist(ftsQuery)
|
||||
}
|
||||
|
||||
MusicLibrarySort.Recent -> if (ftsQuery == null) {
|
||||
musicTrackDao.playbackIdsByRecent()
|
||||
} else {
|
||||
musicTrackDao.searchPlaybackIdsByRecent(ftsQuery)
|
||||
}
|
||||
|
||||
MusicLibrarySort.Formats -> if (ftsQuery == null) {
|
||||
musicTrackDao.playbackIdsByFormat()
|
||||
} else {
|
||||
musicTrackDao.searchPlaybackIdsByFormat(ftsQuery)
|
||||
}
|
||||
}
|
||||
ids.toLongArray()
|
||||
}
|
||||
|
||||
override suspend fun playbackTrack(id: Long): PlaybackTrack? = withContext(Dispatchers.IO) {
|
||||
musicTrackDao.playbackTrackById(id)?.toDomain()
|
||||
}
|
||||
|
||||
override suspend fun loadCachedAudio(): List<ScannedAudioTrack> = withContext(Dispatchers.IO) {
|
||||
musicTrackDao.getAllTracks().map { it.toDomain() }.also { _cachedAudio.value = it }
|
||||
}
|
||||
|
||||
override suspend fun loadLibrarySummary(query: String): MusicLibrarySummary = withContext(Dispatchers.IO) {
|
||||
val ftsQuery = query.trim().toFtsQuery()
|
||||
if (ftsQuery == null) {
|
||||
MusicLibrarySummary(
|
||||
totalTracks = musicTrackDao.trackCount(),
|
||||
highResolutionTracks = musicTrackDao.highResolutionTrackCount(),
|
||||
formats = musicTrackDao.formats()
|
||||
)
|
||||
} else {
|
||||
MusicLibrarySummary(
|
||||
totalTracks = musicTrackDao.searchTrackCount(ftsQuery),
|
||||
highResolutionTracks = musicTrackDao.searchHighResolutionTrackCount(ftsQuery),
|
||||
formats = musicTrackDao.searchFormats(ftsQuery)
|
||||
)
|
||||
override suspend fun loadLibrarySummary(query: String): MusicLibrarySummary =
|
||||
withContext(Dispatchers.IO) {
|
||||
val ftsQuery = query.trim().toFtsQuery()
|
||||
if (ftsQuery == null) {
|
||||
MusicLibrarySummary(
|
||||
totalTracks = musicTrackDao.trackCount(),
|
||||
highResolutionTracks = musicTrackDao.highResolutionTrackCount(),
|
||||
formats = musicTrackDao.formats()
|
||||
)
|
||||
} else {
|
||||
MusicLibrarySummary(
|
||||
totalTracks = musicTrackDao.searchTrackCount(ftsQuery),
|
||||
highResolutionTracks = musicTrackDao.searchHighResolutionTrackCount(ftsQuery),
|
||||
formats = musicTrackDao.searchFormats(ftsQuery)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun resetLibrary(): Unit = withContext(Dispatchers.IO) {
|
||||
musicTrackDao.clearLibrary()
|
||||
@ -138,9 +187,12 @@ class MediaStoreMusicScannerRepository(
|
||||
withContext(Dispatchers.IO) {
|
||||
val files = collectMediaStoreAudioFiles()
|
||||
val cachedTracks = loadCachedTracks(files.map { it.libraryPath() })
|
||||
onProgress(MusicScanProgress(scanned = 0, total = files.size))
|
||||
val filesToScan = files.filter { file ->
|
||||
file.needsLocalScan(cachedTracks[file.libraryPath()])
|
||||
}
|
||||
onProgress(MusicScanProgress(scanned = 0))
|
||||
processLocalFileCandidates(
|
||||
files = files,
|
||||
files = filesToScan,
|
||||
cachedTracks = cachedTracks,
|
||||
onProgress = onProgress
|
||||
)
|
||||
@ -158,7 +210,7 @@ class MediaStoreMusicScannerRepository(
|
||||
val filesToScan = files.filter { file ->
|
||||
file.needsDocumentScan(cachedTracks[file.libraryPath()])
|
||||
}
|
||||
onProgress(MusicScanProgress(scanned = 0, total = filesToScan.size))
|
||||
onProgress(MusicScanProgress(scanned = 0))
|
||||
processDocumentCandidates(
|
||||
files = filesToScan,
|
||||
cachedTracks = cachedTracks,
|
||||
@ -172,7 +224,7 @@ class MediaStoreMusicScannerRepository(
|
||||
onProgress: (MusicScanProgress) -> Unit
|
||||
): List<ScannedAudioTrack> = coroutineScope {
|
||||
val writer = TrackBatchWriter { tracks -> persistTracks(tracks) }
|
||||
val progress = ProgressThrottler(files.size, onProgress)
|
||||
val progress = ProgressThrottler(onProgress)
|
||||
val scannedTracks = mutableListOf<ScannedAudioTrack>()
|
||||
var scanned = 0
|
||||
|
||||
@ -188,7 +240,7 @@ class MediaStoreMusicScannerRepository(
|
||||
val workers = List(metadataReadParallelism()) {
|
||||
launch(metadataDispatcher) {
|
||||
for (file in input) {
|
||||
file.toTrackResult(cachedTracks[file.libraryPath()])
|
||||
file.toTrackResultSafely(cachedTracks[file.libraryPath()])
|
||||
.also { output.send(it) }
|
||||
}
|
||||
}
|
||||
@ -205,9 +257,13 @@ class MediaStoreMusicScannerRepository(
|
||||
// 因此每个 worker 发出的 ScannedTrackResult 都会让 scanned 只递增一次。
|
||||
for (result in output) {
|
||||
coroutineContext.ensureActive()
|
||||
scannedTracks.add(result.track)
|
||||
val track = result.track
|
||||
if (track == null) {
|
||||
continue
|
||||
}
|
||||
scannedTracks.add(track)
|
||||
if (result.shouldPersist) {
|
||||
writer.accept(result.track)
|
||||
writer.accept(track)
|
||||
}
|
||||
scanned += 1
|
||||
progress.update(scanned)
|
||||
@ -215,6 +271,7 @@ class MediaStoreMusicScannerRepository(
|
||||
// 兜底等待 closer 结束,确保 output 已由收尾协程关闭。
|
||||
closer.join()
|
||||
|
||||
progress.flush(scanned)
|
||||
writer.flush()
|
||||
scannedTracks
|
||||
}
|
||||
@ -225,7 +282,7 @@ class MediaStoreMusicScannerRepository(
|
||||
onProgress: (MusicScanProgress) -> Unit
|
||||
): List<ScannedAudioTrack> = coroutineScope {
|
||||
val writer = TrackBatchWriter { tracks -> persistTracks(tracks) }
|
||||
val progress = ProgressThrottler(files.size, onProgress)
|
||||
val progress = ProgressThrottler(onProgress)
|
||||
val scannedTracks = mutableListOf<ScannedAudioTrack>()
|
||||
var scanned = 0
|
||||
|
||||
@ -241,8 +298,10 @@ class MediaStoreMusicScannerRepository(
|
||||
val workers = List(externalMetadataReadParallelism()) {
|
||||
launch(externalMetadataDispatcher) {
|
||||
for (file in input) {
|
||||
file.toTrackResult(cachedTracks[file.libraryPath()])
|
||||
.also { output.send(it) }
|
||||
file.toTrackResultSafely(cachedTracks[file.libraryPath()])
|
||||
.also {
|
||||
output.send(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -258,15 +317,20 @@ class MediaStoreMusicScannerRepository(
|
||||
// 所以进度计数是顺序执行的,不会在 worker 协程之间发生竞争。
|
||||
for (result in output) {
|
||||
coroutineContext.ensureActive()
|
||||
scannedTracks.add(result.track)
|
||||
val track = result.track
|
||||
if (track == null) {
|
||||
continue
|
||||
}
|
||||
scannedTracks.add(track)
|
||||
if (result.shouldPersist) {
|
||||
writer.accept(result.track)
|
||||
writer.accept(track)
|
||||
}
|
||||
scanned += 1
|
||||
progress.update(scanned)
|
||||
}
|
||||
closer.join()
|
||||
|
||||
progress.flush(scanned)
|
||||
writer.flush()
|
||||
scannedTracks
|
||||
}
|
||||
@ -280,12 +344,42 @@ class MediaStoreMusicScannerRepository(
|
||||
return cachedEntities.map { it.toDomain() }.associateBy { it.libraryPath() }
|
||||
}
|
||||
|
||||
private suspend fun LocalAudioFile.toTrackResultSafely(
|
||||
cached: ScannedAudioTrack?
|
||||
): ScannedTrackResult {
|
||||
return try {
|
||||
toTrackResult(cached)
|
||||
} catch (error: CancellationException) {
|
||||
throw error
|
||||
} catch (error: Throwable) {
|
||||
Timber.w(error, "Failed to scan MediaStore audio file: name=%s uri=%s", name, uri)
|
||||
skippedTrackResult(source = "MediaStore", uri = uri, name = name)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun DocumentAudioFile.toTrackResultSafely(
|
||||
cached: ScannedAudioTrack?
|
||||
): ScannedTrackResult {
|
||||
return try {
|
||||
toTrackResult(cached)
|
||||
} catch (error: CancellationException) {
|
||||
throw error
|
||||
} catch (error: Throwable) {
|
||||
Timber.w(error, "Failed to scan SAF audio file: name=%s uri=%s", name, uri)
|
||||
skippedTrackResult(source = "SAF", uri = uri, name = name)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun LocalAudioFile.toTrackResult(cached: ScannedAudioTrack?): ScannedTrackResult {
|
||||
if (cached != null && cached.sizeBytes == sizeBytes && cached.dateModifiedSeconds == dateModifiedSeconds) {
|
||||
val track = cached.copy(
|
||||
uri = uri,
|
||||
relativePath = relativePath,
|
||||
sourcePath = sourcePath
|
||||
).withCapabilities(
|
||||
format = cached.format,
|
||||
metadata = null,
|
||||
inferMissingMetadataFailure = false
|
||||
)
|
||||
return ScannedTrackResult(
|
||||
track = track,
|
||||
@ -296,25 +390,30 @@ class MediaStoreMusicScannerRepository(
|
||||
}
|
||||
|
||||
val format = detectFormat(name, mimeType)
|
||||
val metadata = readBestMetadata(uri, format)
|
||||
val metadata = readBestMetadata(uri, name, format)
|
||||
?: return skippedTrackResult(source = "MediaStore", uri = uri, name = name)
|
||||
val normalizedMimeType = canonicalMimeType(format, mimeType, metadata.mimeType)
|
||||
val track = ScannedAudioTrack(
|
||||
id = newScannedTrackId(),
|
||||
uri = uri,
|
||||
title = metadata.title ?: name.substringBeforeLast('.', name),
|
||||
artist = metadata.artist.orEmpty(),
|
||||
album = metadata.album.orEmpty(),
|
||||
durationMs = metadata.durationMs,
|
||||
sizeBytes = sizeBytes,
|
||||
mimeType = normalizedMimeType,
|
||||
format = format,
|
||||
sampleRateHz = metadata.sampleRateHz,
|
||||
bitrate = metadata.bitrate,
|
||||
bitDepth = metadata.bitDepth ?: inferBitDepth(format, metadata.mimeType),
|
||||
relativePath = relativePath,
|
||||
sourcePath = sourcePath,
|
||||
dateModifiedSeconds = dateModifiedSeconds,
|
||||
parseFailureReason = metadata.parseFailureReason
|
||||
).withCapabilities(format, metadata)
|
||||
logParsedTrack(track, source = "MediaStore", parser = metadata.parserName(format))
|
||||
return ScannedTrackResult(
|
||||
track = ScannedAudioTrack(
|
||||
id = sourcePath.hashCode().toLong(),
|
||||
uri = uri,
|
||||
title = metadata.title ?: name.substringBeforeLast('.', name),
|
||||
artist = metadata.artist.orEmpty(),
|
||||
album = metadata.album.orEmpty(),
|
||||
durationMs = metadata.durationMs,
|
||||
sizeBytes = sizeBytes,
|
||||
mimeType = mimeType.ifBlank { metadata.mimeType.orEmpty() },
|
||||
format = format,
|
||||
sampleRateHz = metadata.sampleRateHz,
|
||||
bitrate = metadata.bitrate,
|
||||
bitDepth = metadata.bitDepth ?: inferBitDepth(format, metadata.mimeType),
|
||||
relativePath = relativePath,
|
||||
sourcePath = sourcePath,
|
||||
dateModifiedSeconds = dateModifiedSeconds
|
||||
),
|
||||
track = track,
|
||||
shouldPersist = true
|
||||
)
|
||||
}
|
||||
@ -323,6 +422,11 @@ class MediaStoreMusicScannerRepository(
|
||||
val sourcePath = this.sourcePath
|
||||
if (cached != null && cached.sizeBytes == sizeBytes && cached.dateModifiedSeconds == lastModifiedSeconds) {
|
||||
val track = cached.copy(uri = uri, relativePath = relativePath, sourcePath = sourcePath)
|
||||
.withCapabilities(
|
||||
format = cached.format,
|
||||
metadata = null,
|
||||
inferMissingMetadataFailure = false
|
||||
)
|
||||
return ScannedTrackResult(
|
||||
track = track,
|
||||
shouldPersist = cached.uri != uri ||
|
||||
@ -332,46 +436,64 @@ class MediaStoreMusicScannerRepository(
|
||||
}
|
||||
|
||||
val format = detectFormat(name, mimeType)
|
||||
val metadata = readBestMetadata(uri, format)
|
||||
val metadata = readBestMetadata(uri, name, format)
|
||||
?: return skippedTrackResult(source = "SAF", uri = uri, name = name)
|
||||
val normalizedMimeType = canonicalMimeType(format, mimeType, metadata.mimeType)
|
||||
val track = ScannedAudioTrack(
|
||||
id = newScannedTrackId(),
|
||||
uri = uri,
|
||||
title = metadata.title ?: name.substringBeforeLast('.', name),
|
||||
artist = metadata.artist.orEmpty(),
|
||||
album = metadata.album.orEmpty(),
|
||||
durationMs = metadata.durationMs,
|
||||
sizeBytes = sizeBytes,
|
||||
mimeType = normalizedMimeType,
|
||||
format = format,
|
||||
sampleRateHz = metadata.sampleRateHz,
|
||||
bitrate = metadata.bitrate,
|
||||
bitDepth = metadata.bitDepth ?: inferBitDepth(format, metadata.mimeType),
|
||||
relativePath = relativePath,
|
||||
sourcePath = sourcePath,
|
||||
dateModifiedSeconds = lastModifiedSeconds,
|
||||
parseFailureReason = metadata.parseFailureReason
|
||||
).withCapabilities(format, metadata)
|
||||
logParsedTrack(track, source = "SAF", parser = metadata.parserName(format))
|
||||
return ScannedTrackResult(
|
||||
track = ScannedAudioTrack(
|
||||
id = uri.toString().hashCode().toLong(),
|
||||
uri = uri,
|
||||
title = metadata.title ?: name.substringBeforeLast('.', name),
|
||||
artist = metadata.artist.orEmpty(),
|
||||
album = metadata.album.orEmpty(),
|
||||
durationMs = metadata.durationMs,
|
||||
sizeBytes = sizeBytes,
|
||||
mimeType = mimeType.ifBlank { metadata.mimeType.orEmpty() },
|
||||
format = format,
|
||||
sampleRateHz = metadata.sampleRateHz,
|
||||
bitrate = metadata.bitrate,
|
||||
bitDepth = metadata.bitDepth ?: inferBitDepth(format, metadata.mimeType),
|
||||
relativePath = relativePath,
|
||||
sourcePath = sourcePath,
|
||||
dateModifiedSeconds = lastModifiedSeconds
|
||||
),
|
||||
track = track,
|
||||
shouldPersist = true
|
||||
)
|
||||
}
|
||||
|
||||
private fun readTaggerMetadata(uri: Uri): TrackMetadata {
|
||||
private fun readTaggerMetadata(uri: Uri, displayName: String): TrackMetadata {
|
||||
return runCatching {
|
||||
if (uri.scheme == "file") {
|
||||
return@runCatching readTaggerMetadata(File(uri.path.orEmpty()))
|
||||
}
|
||||
val extension = taggerExtension(displayName) ?: return@runCatching TrackMetadata()
|
||||
appContext.contentResolver.openFileDescriptor(uri, "r")?.use { descriptor ->
|
||||
readTaggerMetadata(File("/proc/self/fd/${descriptor.fd}"))
|
||||
readTaggerMetadataAs(File("/proc/self/fd/${descriptor.fd}"), extension)
|
||||
} ?: TrackMetadata()
|
||||
}.getOrElse {
|
||||
TrackMetadata()
|
||||
}.getOrElse { error ->
|
||||
Timber.i(
|
||||
"jaudiotagger metadata unavailable: uri=%s reason=%s",
|
||||
uri,
|
||||
error.shortReason()
|
||||
)
|
||||
TrackMetadata(parseFailureReason = "jaudiotagger failed: ${error.shortReason()}")
|
||||
}
|
||||
}
|
||||
|
||||
private fun readTaggerMetadataAs(file: File, extension: String): TrackMetadata {
|
||||
return AudioFileIO.readAs(file, extension).toTrackMetadata()
|
||||
}
|
||||
|
||||
private fun readTaggerMetadata(file: File): TrackMetadata {
|
||||
val audioFile = AudioFileIO.read(file)
|
||||
val tag = audioFile.tag
|
||||
val header = audioFile.audioHeader
|
||||
return AudioFileIO.read(file).toTrackMetadata()
|
||||
}
|
||||
|
||||
private fun org.jaudiotagger.audio.AudioFile.toTrackMetadata(): TrackMetadata {
|
||||
val tag = tag
|
||||
val header = audioHeader
|
||||
return TrackMetadata(
|
||||
title = tag?.getFirst(FieldKey.TITLE).toMetadataValue(),
|
||||
artist = tag?.getFirst(FieldKey.ARTIST).toMetadataValue(),
|
||||
@ -383,15 +505,25 @@ class MediaStoreMusicScannerRepository(
|
||||
)
|
||||
}
|
||||
|
||||
private suspend fun readBestMetadata(uri: Uri, format: String): TrackMetadata {
|
||||
private suspend fun readBestMetadata(
|
||||
uri: Uri,
|
||||
displayName: String,
|
||||
format: String
|
||||
): TrackMetadata? {
|
||||
if (format.uppercase() !in jaudioFirstFormats) {
|
||||
return readFfprobeMetadataLimited(uri, format)
|
||||
return readFfprobeMetadataLimited(
|
||||
uri,
|
||||
format
|
||||
).takeIf { it.hasCompleteTechnicalMetadata() }
|
||||
}
|
||||
val taggerMetadata = readTaggerMetadata(uri)
|
||||
val taggerMetadata = readTaggerMetadata(uri, displayName)
|
||||
if (!taggerMetadata.needsFfprobeFallback(format)) {
|
||||
return taggerMetadata
|
||||
}
|
||||
val ffprobeMetadata = readFfprobeMetadataLimited(uri, format)
|
||||
if (!ffprobeMetadata.hasCompleteTechnicalMetadata()) {
|
||||
return null
|
||||
}
|
||||
return mergeMetadataForFallback(
|
||||
taggerMetadata = taggerMetadata,
|
||||
ffprobeMetadata = ffprobeMetadata
|
||||
@ -417,7 +549,7 @@ class MediaStoreMusicScannerRepository(
|
||||
"-select_streams",
|
||||
"a:0",
|
||||
"-show_entries",
|
||||
"format=duration,bit_rate:format_tags=title,artist,album,album_artist:" +
|
||||
"format=duration,bit_rate,format_name:format_tags=title,artist,album,album_artist:" +
|
||||
"stream=codec_name,sample_rate,bit_rate,sample_fmt,bits_per_raw_sample,bits_per_sample:" +
|
||||
"stream_tags=title,artist,album,album_artist",
|
||||
"-of",
|
||||
@ -425,12 +557,39 @@ class MediaStoreMusicScannerRepository(
|
||||
probePath
|
||||
)
|
||||
)
|
||||
if (session.returnCode?.isValueSuccess != true) {
|
||||
val failureReason = "FFprobe failed: rc=${session.returnCode}"
|
||||
Timber.w(
|
||||
"FFprobe metadata read failed: format=%s uri=%s rc=%s output=%s failStackTrace=%s",
|
||||
format,
|
||||
uri,
|
||||
session.returnCode,
|
||||
session.output.orEmpty().take(LOG_PREVIEW_LIMIT),
|
||||
session.failStackTrace.orEmpty().take(LOG_PREVIEW_LIMIT)
|
||||
)
|
||||
return@runCatching TrackMetadata(parseFailureReason = failureReason)
|
||||
}
|
||||
JSONObject(session.output.orEmpty()).toTrackMetadata(format)
|
||||
}.getOrElse {
|
||||
TrackMetadata()
|
||||
}.getOrElse { error ->
|
||||
Timber.w(error, "Failed to parse FFprobe metadata: format=%s uri=%s", format, uri)
|
||||
TrackMetadata(parseFailureReason = "FFprobe parse failed: ${error.shortReason()}")
|
||||
}
|
||||
}
|
||||
|
||||
private fun skippedTrackResult(
|
||||
source: String,
|
||||
uri: Uri,
|
||||
name: String
|
||||
): ScannedTrackResult {
|
||||
Timber.w(
|
||||
"Skip audio file because metadata parsing failed: source=%s name=%s uri=%s",
|
||||
source,
|
||||
name,
|
||||
uri
|
||||
)
|
||||
return ScannedTrackResult(track = null, shouldPersist = false)
|
||||
}
|
||||
|
||||
private fun buildFfprobePath(uri: Uri): String {
|
||||
return when (uri.scheme) {
|
||||
"file" -> uri.path.orEmpty()
|
||||
@ -444,7 +603,7 @@ class MediaStoreMusicScannerRepository(
|
||||
): String {
|
||||
val extension = displayName.substringAfterLast('.', missingDelimiterValue = "").uppercase()
|
||||
if (extension in supportedAudioExtensions) return extension
|
||||
val mime = mediaStoreMime
|
||||
val mime = mediaStoreMime.normalizedMimeType().orEmpty()
|
||||
return when {
|
||||
"mpeg" in mime -> "MP3"
|
||||
"flac" in mime -> "FLAC"
|
||||
@ -455,6 +614,19 @@ class MediaStoreMusicScannerRepository(
|
||||
"dsf" in mime || "dff" in mime || "dsd" in mime -> "DSD"
|
||||
"wavpack" in mime -> "WV"
|
||||
"x-ms-wma" in mime || "windows" in mime -> "WMA"
|
||||
"ape" in mime || "monkey" in mime -> "APE"
|
||||
"tta" in mime -> "TTA"
|
||||
"tak" in mime -> "TAK"
|
||||
"musepack" in mime || "mpc" in mime -> "MPC"
|
||||
"matroska" in mime || "mka" in mime -> "MKA"
|
||||
"webm" in mime -> "WEBM"
|
||||
"ac3" in mime -> "AC3"
|
||||
"eac3" in mime || "ec-3" in mime -> "EAC3"
|
||||
"truehd" in mime || "mlp" in mime -> "TRUEHD"
|
||||
"amr" in mime -> "AMR"
|
||||
"realaudio" in mime || "realmedia" in mime -> "RA"
|
||||
"caf" in mime -> "CAF"
|
||||
"basic" in mime || "au" in mime -> "AU"
|
||||
"dts" in mime -> "DTS"
|
||||
"iso" in mime -> "ISO"
|
||||
else -> "AUDIO"
|
||||
@ -473,18 +645,36 @@ class MediaStoreMusicScannerRepository(
|
||||
"OGG",
|
||||
"OPUS",
|
||||
"WMA",
|
||||
"DTS"
|
||||
"DTS",
|
||||
"AC3",
|
||||
"EAC3",
|
||||
"TRUEHD",
|
||||
"MLP",
|
||||
"AMR",
|
||||
"AWB",
|
||||
"RA"
|
||||
) -> "16-bit estimated"
|
||||
|
||||
normalized in setOf(
|
||||
"WV",
|
||||
"WAVPACK",
|
||||
"APE",
|
||||
"TTA",
|
||||
"TAK",
|
||||
"MPC",
|
||||
"OFR",
|
||||
"OFS",
|
||||
"ALAC",
|
||||
"FLAC",
|
||||
"WAV",
|
||||
"AIFF",
|
||||
"AIF"
|
||||
"AIF",
|
||||
"AU",
|
||||
"SND",
|
||||
"CAF",
|
||||
"MKA",
|
||||
"MKV",
|
||||
"WEBM"
|
||||
) -> "Unknown"
|
||||
|
||||
mimeType?.contains("flac", ignoreCase = true) == true -> "Unknown"
|
||||
@ -593,7 +783,7 @@ class MediaStoreMusicScannerRepository(
|
||||
appContext.contentResolver.query(
|
||||
collection,
|
||||
projection,
|
||||
null,
|
||||
mediaStoreMusicSelection(),
|
||||
null,
|
||||
null
|
||||
)?.use { cursor ->
|
||||
@ -622,6 +812,7 @@ class MediaStoreMusicScannerRepository(
|
||||
coroutineContext.ensureActive()
|
||||
val name = cursor.getNullableString(nameColumn).orEmpty()
|
||||
val mimeType = cursor.getNullableString(mimeColumn).orEmpty()
|
||||
val sizeBytes = cursor.getLong(sizeColumn).coerceAtLeast(0L)
|
||||
if (!isSupportedAudioName(name, mimeType)) continue
|
||||
val relativePath = cursor.getNullableString(relativePathColumn)
|
||||
val volumeName = cursor.getNullableString(volumeNameColumn)
|
||||
@ -632,7 +823,7 @@ class MediaStoreMusicScannerRepository(
|
||||
uri = uri,
|
||||
name = name,
|
||||
mimeType = mimeType,
|
||||
sizeBytes = cursor.getLong(sizeColumn).coerceAtLeast(0L),
|
||||
sizeBytes = sizeBytes,
|
||||
dateModifiedSeconds = cursor.getLong(modifiedColumn).coerceAtLeast(0L),
|
||||
relativePath = relativePath,
|
||||
// MediaStore 和 SAF 都统一成同一种 sourcePath:
|
||||
@ -707,6 +898,8 @@ private const val DB_WRITE_INTERVAL_MS = 500L
|
||||
private const val PROGRESS_UPDATE_INTERVAL_MS = 200L
|
||||
private const val SQLITE_QUERY_BIND_LIMIT = 900
|
||||
private const val DSD_BIT_DEPTH = "1-bit DSD"
|
||||
private const val LOG_PREVIEW_LIMIT = 512
|
||||
private const val MAX_TAGGER_EXTENSION_LENGTH = 12
|
||||
private val supportedAudioExtensions = setOf(
|
||||
"MP3",
|
||||
"FLAC",
|
||||
@ -721,9 +914,31 @@ private val supportedAudioExtensions = setOf(
|
||||
"WMA",
|
||||
"DTS",
|
||||
"APE",
|
||||
"TTA",
|
||||
"TAK",
|
||||
"MPC",
|
||||
"OFR",
|
||||
"OFS",
|
||||
"ALAC",
|
||||
"AIFF",
|
||||
"AIF",
|
||||
"AU",
|
||||
"SND",
|
||||
"CAF",
|
||||
"MKA",
|
||||
"MKAUDIO",
|
||||
"MKV",
|
||||
"WEBM",
|
||||
"AC3",
|
||||
"EAC3",
|
||||
"TRUEHD",
|
||||
"MLP",
|
||||
"AMR",
|
||||
"AWB",
|
||||
"RA",
|
||||
"RM",
|
||||
"MPA",
|
||||
"MPEG",
|
||||
"DSF",
|
||||
"DFF",
|
||||
"DSD",
|
||||
@ -734,8 +949,28 @@ private val ffprobeFirstFormats = setOf(
|
||||
"WV",
|
||||
"WAVPACK",
|
||||
"APE",
|
||||
"TTA",
|
||||
"TAK",
|
||||
"MPC",
|
||||
"OFR",
|
||||
"OFS",
|
||||
"WMA",
|
||||
"DTS",
|
||||
"AC3",
|
||||
"EAC3",
|
||||
"TRUEHD",
|
||||
"MLP",
|
||||
"AMR",
|
||||
"AWB",
|
||||
"MKA",
|
||||
"MKAUDIO",
|
||||
"MKV",
|
||||
"WEBM",
|
||||
"RA",
|
||||
"RM",
|
||||
"AU",
|
||||
"SND",
|
||||
"CAF",
|
||||
"DSF",
|
||||
"DFF",
|
||||
"DSD",
|
||||
@ -771,7 +1006,16 @@ private val bitDepthFallbackFormats = setOf(
|
||||
"DSF",
|
||||
"DFF",
|
||||
"DSD",
|
||||
"ISO"
|
||||
"ISO",
|
||||
"MKA",
|
||||
"MKAUDIO",
|
||||
"MKV",
|
||||
"WEBM",
|
||||
"AU",
|
||||
"SND",
|
||||
"CAF",
|
||||
"RA",
|
||||
"RM"
|
||||
)
|
||||
|
||||
private data class LocalAudioFile(
|
||||
@ -802,11 +1046,12 @@ private data class TrackMetadata(
|
||||
val sampleRateHz: Int? = null,
|
||||
val bitrate: Int? = null,
|
||||
val bitDepth: String? = null,
|
||||
val mimeType: String? = null
|
||||
val mimeType: String? = null,
|
||||
val parseFailureReason: String? = null
|
||||
)
|
||||
|
||||
private data class ScannedTrackResult(
|
||||
val track: ScannedAudioTrack,
|
||||
val track: ScannedAudioTrack?,
|
||||
val shouldPersist: Boolean
|
||||
)
|
||||
|
||||
@ -839,18 +1084,22 @@ private class TrackBatchWriter(
|
||||
}
|
||||
|
||||
private class ProgressThrottler(
|
||||
private val total: Int,
|
||||
private val onProgress: (MusicScanProgress) -> Unit
|
||||
) {
|
||||
private var lastUpdateAtMillis = 0L
|
||||
|
||||
fun update(scanned: Int) {
|
||||
val now = System.currentTimeMillis()
|
||||
if (scanned == total || now - lastUpdateAtMillis >= PROGRESS_UPDATE_INTERVAL_MS) {
|
||||
onProgress(MusicScanProgress(scanned = scanned, total = total))
|
||||
if (now - lastUpdateAtMillis >= PROGRESS_UPDATE_INTERVAL_MS) {
|
||||
onProgress(MusicScanProgress(scanned = scanned))
|
||||
lastUpdateAtMillis = now
|
||||
}
|
||||
}
|
||||
|
||||
fun flush(scanned: Int) {
|
||||
onProgress(MusicScanProgress(scanned = scanned))
|
||||
lastUpdateAtMillis = System.currentTimeMillis()
|
||||
}
|
||||
}
|
||||
|
||||
private fun android.database.Cursor.getNullableString(columnIndex: Int): String? {
|
||||
@ -858,9 +1107,104 @@ private fun android.database.Cursor.getNullableString(columnIndex: Int): String?
|
||||
return getString(columnIndex)?.takeIf { it.isNotBlank() }
|
||||
}
|
||||
|
||||
private fun logParsedTrack(track: ScannedAudioTrack, source: String, parser: String) {
|
||||
Timber.i(
|
||||
"Parsed track metadata: source=%s parser=%s path=%s title=%s artist=%s album=%s format=%s mimeType=%s durationMs=%d sampleRateHz=%s bitrate=%s bitDepth=%s playable=%s requiresFfmpeg=%s tagReadable=%s tagWritable=%s parseFailure=%s sizeBytes=%d uri=%s",
|
||||
source,
|
||||
parser,
|
||||
track.sourcePath.orEmpty().ifBlank { track.uri.toString() },
|
||||
track.title,
|
||||
track.artist.ifBlank { "unknown" },
|
||||
track.album.ifBlank { "unknown" },
|
||||
track.format,
|
||||
track.mimeType.ifBlank { "unknown" },
|
||||
track.durationMs,
|
||||
track.sampleRateHz?.toString() ?: "unknown",
|
||||
track.bitrate?.toString() ?: "unknown",
|
||||
track.bitDepth ?: "unknown",
|
||||
track.isPlayable,
|
||||
track.requiresFfmpeg,
|
||||
track.isTagReadable,
|
||||
track.isTagWritable,
|
||||
track.parseFailureReason ?: "none",
|
||||
track.sizeBytes,
|
||||
track.uri
|
||||
)
|
||||
}
|
||||
|
||||
private fun ScannedAudioTrack.withCapabilities(
|
||||
format: String,
|
||||
metadata: TrackMetadata?,
|
||||
inferMissingMetadataFailure: Boolean = true
|
||||
): ScannedAudioTrack {
|
||||
val normalized = format.uppercase()
|
||||
val resolved = AudioFormatCapability.resolve(
|
||||
format = normalized,
|
||||
parseFailureReason = metadata?.parseFailureReason,
|
||||
inferMissingMetadataFailure = inferMissingMetadataFailure,
|
||||
hasAnyMetadata = metadata?.hasAnyMetadata() == true
|
||||
)
|
||||
val capability = resolved.capability
|
||||
return copy(
|
||||
isPlayable = capability.isPlayable,
|
||||
requiresFfmpeg = capability.requiresFfmpeg,
|
||||
isTagReadable = capability.isTagReadable,
|
||||
isTagWritable = capability.isTagWritable,
|
||||
unavailableReason = capability.unavailableReason,
|
||||
parseFailureReason = resolved.parseFailureReason
|
||||
)
|
||||
}
|
||||
|
||||
private fun TrackMetadata.hasAnyMetadata(): Boolean {
|
||||
return durationMs > 0L ||
|
||||
sampleRateHz != null ||
|
||||
bitrate != null ||
|
||||
bitDepth != null ||
|
||||
title != null ||
|
||||
artist != null ||
|
||||
album != null
|
||||
}
|
||||
|
||||
private fun TrackMetadata.hasCompleteTechnicalMetadata(): Boolean {
|
||||
return parseFailureReason == null &&
|
||||
durationMs > 0L &&
|
||||
(sampleRateHz ?: 0) > 0 &&
|
||||
bitDepth.isReliableBitDepth()
|
||||
}
|
||||
|
||||
private fun TrackMetadata.parserName(format: String): String {
|
||||
val normalized = format.uppercase()
|
||||
val ffmpegSucceeded = parseFailureReason?.startsWith("FFprobe") != true &&
|
||||
(normalized !in jaudioFirstFormats || needsFfprobeFallback(format))
|
||||
return if (ffmpegSucceeded) "ffmpeg" else "jaudiotagger"
|
||||
}
|
||||
|
||||
private fun Throwable.shortReason(): String {
|
||||
val type = this::class.simpleName ?: "Error"
|
||||
val message = message?.take(LOG_PREVIEW_LIMIT)
|
||||
return if (message.isNullOrBlank()) type else "$type: $message"
|
||||
}
|
||||
|
||||
internal fun taggerExtension(displayName: String): String? {
|
||||
return displayName
|
||||
.substringAfterLast('.', missingDelimiterValue = "")
|
||||
.substringBefore('?')
|
||||
.trim()
|
||||
.lowercase()
|
||||
.takeIf { it.isNotBlank() && it.length <= MAX_TAGGER_EXTENSION_LENGTH }
|
||||
}
|
||||
|
||||
internal fun mediaStoreMusicSelection(): String {
|
||||
// 系统扫描只取 MediaStore 判定的音乐条目,铃声、通知音、闹钟音、普通录音不进入歌曲解析。
|
||||
// 用户主动选择的文件夹/U 盘仍走 SAF 扫描,用扩展名补充 MediaStore 不认识的小众格式。
|
||||
Timber.i("pathaudio/media/106041: ${MediaStore.Audio.Media.RELATIVE_PATH} MediaStore music selection: ${MediaStore.Audio.Media.IS_MUSIC} != 0 AND ${MediaStore.Audio.Media.SIZE} > 0")
|
||||
return "${MediaStore.Audio.Media.IS_MUSIC} != 0 AND ${MediaStore.Audio.Media.SIZE} > 0"
|
||||
}
|
||||
|
||||
private fun isSupportedAudioName(name: String, mimeType: String): Boolean {
|
||||
val extension = name.substringAfterLast('.', missingDelimiterValue = "").uppercase()
|
||||
return extension in supportedAudioExtensions || mimeType.startsWith("audio/")
|
||||
val normalizedMimeType = mimeType.normalizedMimeType()
|
||||
return extension in supportedAudioExtensions || normalizedMimeType?.startsWith("audio/") == true
|
||||
}
|
||||
|
||||
private fun LocalAudioFile.libraryPath(): String {
|
||||
@ -871,14 +1215,42 @@ private fun DocumentAudioFile.libraryPath(): String {
|
||||
return normalizedLibraryPath(sourcePath, uri)
|
||||
}
|
||||
|
||||
private fun LocalAudioFile.needsLocalScan(cached: ScannedAudioTrack?): Boolean {
|
||||
return scanFingerprint().needsScan(cached?.scanFingerprint())
|
||||
}
|
||||
|
||||
private fun DocumentAudioFile.needsDocumentScan(cached: ScannedAudioTrack?): Boolean {
|
||||
if (cached == null) return true
|
||||
val sourcePath = this.sourcePath
|
||||
return cached.sizeBytes != sizeBytes ||
|
||||
cached.dateModifiedSeconds != lastModifiedSeconds ||
|
||||
cached.uri != uri ||
|
||||
cached.relativePath != relativePath ||
|
||||
cached.sourcePath != sourcePath
|
||||
return scanFingerprint().needsScan(cached?.scanFingerprint())
|
||||
}
|
||||
|
||||
private fun LocalAudioFile.scanFingerprint(): AudioScanFingerprint {
|
||||
return AudioScanFingerprint(
|
||||
uri = uri.toString(),
|
||||
relativePath = relativePath,
|
||||
sourcePath = sourcePath,
|
||||
sizeBytes = sizeBytes,
|
||||
dateModifiedSeconds = dateModifiedSeconds
|
||||
)
|
||||
}
|
||||
|
||||
private fun DocumentAudioFile.scanFingerprint(): AudioScanFingerprint {
|
||||
return AudioScanFingerprint(
|
||||
uri = uri.toString(),
|
||||
relativePath = relativePath,
|
||||
sourcePath = sourcePath,
|
||||
sizeBytes = sizeBytes,
|
||||
dateModifiedSeconds = lastModifiedSeconds
|
||||
)
|
||||
}
|
||||
|
||||
private fun ScannedAudioTrack.scanFingerprint(): CachedAudioScanFingerprint {
|
||||
return CachedAudioScanFingerprint(
|
||||
uri = uri.toString(),
|
||||
relativePath = relativePath,
|
||||
sourcePath = sourcePath,
|
||||
sizeBytes = sizeBytes,
|
||||
dateModifiedSeconds = dateModifiedSeconds
|
||||
)
|
||||
}
|
||||
|
||||
private fun normalizedLibraryPath(sourcePath: String?, uri: Uri): String {
|
||||
@ -940,6 +1312,9 @@ private fun JSONObject.toTrackMetadata(mediaFormat: String): TrackMetadata {
|
||||
val formatTags = formatJson?.optJSONObject("tags")
|
||||
val streamTags = audioStream?.optJSONObject("tags")
|
||||
val sampleRateHz = audioStream.readString("sample_rate").toNumericInt()
|
||||
val codecName = audioStream.readString("codec_name")
|
||||
val formatName = formatJson.readString("format_name")
|
||||
val hasAudioStream = audioStream != null && !codecName.isNullOrBlank()
|
||||
return TrackMetadata(
|
||||
title = streamTags.readTag("title") ?: formatTags.readTag("title"),
|
||||
artist = streamTags.readTag("artist")
|
||||
@ -951,7 +1326,9 @@ private fun JSONObject.toTrackMetadata(mediaFormat: String): TrackMetadata {
|
||||
sampleRateHz = sampleRateHz,
|
||||
bitrate = audioStream.readString("bit_rate").toNumericInt()
|
||||
?: formatJson.readString("bit_rate").toNumericInt(),
|
||||
bitDepth = audioStream.toBitDepth(mediaFormat)
|
||||
bitDepth = audioStream.toBitDepth(mediaFormat),
|
||||
mimeType = ffprobeMimeType(mediaFormat, formatName, codecName),
|
||||
parseFailureReason = if (hasAudioStream) null else "FFprobe found no audio stream"
|
||||
)
|
||||
}
|
||||
|
||||
@ -999,7 +1376,8 @@ private fun mergeMetadata(primary: TrackMetadata, secondary: TrackMetadata): Tra
|
||||
sampleRateHz = primary.sampleRateHz ?: secondary.sampleRateHz,
|
||||
bitrate = primary.bitrate ?: secondary.bitrate,
|
||||
bitDepth = primary.bitDepth ?: secondary.bitDepth,
|
||||
mimeType = primary.mimeType ?: secondary.mimeType
|
||||
mimeType = primary.mimeType ?: secondary.mimeType,
|
||||
parseFailureReason = primary.parseFailureReason ?: secondary.parseFailureReason
|
||||
)
|
||||
}
|
||||
|
||||
@ -1015,7 +1393,15 @@ private fun mergeMetadataForFallback(
|
||||
sampleRateHz = ffprobeMetadata.sampleRateHz ?: taggerMetadata.sampleRateHz,
|
||||
bitrate = ffprobeMetadata.bitrate ?: taggerMetadata.bitrate,
|
||||
bitDepth = ffprobeMetadata.bitDepth ?: taggerMetadata.bitDepth,
|
||||
mimeType = ffprobeMetadata.mimeType ?: taggerMetadata.mimeType
|
||||
mimeType = ffprobeMetadata.mimeType ?: taggerMetadata.mimeType,
|
||||
parseFailureReason = when {
|
||||
ffprobeMetadata.durationMs > 0L ||
|
||||
ffprobeMetadata.sampleRateHz != null ||
|
||||
ffprobeMetadata.bitrate != null ||
|
||||
ffprobeMetadata.bitDepth != null -> null
|
||||
|
||||
else -> taggerMetadata.parseFailureReason ?: ffprobeMetadata.parseFailureReason
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@ -1085,6 +1471,48 @@ private fun String?.toMetadataValue(): String? {
|
||||
return MetadataTextRepair.repair(this)
|
||||
}
|
||||
|
||||
private fun String?.normalizedMimeType(): String? {
|
||||
return this
|
||||
?.substringBefore(';')
|
||||
?.trim()
|
||||
?.lowercase()
|
||||
?.takeIf { it.isNotBlank() }
|
||||
}
|
||||
|
||||
private fun canonicalMimeType(
|
||||
format: String,
|
||||
scannedMimeType: String,
|
||||
probedMimeType: String?
|
||||
): String {
|
||||
scannedMimeType.normalizedMimeType()
|
||||
?.takeIf { it.startsWith("audio/") }
|
||||
?.let { return it }
|
||||
probedMimeType.normalizedMimeType()
|
||||
?.takeIf { it.startsWith("audio/") }
|
||||
?.let { return it }
|
||||
return canonicalMimeTypes[format.uppercase()].orEmpty()
|
||||
}
|
||||
|
||||
private fun ffprobeMimeType(
|
||||
mediaFormat: String,
|
||||
containerName: String?,
|
||||
codecName: String?
|
||||
): String? {
|
||||
val normalizedFormat = mediaFormat.uppercase()
|
||||
canonicalMimeTypes[normalizedFormat]?.let { return it }
|
||||
val normalizedContainer = containerName.normalizedMimeType().orEmpty()
|
||||
val normalizedCodec = codecName.normalizedMimeType().orEmpty()
|
||||
return when {
|
||||
"mp3" in normalizedContainer || normalizedCodec == "mp3" -> "audio/mpeg"
|
||||
"flac" in normalizedContainer || normalizedCodec == "flac" -> "audio/flac"
|
||||
"wav" in normalizedContainer || normalizedCodec.startsWith("pcm_") -> "audio/wav"
|
||||
"ogg" in normalizedContainer || normalizedCodec in setOf("vorbis", "opus") -> "audio/ogg"
|
||||
"aac" in normalizedContainer || normalizedCodec == "aac" -> "audio/aac"
|
||||
"mp4" in normalizedContainer || "m4a" in normalizedContainer -> "audio/mp4"
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
private fun String?.toNumericInt(): Int? {
|
||||
return this
|
||||
?.filter { it.isDigit() }
|
||||
@ -1110,3 +1538,28 @@ private fun mergeTracks(
|
||||
}
|
||||
return byKey.values.sortedWith(compareByDescending<ScannedAudioTrack> { it.dateModifiedSeconds }.thenBy { it.title })
|
||||
}
|
||||
|
||||
internal fun newScannedTrackId(): Long = 0L
|
||||
|
||||
private val canonicalMimeTypes = mapOf(
|
||||
"MP3" to "audio/mpeg",
|
||||
"FLAC" to "audio/flac",
|
||||
"WAV" to "audio/wav",
|
||||
"M4A" to "audio/mp4",
|
||||
"MP4" to "audio/mp4",
|
||||
"AAC" to "audio/aac",
|
||||
"OGG" to "audio/ogg",
|
||||
"OPUS" to "audio/ogg",
|
||||
"WV" to "audio/x-wavpack",
|
||||
"WAVPACK" to "audio/x-wavpack",
|
||||
"WMA" to "audio/x-ms-wma",
|
||||
"DTS" to "audio/vnd.dts",
|
||||
"APE" to "audio/x-ape",
|
||||
"ALAC" to "audio/alac",
|
||||
"AIFF" to "audio/aiff",
|
||||
"AIF" to "audio/aiff",
|
||||
"DSF" to "audio/x-dsf",
|
||||
"DFF" to "audio/x-dff",
|
||||
"DSD" to "audio/x-dsd",
|
||||
"ISO" to "application/octet-stream"
|
||||
)
|
||||
|
||||
@ -0,0 +1,132 @@
|
||||
package com.audio.vibe.domain.model
|
||||
|
||||
data class AudioFormatCapability(
|
||||
val isPlayable: Boolean,
|
||||
val requiresFfmpeg: Boolean,
|
||||
val isTagReadable: Boolean,
|
||||
val isTagWritable: Boolean,
|
||||
val unavailableReason: String?
|
||||
) {
|
||||
companion object {
|
||||
fun fromFormat(format: String): AudioFormatCapability {
|
||||
val normalized = format.uppercase()
|
||||
val isKnown = normalized in platformPlayableFormats ||
|
||||
normalized in ffmpegRequiredFormats ||
|
||||
normalized == "AUDIO"
|
||||
val playable = isKnown
|
||||
return AudioFormatCapability(
|
||||
isPlayable = playable,
|
||||
requiresFfmpeg = normalized in ffmpegRequiredFormats,
|
||||
isTagReadable = normalized in readableTagFormats,
|
||||
isTagWritable = normalized in writableTagFormats,
|
||||
unavailableReason = if (playable) null else "Unsupported audio format"
|
||||
)
|
||||
}
|
||||
|
||||
fun resolve(
|
||||
format: String,
|
||||
parseFailureReason: String?,
|
||||
inferMissingMetadataFailure: Boolean,
|
||||
hasAnyMetadata: Boolean
|
||||
): ResolvedAudioFormatCapability {
|
||||
val resolvedParseFailure = parseFailureReason
|
||||
?: if (inferMissingMetadataFailure && !hasAnyMetadata) {
|
||||
"No readable metadata"
|
||||
} else {
|
||||
null
|
||||
}
|
||||
return ResolvedAudioFormatCapability(
|
||||
capability = fromFormat(format),
|
||||
parseFailureReason = resolvedParseFailure
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class ResolvedAudioFormatCapability(
|
||||
val capability: AudioFormatCapability,
|
||||
val parseFailureReason: String?
|
||||
)
|
||||
|
||||
private val ffmpegRequiredFormats = setOf(
|
||||
"WV",
|
||||
"WAVPACK",
|
||||
"WMA",
|
||||
"DTS",
|
||||
"APE",
|
||||
"TTA",
|
||||
"TAK",
|
||||
"MPC",
|
||||
"OFR",
|
||||
"OFS",
|
||||
"AC3",
|
||||
"EAC3",
|
||||
"TRUEHD",
|
||||
"MLP",
|
||||
"AMR",
|
||||
"AWB",
|
||||
"MKA",
|
||||
"MKAUDIO",
|
||||
"MKV",
|
||||
"WEBM",
|
||||
"RA",
|
||||
"RM",
|
||||
"AU",
|
||||
"SND",
|
||||
"CAF",
|
||||
"DSF",
|
||||
"DFF",
|
||||
"DSD",
|
||||
"ISO"
|
||||
)
|
||||
|
||||
private val platformPlayableFormats = setOf(
|
||||
"MP3",
|
||||
"FLAC",
|
||||
"WAV",
|
||||
"M4A",
|
||||
"MP4",
|
||||
"AAC",
|
||||
"OGG",
|
||||
"OPUS",
|
||||
"ALAC",
|
||||
"AIFF",
|
||||
"AIF",
|
||||
"AUDIO"
|
||||
)
|
||||
|
||||
private val readableTagFormats = setOf(
|
||||
"MP3",
|
||||
"FLAC",
|
||||
"WAV",
|
||||
"M4A",
|
||||
"MP4",
|
||||
"AAC",
|
||||
"OGG",
|
||||
"OPUS",
|
||||
"ALAC",
|
||||
"AIFF",
|
||||
"AIF",
|
||||
"WV",
|
||||
"WAVPACK",
|
||||
"APE",
|
||||
"WMA",
|
||||
"TTA",
|
||||
"TAK",
|
||||
"MPC",
|
||||
"DSF",
|
||||
"DFF",
|
||||
"DSD",
|
||||
"ISO"
|
||||
)
|
||||
|
||||
private val writableTagFormats = setOf(
|
||||
"MP3",
|
||||
"FLAC",
|
||||
"M4A",
|
||||
"MP4",
|
||||
"AAC",
|
||||
"OGG",
|
||||
"OPUS",
|
||||
"ALAC"
|
||||
)
|
||||
@ -0,0 +1,21 @@
|
||||
package com.audio.vibe.domain.model
|
||||
|
||||
import android.net.Uri
|
||||
|
||||
data class PlaybackTrack(
|
||||
val id: Long,
|
||||
val uri: Uri,
|
||||
val title: String,
|
||||
val artist: String,
|
||||
val album: String,
|
||||
val mimeType: String = "",
|
||||
val format: String,
|
||||
val sampleRateHz: Int?,
|
||||
val bitrate: Int? = null,
|
||||
val bitDepth: String? = null,
|
||||
val durationMs: Long? = null,
|
||||
val sourcePath: String? = null,
|
||||
val isPlayable: Boolean = true,
|
||||
val requiresFfmpeg: Boolean = false,
|
||||
val unavailableReason: String? = null
|
||||
)
|
||||
@ -17,7 +17,13 @@ data class ScannedAudioTrack(
|
||||
val bitDepth: String?,
|
||||
val relativePath: String?,
|
||||
val sourcePath: String?,
|
||||
val dateModifiedSeconds: Long
|
||||
val dateModifiedSeconds: Long,
|
||||
val isPlayable: Boolean = defaultCapabilityFor(format).isPlayable,
|
||||
val requiresFfmpeg: Boolean = defaultCapabilityFor(format).requiresFfmpeg,
|
||||
val isTagReadable: Boolean = defaultCapabilityFor(format).isTagReadable,
|
||||
val isTagWritable: Boolean = defaultCapabilityFor(format).isTagWritable,
|
||||
val unavailableReason: String? = defaultCapabilityFor(format).unavailableReason,
|
||||
val parseFailureReason: String? = null
|
||||
) {
|
||||
val isHighResolution: Boolean
|
||||
get() = (sampleRateHz ?: 0) >= 88_200 || bitDepth in highBitDepthLabels || format in dsdFormats
|
||||
@ -27,3 +33,6 @@ data class ScannedAudioTrack(
|
||||
private val dsdFormats = setOf("DSF", "DFF", "DSD", "ISO")
|
||||
}
|
||||
}
|
||||
|
||||
private fun defaultCapabilityFor(format: String): AudioFormatCapability =
|
||||
AudioFormatCapability.fromFormat(format)
|
||||
|
||||
@ -2,6 +2,7 @@ package com.audio.vibe.domain.repository
|
||||
|
||||
import android.net.Uri
|
||||
import androidx.paging.PagingData
|
||||
import com.audio.vibe.domain.model.PlaybackTrack
|
||||
import com.audio.vibe.domain.model.ScannedAudioTrack
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
@ -11,6 +12,8 @@ interface MusicScannerRepository {
|
||||
fun pagedAudio(query: String, sort: MusicLibrarySort): Flow<PagingData<ScannedAudioTrack>>
|
||||
suspend fun loadCachedAudio(): List<ScannedAudioTrack>
|
||||
suspend fun loadLibrarySummary(query: String = ""): MusicLibrarySummary
|
||||
suspend fun playbackQueueIds(query: String, sort: MusicLibrarySort): LongArray
|
||||
suspend fun playbackTrack(id: Long): PlaybackTrack?
|
||||
suspend fun scanAudio(onProgress: (MusicScanProgress) -> Unit): List<ScannedAudioTrack>
|
||||
suspend fun scanFolder(
|
||||
treeUri: Uri,
|
||||
@ -21,8 +24,7 @@ interface MusicScannerRepository {
|
||||
}
|
||||
|
||||
data class MusicScanProgress(
|
||||
val scanned: Int,
|
||||
val total: Int
|
||||
val scanned: Int
|
||||
)
|
||||
|
||||
data class MusicLibrarySummary(
|
||||
|
||||
@ -141,7 +141,6 @@ data class AppStrings(
|
||||
val resetLibrary: String,
|
||||
val scanning: String,
|
||||
val scannedCount: String,
|
||||
val scanProgress: String,
|
||||
val cachedLibrary: String,
|
||||
val noAudioFound: String,
|
||||
val noAudioFoundDesc: String,
|
||||
@ -299,7 +298,6 @@ private fun android.content.res.Resources.toAppStrings(): AppStrings = AppString
|
||||
resetLibrary = getString(R.string.reset_library),
|
||||
scanning = getString(R.string.scanning),
|
||||
scannedCount = getString(R.string.scanned_count),
|
||||
scanProgress = getString(R.string.scan_progress),
|
||||
cachedLibrary = getString(R.string.cached_library),
|
||||
noAudioFound = getString(R.string.no_audio_found),
|
||||
noAudioFoundDesc = getString(R.string.no_audio_found_desc),
|
||||
@ -413,7 +411,6 @@ private val fallbackStrings = AppStrings(
|
||||
resetLibrary = "",
|
||||
scanning = "",
|
||||
scannedCount = "",
|
||||
scanProgress = "",
|
||||
cachedLibrary = "",
|
||||
noAudioFound = "",
|
||||
noAudioFoundDesc = "",
|
||||
|
||||
@ -0,0 +1,9 @@
|
||||
package com.audio.vibe.ui.musicmanager
|
||||
|
||||
class LazyPlaybackControllerProvider<T>(
|
||||
private val create: suspend () -> T?
|
||||
) {
|
||||
suspend fun get(): T? {
|
||||
return create()
|
||||
}
|
||||
}
|
||||
@ -44,7 +44,9 @@ import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.collectAsState
|
||||
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.clip
|
||||
@ -60,6 +62,7 @@ import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import androidx.paging.PagingData
|
||||
import androidx.paging.compose.LazyPagingItems
|
||||
import androidx.paging.compose.collectAsLazyPagingItems
|
||||
import com.audio.vibe.data.playback.AudioPlaybackService
|
||||
import com.audio.vibe.data.repository.MusicScannerRepositoryProvider
|
||||
import com.audio.vibe.domain.model.ScannedAudioTrack
|
||||
import com.audio.vibe.ui.components.AudioVibeColors
|
||||
@ -80,13 +83,30 @@ fun MusicManagerScreen(onBack: () -> Unit = {}, toEditor: () -> Unit = {}) {
|
||||
val repository = remember(context) {
|
||||
MusicScannerRepositoryProvider.get(context.applicationContext)
|
||||
}
|
||||
val playbackControllerProvider = remember(context) {
|
||||
LazyPlaybackControllerProvider {
|
||||
AudioPlaybackService.startAndBindController(context.applicationContext)
|
||||
}
|
||||
}
|
||||
val viewModel: MusicManagerViewModel = viewModel(
|
||||
factory = MusicManagerViewModelFactory(repository)
|
||||
factory = MusicManagerViewModelFactory(repository, playbackControllerProvider)
|
||||
)
|
||||
val uiState by viewModel.uiState.collectAsState()
|
||||
val pagedTracks = viewModel.pagedTracks.collectAsLazyPagingItems()
|
||||
val strings = LocalAppStrings.current
|
||||
val permission = rememberAudioPermission()
|
||||
val notificationPermission = rememberNotificationPermission()
|
||||
var pendingPlaybackTrackId by remember { mutableStateOf<Long?>(null) }
|
||||
val notificationPermissionLauncher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.RequestPermission(),
|
||||
onResult = { granted ->
|
||||
val trackId = pendingPlaybackTrackId
|
||||
pendingPlaybackTrackId = null
|
||||
if (trackId != null) {
|
||||
viewModel.onEvent(MusicManagerEvent.PlayToggled(trackId))
|
||||
}
|
||||
}
|
||||
)
|
||||
val permissionLauncher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.RequestPermission(),
|
||||
onResult = { granted ->
|
||||
@ -138,6 +158,14 @@ fun MusicManagerScreen(onBack: () -> Unit = {}, toEditor: () -> Unit = {}) {
|
||||
uiState = uiState,
|
||||
pagedTracks = pagedTracks,
|
||||
onEvent = viewModel::onEvent,
|
||||
onPlayTrack = { trackId ->
|
||||
if (notificationPermission == null || context.hasPermission(notificationPermission)) {
|
||||
viewModel.onEvent(MusicManagerEvent.PlayToggled(trackId))
|
||||
} else {
|
||||
pendingPlaybackTrackId = trackId
|
||||
notificationPermissionLauncher.launch(notificationPermission)
|
||||
}
|
||||
},
|
||||
onRequestPermission = { permissionLauncher.launch(permission) },
|
||||
onScanFolder = { folderLauncher.launch(null) },
|
||||
toEditor = toEditor
|
||||
@ -150,6 +178,7 @@ private fun MusicManagerContent(
|
||||
uiState: MusicManagerUiState,
|
||||
pagedTracks: LazyPagingItems<ScannedAudioTrack>,
|
||||
onEvent: (MusicManagerEvent) -> Unit,
|
||||
onPlayTrack: (Long) -> Unit,
|
||||
onRequestPermission: () -> Unit,
|
||||
onScanFolder: () -> Unit,
|
||||
toEditor: () -> Unit
|
||||
@ -176,13 +205,13 @@ private fun MusicManagerContent(
|
||||
when (val state = uiState.libraryState) {
|
||||
is MusicLibraryState.Scanning -> ScanningLibrary(
|
||||
scanned = state.scanned,
|
||||
total = state.total,
|
||||
stats = state.stats,
|
||||
pagedTracks = pagedTracks,
|
||||
query = uiState.query,
|
||||
category = uiState.category,
|
||||
playingId = uiState.playingId,
|
||||
onEvent = onEvent,
|
||||
onPlayTrack = onPlayTrack,
|
||||
toEditor = toEditor
|
||||
)
|
||||
|
||||
@ -196,6 +225,7 @@ private fun MusicManagerContent(
|
||||
category = uiState.category,
|
||||
playingId = uiState.playingId,
|
||||
onEvent = onEvent,
|
||||
onPlayTrack = onPlayTrack,
|
||||
toEditor = toEditor
|
||||
)
|
||||
}
|
||||
@ -229,6 +259,7 @@ private fun LibrarySearchAndList(
|
||||
category: MusicCategory,
|
||||
playingId: Long?,
|
||||
onEvent: (MusicManagerEvent) -> Unit,
|
||||
onPlayTrack: (Long) -> Unit,
|
||||
toEditor: () -> Unit
|
||||
) {
|
||||
val strings = LocalAppStrings.current
|
||||
@ -247,7 +278,7 @@ private fun LibrarySearchAndList(
|
||||
TrackList(
|
||||
tracks = tracks,
|
||||
playingId = playingId,
|
||||
onPlay = { onEvent(MusicManagerEvent.PlayToggled(it)) },
|
||||
onPlay = onPlayTrack,
|
||||
toEditor = toEditor
|
||||
)
|
||||
}
|
||||
@ -255,17 +286,17 @@ private fun LibrarySearchAndList(
|
||||
@Composable
|
||||
private fun ScanningLibrary(
|
||||
scanned: Int,
|
||||
total: Int,
|
||||
stats: MusicLibraryStats?,
|
||||
pagedTracks: LazyPagingItems<ScannedAudioTrack>,
|
||||
query: String,
|
||||
category: MusicCategory,
|
||||
playingId: Long?,
|
||||
onEvent: (MusicManagerEvent) -> Unit,
|
||||
onPlayTrack: (Long) -> Unit,
|
||||
toEditor: () -> Unit
|
||||
) {
|
||||
val visibleStats = stats ?: MusicLibraryStats.Empty
|
||||
ScanningCard(scanned = scanned, total = total)
|
||||
ScanningCard(scanned = scanned)
|
||||
LibrarySummary(visibleStats, fromCache = true)
|
||||
LibrarySearchAndList(
|
||||
tracks = pagedTracks,
|
||||
@ -273,12 +304,13 @@ private fun ScanningLibrary(
|
||||
category = category,
|
||||
playingId = playingId,
|
||||
onEvent = onEvent,
|
||||
onPlayTrack = onPlayTrack,
|
||||
toEditor = toEditor
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ScanningCard(scanned: Int, total: Int) {
|
||||
private fun ScanningCard(scanned: Int) {
|
||||
val strings = LocalAppStrings.current
|
||||
VibeCard(modifier = Modifier.fillMaxWidth()) {
|
||||
Row(modifier = Modifier.padding(14.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
@ -299,11 +331,7 @@ private fun ScanningCard(scanned: Int, total: Int) {
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
Text(
|
||||
text = if (total > 0) {
|
||||
strings.scanProgress.format(scanned, total)
|
||||
} else {
|
||||
strings.scannedCount.format(scanned)
|
||||
},
|
||||
text = strings.scannedCount.format(scanned),
|
||||
color = AudioVibeColors.Muted,
|
||||
fontSize = 13.sp
|
||||
)
|
||||
@ -454,6 +482,7 @@ private fun StatCard(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TrackList(
|
||||
tracks: LazyPagingItems<ScannedAudioTrack>,
|
||||
@ -538,7 +567,7 @@ private fun TrackRow(
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
SpecChip(track.format)
|
||||
SpecChip(track.sampleRateLabel(strings))
|
||||
SpecChip(track.durationLabel())
|
||||
// SpecChip(track.durationLabel())
|
||||
}
|
||||
}
|
||||
IconButton(onClick = onPlay) {
|
||||
@ -578,6 +607,14 @@ private fun rememberAudioPermission(): String {
|
||||
}
|
||||
}
|
||||
|
||||
private fun rememberNotificationPermission(): String? {
|
||||
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
Manifest.permission.POST_NOTIFICATIONS
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun Context.hasPermission(permission: String): Boolean {
|
||||
return ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED
|
||||
}
|
||||
@ -655,6 +692,7 @@ private fun MusicManagerScreenPreview() {
|
||||
)
|
||||
).collectAsLazyPagingItems(),
|
||||
onEvent = {},
|
||||
onPlayTrack = {},
|
||||
onRequestPermission = {},
|
||||
onScanFolder = {},
|
||||
toEditor = {}
|
||||
|
||||
@ -6,6 +6,7 @@ import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.ViewModelProvider
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import androidx.paging.cachedIn
|
||||
import com.audio.vibe.data.playback.PlaybackServiceController
|
||||
import com.audio.vibe.domain.model.ScannedAudioTrack
|
||||
import com.audio.vibe.domain.repository.MusicLibrarySort
|
||||
import com.audio.vibe.domain.repository.MusicLibrarySummary
|
||||
@ -25,7 +26,8 @@ import kotlin.coroutines.coroutineContext
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
class MusicManagerViewModel(
|
||||
private val repository: MusicScannerRepository
|
||||
private val repository: MusicScannerRepository,
|
||||
private val playbackControllerProvider: LazyPlaybackControllerProvider<PlaybackServiceController>? = null
|
||||
) : ViewModel() {
|
||||
private val _uiState = MutableStateFlow(MusicManagerUiState())
|
||||
val uiState: StateFlow<MusicManagerUiState> = _uiState
|
||||
@ -35,6 +37,8 @@ class MusicManagerViewModel(
|
||||
.flatMapLatest { repository.pagedAudio(query = it.query, sort = it.sort) }
|
||||
.cachedIn(viewModelScope)
|
||||
private var scanJob: Job? = null
|
||||
private var observedPlaybackController: PlaybackServiceController? = null
|
||||
private var playbackStateJob: Job? = null
|
||||
|
||||
init {
|
||||
loadCachedLibrary()
|
||||
@ -49,10 +53,52 @@ class MusicManagerViewModel(
|
||||
refreshLibrarySummaryForQuery(event.query)
|
||||
}
|
||||
is MusicManagerEvent.CategoryChanged -> _uiState.update { it.copy(category = event.category) }
|
||||
is MusicManagerEvent.PlayToggled -> _uiState.update { state ->
|
||||
state.copy(playingId = if (state.playingId == event.trackId) null else event.trackId)
|
||||
is MusicManagerEvent.PlayToggled -> togglePlayback(event.trackId)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun ensurePlaybackController(): PlaybackServiceController? {
|
||||
val controller = playbackControllerProvider?.get()
|
||||
if (controller != null && observedPlaybackController !== controller) {
|
||||
playbackStateJob?.cancel()
|
||||
observedPlaybackController = controller
|
||||
playbackStateJob = viewModelScope.launch {
|
||||
observePlayback(controller)
|
||||
}
|
||||
}
|
||||
return controller
|
||||
}
|
||||
|
||||
private suspend fun observePlayback(controller: PlaybackServiceController) {
|
||||
controller.state.collect { playbackState ->
|
||||
_uiState.update { state ->
|
||||
state.copy(playingId = playbackState.currentId.takeIf { playbackState.isPlaying })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun togglePlayback(trackId: Long) {
|
||||
viewModelScope.launch {
|
||||
val controller = ensurePlaybackController()
|
||||
if (controller == null) {
|
||||
return@launch
|
||||
}
|
||||
val currentState = controller.state.value
|
||||
if (currentState.currentId == trackId) {
|
||||
controller.toggleCurrent()
|
||||
return@launch
|
||||
}
|
||||
val state = _uiState.value
|
||||
val queueIds = repository.playbackQueueIds(
|
||||
query = state.query,
|
||||
sort = state.category.toLibrarySort()
|
||||
)
|
||||
controller.playQueue(
|
||||
queueIds = queueIds,
|
||||
startTrackId = trackId,
|
||||
trackResolver = repository::playbackTrack
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun loadCachedLibrary() {
|
||||
@ -70,7 +116,6 @@ class MusicManagerViewModel(
|
||||
it.copy(
|
||||
libraryState = MusicLibraryState.Scanning(
|
||||
scanned = 0,
|
||||
total = 0,
|
||||
stats = currentStats
|
||||
)
|
||||
)
|
||||
@ -79,7 +124,7 @@ class MusicManagerViewModel(
|
||||
try {
|
||||
jobToCancel?.cancelAndJoin()
|
||||
repository.scanAudio { progress ->
|
||||
updateScanProgress(progress.scanned, progress.total, currentStats)
|
||||
updateScanProgress(progress.scanned, currentStats)
|
||||
}
|
||||
val query = _uiState.value.query
|
||||
val summary = repository.loadLibrarySummary(query)
|
||||
@ -100,13 +145,12 @@ class MusicManagerViewModel(
|
||||
}
|
||||
}
|
||||
|
||||
private fun updateScanProgress(scanned: Int, total: Int, currentStats: MusicLibraryStats?) {
|
||||
private fun updateScanProgress(scanned: Int, currentStats: MusicLibraryStats?) {
|
||||
_uiState.update { state ->
|
||||
val current = state.libraryState
|
||||
state.copy(
|
||||
libraryState = MusicLibraryState.Scanning(
|
||||
scanned = scanned,
|
||||
total = total,
|
||||
stats = if (current is MusicLibraryState.Scanning) current.stats else currentStats
|
||||
)
|
||||
)
|
||||
@ -121,7 +165,6 @@ class MusicManagerViewModel(
|
||||
it.copy(
|
||||
libraryState = MusicLibraryState.Scanning(
|
||||
scanned = 0,
|
||||
total = 0,
|
||||
stats = currentStats
|
||||
)
|
||||
)
|
||||
@ -130,7 +173,7 @@ class MusicManagerViewModel(
|
||||
try {
|
||||
jobToCancel?.cancelAndJoin()
|
||||
repository.scanFolder(uri) { progress ->
|
||||
updateScanProgress(progress.scanned, progress.total, currentStats)
|
||||
updateScanProgress(progress.scanned, currentStats)
|
||||
}
|
||||
val query = _uiState.value.query
|
||||
val summary = repository.loadLibrarySummary(query)
|
||||
@ -213,12 +256,13 @@ class MusicManagerViewModel(
|
||||
}
|
||||
|
||||
class MusicManagerViewModelFactory(
|
||||
private val repository: MusicScannerRepository
|
||||
private val repository: MusicScannerRepository,
|
||||
private val playbackControllerProvider: LazyPlaybackControllerProvider<PlaybackServiceController>? = null
|
||||
) : ViewModelProvider.Factory {
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
override fun <T : ViewModel> create(modelClass: Class<T>): T {
|
||||
if (modelClass.isAssignableFrom(MusicManagerViewModel::class.java)) {
|
||||
return MusicManagerViewModel(repository) as T
|
||||
return MusicManagerViewModel(repository, playbackControllerProvider) as T
|
||||
}
|
||||
throw IllegalArgumentException("Unknown ViewModel class: ${modelClass.name}")
|
||||
}
|
||||
@ -243,7 +287,6 @@ data class MusicManagerUiState(
|
||||
sealed interface MusicLibraryState {
|
||||
data class Scanning(
|
||||
val scanned: Int,
|
||||
val total: Int,
|
||||
val stats: MusicLibraryStats?
|
||||
) : MusicLibraryState
|
||||
|
||||
|
||||
10
app/src/main/res/drawable/ic_notification_audio.xml
Normal file
@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24">
|
||||
<path
|
||||
android:fillColor="@android:color/white"
|
||||
android:pathData="M12,3C10.9,3 10,3.9 10,5V14.3C9.4,14.1 8.7,14 8,14C5.8,14 4,15.3 4,17C4,18.7 5.8,20 8,20C10.2,20 12,18.7 12,17V8H18V5H12V3Z" />
|
||||
</vector>
|
||||
@ -76,7 +76,6 @@
|
||||
<string name="reset_library">ライブラリをリセット</string>
|
||||
<string name="scanning">ローカル音声をスキャン中...</string>
|
||||
<string name="scanned_count">%1$d 曲をスキャン済み</string>
|
||||
<string name="scan_progress">%1$d / %2$d 曲をスキャン済み</string>
|
||||
<string name="cached_library">スキャン中は保存済みライブラリを表示</string>
|
||||
<string name="no_audio_found">音声が見つかりません</string>
|
||||
<string name="scan_failed">スキャン失敗</string>
|
||||
|
||||
@ -76,7 +76,6 @@
|
||||
<string name="reset_library">라이브러리 초기화</string>
|
||||
<string name="scanning">로컬 오디오 스캔 중...</string>
|
||||
<string name="scanned_count">%1$d곡 스캔됨</string>
|
||||
<string name="scan_progress">%1$d / %2$d곡 스캔됨</string>
|
||||
<string name="cached_library">스캔 중 저장된 라이브러리 표시</string>
|
||||
<string name="no_audio_found">오디오 없음</string>
|
||||
<string name="scan_failed">스캔 실패</string>
|
||||
|
||||
@ -76,7 +76,6 @@
|
||||
<string name="reset_library">Сбросить библиотеку</string>
|
||||
<string name="scanning">Сканирование локального аудио...</string>
|
||||
<string name="scanned_count">Сканировано песен: %1$d</string>
|
||||
<string name="scan_progress">Сканировано %1$d из %2$d песен</string>
|
||||
<string name="cached_library">Показ сохраненной библиотеки во время сканирования</string>
|
||||
<string name="no_audio_found">Аудио не найдено</string>
|
||||
<string name="scan_failed">Ошибка сканирования</string>
|
||||
|
||||
@ -76,7 +76,6 @@
|
||||
<string name="reset_library">重置曲庫</string>
|
||||
<string name="scanning">正在掃描本地音訊...</string>
|
||||
<string name="scanned_count">已掃描 %1$d 首歌曲</string>
|
||||
<string name="scan_progress">已掃描 %1$d / %2$d 首歌曲</string>
|
||||
<string name="cached_library">掃描時顯示已儲存曲庫</string>
|
||||
<string name="no_audio_found">找不到音訊</string>
|
||||
<string name="scan_failed">掃描失敗</string>
|
||||
|
||||
@ -101,7 +101,6 @@
|
||||
<string name="reset_library">重置曲库</string>
|
||||
<string name="scanning">正在扫描本地音频...</string>
|
||||
<string name="scanned_count">已扫描 %1$d 首歌曲</string>
|
||||
<string name="scan_progress">已扫描 %1$d / %2$d 首歌曲</string>
|
||||
<string name="cached_library">扫描过程中显示已保存曲库</string>
|
||||
<string name="no_audio_found">未找到音频</string>
|
||||
<string name="no_audio_found_desc">请先把音乐加入设备,或在存储设置中选择其他文件夹后重新扫描。</string>
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
<resources>
|
||||
<string name="app_name">AudioVibe</string>
|
||||
<string name="playback_notification_text">Playing audio</string>
|
||||
<string name="settings">Settings</string>
|
||||
<string name="premium">Premium</string>
|
||||
<string name="back">Back</string>
|
||||
@ -101,7 +102,6 @@
|
||||
<string name="reset_library">Reset library</string>
|
||||
<string name="scanning">Scanning local audio...</string>
|
||||
<string name="scanned_count">%1$d songs scanned</string>
|
||||
<string name="scan_progress">%1$d of %2$d songs scanned</string>
|
||||
<string name="cached_library">Showing saved library while scanning</string>
|
||||
<string name="no_audio_found">No audio found</string>
|
||||
<string name="no_audio_found_desc">Add music to this device or choose another folder in storage settings, then scan again.</string>
|
||||
|
||||
182
docs/ARCHITECTURE.md
Normal file
@ -0,0 +1,182 @@
|
||||
# AudioVibe 架构全景图
|
||||
|
||||
> 自动生成于 2026-05-19 | 基于 `master` 分支最新代码
|
||||
|
||||
---
|
||||
|
||||
## 1. 技术栈总览
|
||||
|
||||
| 层级 | 技术 | 版本 |
|
||||
|:---|:---|:---|
|
||||
| **语言** | Kotlin | 2.2.10 |
|
||||
| **UI** | Jetpack Compose + Material 3 | BOM 2026.02.01 |
|
||||
| **导航** | Navigation Compose | 2.9.8 |
|
||||
| **数据库** | Room (FTS4 + Paging 3) | 2.8.3 |
|
||||
| **偏好存储** | DataStore Preferences | 1.2.0 |
|
||||
| **播放引擎** | Media3 ExoPlayer | 1.10.0 |
|
||||
| **FFmpeg** | ffmpeg-kit-min | 6.0.1 |
|
||||
| **元数据** | jaudiotagger | 3.0.1 |
|
||||
| **日志** | Timber | 5.0.1 |
|
||||
| **编译** | AGP / KSP | 9.1.1 / 2.3.4 |
|
||||
| **最低/目标 SDK** | -- | 26 / 36 |
|
||||
|
||||
---
|
||||
|
||||
## 2. 分层架构全景
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
## 3. MVVM 单向数据流
|
||||
|
||||

|
||||
|
||||
### 状态管理模型
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
## 4. 导航路由图
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
## 5. 音乐扫描管道
|
||||
|
||||

|
||||
|
||||
### 并发模型
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
## 6. 双引擎播放架构
|
||||
|
||||

|
||||
|
||||
### 播放状态机
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
## 7. 数据库表结构
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
## 8. 核心类关系图
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
## 9. 项目文件结构
|
||||
|
||||
```
|
||||
app/src/main/java/com/audio/vibe/
|
||||
│
|
||||
├── AudioVibeApp.kt # Application 初始化 (日志静默)
|
||||
├── MainActivity.kt # 单Activity + AppNavHost + CompositionLocal
|
||||
│
|
||||
├── ui/
|
||||
│ ├── theme/
|
||||
│ │ ├── Color.kt # Material3 色彩 + 品牌色 #4285F4
|
||||
│ │ ├── Type.kt # 排版 (headline 22sp / body 16sp)
|
||||
│ │ └── Theme.kt # 明暗主题 + Android12 Dynamic Color
|
||||
│ │
|
||||
│ ├── components/
|
||||
│ │ └── AudioVibeUi.kt # 10个共享组件 (VibeScreen/Card/Button/Waveform/VoiceDial...)
|
||||
│ │
|
||||
│ ├── i18n/
|
||||
│ │ └── AppLanguage.kt # 23种语言枚举 + AppStrings(100+字段) + CompositionLocal
|
||||
│ │
|
||||
│ ├── home/
|
||||
│ │ └── HomeScreen.kt # 首页: 功能网格 + 付费卡片
|
||||
│ │
|
||||
│ ├── musicmanager/
|
||||
│ │ ├── MusicManagerScreen.kt # 音乐库: 扫描/搜索/播放/分页列表
|
||||
│ │ ├── MusicManagerViewModel.kt # 状态管理 + 事件驱动
|
||||
│ │ └── LazyPlaybackControllerProvider.kt # 播放控制器懒加载
|
||||
│ │
|
||||
│ ├── editor/
|
||||
│ │ └── TagEditorScreen.kt # (Demo) 标签编辑
|
||||
│ ├── voicechanger/
|
||||
│ │ └── VoiceChangerScreen.kt # (Demo) 变声器
|
||||
│ ├── cutter/
|
||||
│ │ └── AudioCutterScreen.kt # (Demo) 音频裁剪
|
||||
│ ├── settings/
|
||||
│ │ └── SettingsScreen.kt # 设置页 + 语言切换
|
||||
│ └── premium/
|
||||
│ └── PremiumScreen.kt # (静态) 付费页
|
||||
│
|
||||
├── domain/
|
||||
│ ├── model/
|
||||
│ │ ├── ScannedAudioTrack.kt # 扫描音轨实体
|
||||
│ │ ├── PlaybackTrack.kt # 播放音轨实体
|
||||
│ │ └── AudioFormatCapability.kt # 格式能力模型
|
||||
│ └── repository/
|
||||
│ └── MusicScannerRepository.kt # 仓库接口契约
|
||||
│
|
||||
├── data/
|
||||
│ ├── local/
|
||||
│ │ ├── MusicLibraryDatabase.kt # Room DB v3 + DAO + Entity
|
||||
│ │ └── LanguagePreferences.kt # DataStore 语言偏好
|
||||
│ │
|
||||
│ ├── repository/
|
||||
│ │ ├── MediaStoreMusicScannerRepository.kt # 核心仓库实现 (~1560行)
|
||||
│ │ ├── MusicScannerRepositoryProvider.kt # 单例提供者
|
||||
│ │ ├── StoragePathResolver.kt # 路径标准化
|
||||
│ │ └── AudioScanFingerprint.kt # 增量扫描指纹
|
||||
│ │
|
||||
│ └── playback/
|
||||
│ ├── AudioPlaybackController.kt # 双引擎控制器 (~1178行)
|
||||
│ ├── AudioPlaybackService.kt # 前台服务 + 通知栏
|
||||
│ ├── PlaybackServiceController.kt # 解耦接口
|
||||
│ └── PlaybackSystemState.kt # 状态投影
|
||||
│
|
||||
└── common/
|
||||
└── text/
|
||||
└── MetadataTextRepair.kt # 元数据乱码修复 (多编码探测+评分)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 10. 国际化数据流
|
||||
|
||||

|
||||
|
||||
**23 种语言支持**: 英语, 简体中文, 繁体中文, 印地语, 西班牙语, 葡萄牙语, 印尼语, 日语, 韩语, 俄语, 阿拉伯语, 法语, 德语, 意大利语, 土耳其语, 泰语, 越南语, 马来语, 菲律宾语, 荷兰语, 波兰语, 乌克兰语, 波斯语 + 跟随系统
|
||||
|
||||
---
|
||||
|
||||
## 11. 播放通知管道
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
## 12. FFmpeg 渲染管道
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
## 13. 设计模式索引
|
||||
|
||||
| 模式 | 应用位置 | 说明 |
|
||||
|:---|:---|:---|
|
||||
| **MVVM** | MusicManagerViewModel | StateFlow + 密封类状态 + 事件驱动 |
|
||||
| **Repository** | MusicScannerRepository | 接口抽象 + 单一实现 |
|
||||
| **Singleton** | MusicLibraryDatabase, MusicScannerRepositoryProvider | 双重检查锁定 |
|
||||
| **Strategy** | AudioPlaybackController (双引擎) | 运行时选择 ExoPlayer / FFmpeg |
|
||||
| **Observer** | StateFlow.collect() | ViewModel 观察 Controller 状态 |
|
||||
| **Producer-Consumer** | 扫描管道 | Channel 解耦生产与消费 |
|
||||
| **Factory** | MusicManagerViewModelFactory | 手动 DI |
|
||||
| **Facade** | PlaybackServiceController | 简化服务交互 |
|
||||
| **Lazy Init** | LazyPlaybackControllerProvider | 按需创建播放控制器 |
|
||||
74
docs/CODEX_HANDOFF.md
Normal file
@ -0,0 +1,74 @@
|
||||
# Codex 交接摘要
|
||||
|
||||
最后更新:2026-05-15
|
||||
|
||||
新开 Codex 会话时,优先把这个文件作为短上下文。
|
||||
|
||||
## 项目
|
||||
|
||||
AudioVibe Android App。技术栈是 Kotlin + Compose + MVVM + Flow + Room/Paging 3。当前主要工作是本地音乐扫描、歌曲信息解析、播放服务、通知栏控制和音乐管理页面接线。
|
||||
|
||||
## 当前架构
|
||||
|
||||
- `MediaStoreMusicScannerRepository` 负责通过 MediaStore 和 SAF 扫描音乐。
|
||||
- MediaStore 覆盖系统已索引的常规音频。
|
||||
- SAF 覆盖用户选择的文件夹、SD 卡、U 盘和小众格式。
|
||||
- Room 的 `music_tracks` 保存音乐库数据。
|
||||
- FTS 负责搜索。
|
||||
- Paging 3 负责音乐管理列表。
|
||||
- 播放队列只保存 Room 数据库 id。
|
||||
- `PlaybackTrack` 是通过 id 查询的轻量播放投影。
|
||||
- `AudioPlaybackService` 持有唯一的 `AudioPlaybackController`。
|
||||
- UI 只能通过 `PlaybackServiceController` 调用播放能力。
|
||||
|
||||
## 必须保持的规则
|
||||
|
||||
- 不要把扫描 hash id 当作 Room 主键。
|
||||
- 新 `MusicTrackEntity` 使用 `id = 0L`,已有歌曲通过 `sourcePath` 复用旧 id。
|
||||
- MediaStore 和 SAF 的重复判断使用规范化后的 `sourcePath`,不是原始 URI。
|
||||
- 不要因为进入音乐管理页就启动播放服务。
|
||||
- 播放服务绑定失败时,不要伪造 UI 播放状态。
|
||||
- 清空曲库前必须等待旧扫描任务真正取消。
|
||||
- 通知栏不要因为播放进度 tick 每秒刷新。
|
||||
- 不要对所有普通文件都跑 FFprobe,只有必要时再用。
|
||||
- 所有对话和项目说明文档优先使用中文。
|
||||
|
||||
## 近期重要文件
|
||||
|
||||
- `app/src/main/java/com/audio/vibe/data/local/MusicLibraryDatabase.kt`
|
||||
- `app/src/main/java/com/audio/vibe/data/repository/MediaStoreMusicScannerRepository.kt`
|
||||
- `app/src/main/java/com/audio/vibe/data/repository/AudioScanFingerprint.kt`
|
||||
- `app/src/main/java/com/audio/vibe/data/repository/StoragePathResolver.kt`
|
||||
- `app/src/main/java/com/audio/vibe/data/playback/AudioPlaybackService.kt`
|
||||
- `app/src/main/java/com/audio/vibe/data/playback/AudioPlaybackController.kt`
|
||||
- `app/src/main/java/com/audio/vibe/data/playback/PlaybackServiceController.kt`
|
||||
- `app/src/main/java/com/audio/vibe/data/playback/PlaybackSystemState.kt`
|
||||
- `app/src/main/java/com/audio/vibe/domain/model/AudioFormatCapability.kt`
|
||||
- `app/src/main/java/com/audio/vibe/domain/model/PlaybackTrack.kt`
|
||||
- `app/src/main/java/com/audio/vibe/domain/model/ScannedAudioTrack.kt`
|
||||
- `app/src/main/java/com/audio/vibe/domain/repository/MusicScannerRepository.kt`
|
||||
- `app/src/main/java/com/audio/vibe/ui/musicmanager/MusicManagerScreen.kt`
|
||||
- `app/src/main/java/com/audio/vibe/ui/musicmanager/MusicManagerViewModel.kt`
|
||||
|
||||
## 当前验证命令
|
||||
|
||||
```bash
|
||||
./gradlew testDebugUnitTest
|
||||
```
|
||||
|
||||
## 建议下一步
|
||||
|
||||
1. Review 当前未提交的播放服务改动,重点看生命周期和通知栏行为。
|
||||
2. 在真机上验证 MediaStore + SAF 的去重,覆盖内置存储、SD 卡和 U 盘。
|
||||
3. 如果设备可用,补充或执行通知栏控制的设备测试。
|
||||
4. 只针对 Media3 无法可靠播放的格式继续完善 FFmpeg 播放链路。
|
||||
5. 扫描或播放架构变化后,及时更新 `docs/` 文档。
|
||||
|
||||
## 新会话最小提示词
|
||||
|
||||
```text
|
||||
请先读 docs/CODEX_HANDOFF.md、docs/PROJECT_CONTEXT.md、docs/MUSIC_SCAN_FLOW.md、docs/PLAYBACK_FLOW.md。
|
||||
当前项目是 AudioVibe Android App。所有回答用中文。不要执行 git 操作。
|
||||
本次任务是:<在这里写具体任务>。
|
||||
```
|
||||
|
||||
913
docs/KNOWLEDGE.md
Normal file
@ -0,0 +1,913 @@
|
||||
# Kotlin & Android 开发知识全景
|
||||
|
||||
> 涵盖 Kotlin 语言核心 + Jetpack Compose + Android 架构最佳实践,每个知识点附带可运行的代码示例
|
||||
|
||||
---
|
||||
|
||||
## 1. Kotlin 语言核心
|
||||
|
||||
### 1.1 基础语法
|
||||
|
||||

|
||||
|
||||
**val vs var — 不可变优先**
|
||||
|
||||
```kotlin
|
||||
val name = "Kotlin" // 不可变,类似 Java 的 final
|
||||
var count = 0 // 可变
|
||||
count = 1 // OK
|
||||
// name = "Java" // 编译错误!
|
||||
|
||||
val list = mutableListOf(1, 2, 3) // val 只是引用不可变,对象本身可以修改
|
||||
list.add(4) // OK
|
||||
```
|
||||
|
||||
**字符串模板**
|
||||
|
||||
```kotlin
|
||||
val user = "小明"
|
||||
val age = 25
|
||||
// 在字符串中直接嵌入变量,比 Java 的 "hello " + user + "..." 清晰得多
|
||||
val msg = "你好 $user,你今年 ${age}岁" // 你好 小明,你今年 25岁
|
||||
val detail = "价格: ${"%.2f".format(9.99)}" // 表达式用花括号包裹
|
||||
```
|
||||
|
||||
**when 表达式 — 比 switch 强大得多**
|
||||
|
||||
```kotlin
|
||||
// 用作语句(不需要覆盖所有分支)
|
||||
when (x) {
|
||||
1 -> println("一")
|
||||
2, 3 -> println("二或三")
|
||||
in 4..10 -> println("4到10之间") // 支持范围判断!
|
||||
else -> println("其他")
|
||||
}
|
||||
|
||||
// 用作表达式(必须覆盖所有分支,返回值)
|
||||
val desc = when (color) {
|
||||
Color.RED -> "红色"
|
||||
Color.BLUE -> "蓝色"
|
||||
else -> "未知" // sealed class 时可省略 else
|
||||
}
|
||||
|
||||
// 不传参数,替代 if-else if 链
|
||||
when {
|
||||
score >= 90 -> grade = "A"
|
||||
score >= 80 -> grade = "B"
|
||||
score >= 60 -> grade = "C"
|
||||
else -> grade = "D"
|
||||
}
|
||||
```
|
||||
|
||||
**双等号 vs 三等号**
|
||||
|
||||
```kotlin
|
||||
val a = "hello"
|
||||
val b = "hello"
|
||||
println(a == b) // true — 值比较(调用 equals)
|
||||
println(a === b) // true — 引用比较(字符串常量池)
|
||||
|
||||
val list1 = listOf(1, 2)
|
||||
val list2 = listOf(1, 2)
|
||||
println(list1 == list2) // true — 内容相同
|
||||
println(list1 === list2) // false — 不同对象
|
||||
```
|
||||
|
||||
**区间**
|
||||
|
||||
```kotlin
|
||||
for (i in 1..5) print(i) // 12345 闭区间
|
||||
for (i in 1 until 5) print(i) // 1234 左闭右开
|
||||
for (i in 5 downTo 1) print(i) // 54321 递减
|
||||
for (i in 1..10 step 2) print(i) // 13579 步长
|
||||
|
||||
if (x in 1..10) { } // 判断 x 是否在范围内
|
||||
```
|
||||
|
||||
**默认参数 + 命名参数**
|
||||
|
||||
```kotlin
|
||||
// 声明时给默认值,调用时可以按需传参
|
||||
fun greet(name: String = "世界", greeting: String = "你好") = "$greeting, $name"
|
||||
|
||||
greet() // 你好, 世界
|
||||
greet("小明") // 你好, 小明
|
||||
greet(greeting = "Hello") // Hello, 世界 — 命名参数,不依赖位置
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 1.2 类型系统
|
||||
|
||||

|
||||
|
||||
**可空类型和安全调用**
|
||||
|
||||
```kotlin
|
||||
var name: String? = null // 可空类型,加 ?
|
||||
val length = name?.length // 安全调用:name 为 null 时不执行,返回 null
|
||||
val len = name?.length ?: 0 // Elvis:左边为 null 则取右边的值
|
||||
|
||||
// 链式安全调用 — 任何一环为 null 整体返回 null
|
||||
val city = user?.address?.city?.name
|
||||
|
||||
// let 处理非空场景
|
||||
name?.let {
|
||||
println("名字长度: ${it.length}") // 只有 name 非空时才执行
|
||||
}
|
||||
|
||||
// !! 非空断言 — 危险! 为 null 时抛 NPE,尽量不用
|
||||
val force = name!!.length // 除非你 100% 确定非空
|
||||
```
|
||||
|
||||
**smart cast — 类型判断后自动转型**
|
||||
|
||||
```kotlin
|
||||
fun process(obj: Any) {
|
||||
if (obj is String) {
|
||||
println(obj.length) // 自动转为 String,无需强转!
|
||||
}
|
||||
// 取反判断
|
||||
if (obj !is Int) return
|
||||
println(obj + 1) // 自动转为 Int
|
||||
}
|
||||
|
||||
// when 中的 smart cast
|
||||
when (obj) {
|
||||
is String -> println(obj.uppercase())
|
||||
is Int -> println(obj * 2)
|
||||
is List<*> -> println(obj.size)
|
||||
}
|
||||
```
|
||||
|
||||
**typealias 类型别名 — 让代码语义更清晰**
|
||||
|
||||
```kotlin
|
||||
typealias UserId = Long
|
||||
typealias OnClick = (View) -> Unit
|
||||
|
||||
fun getUser(id: UserId) { } // 一眼看出参数是用户 ID
|
||||
val click: OnClick = { view -> /* ... */ }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 1.3 函数式编程
|
||||
|
||||

|
||||
|
||||
**高阶函数 — 函数作为参数或返回值**
|
||||
|
||||
```kotlin
|
||||
// 参数是一个函数类型: (Int) -> Boolean
|
||||
fun filterNumbers(list: List<Int>, predicate: (Int) -> Boolean): List<Int> {
|
||||
val result = mutableListOf<Int>()
|
||||
for (item in list) {
|
||||
if (predicate(item)) result.add(item)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// 调用时传入 lambda
|
||||
val even = filterNumbers(listOf(1, 2, 3, 4)) { it % 2 == 0 } // [2, 4]
|
||||
```
|
||||
|
||||
**尾随 lambda — 最后一个参数是函数时,可以放在括号外面**
|
||||
|
||||
```kotlin
|
||||
// 这两种写法等价
|
||||
list.filter({ it > 0 })
|
||||
list.filter { it > 0 } // 更简洁,Kotlin 惯用写法
|
||||
|
||||
// 多个参数时
|
||||
list.fold(0) { acc, item -> acc + item }
|
||||
```
|
||||
|
||||
**扩展函数 — 给已有类添加方法,无需继承**
|
||||
|
||||
```kotlin
|
||||
// 给 String 添加新方法
|
||||
fun String.isEmail(): Boolean = this.contains("@") && this.contains(".")
|
||||
|
||||
"test@abc.com".isEmail() // true — 就像 String 自带的方法
|
||||
|
||||
// 实际项目中的例子
|
||||
fun Context.toast(message: String) = Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
|
||||
fun View.visible() { visibility = View.VISIBLE }
|
||||
fun View.gone() { visibility = View.GONE }
|
||||
|
||||
// 泛型扩展函数
|
||||
fun <T> T?.orDefault(default: T): T = this ?: default
|
||||
val name = nullableName.orDefault("未命名")
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 1.4 异步与并发
|
||||
|
||||

|
||||
|
||||
**suspend 挂起函数**
|
||||
|
||||
```kotlin
|
||||
// suspend = 可暂停的函数,不会阻塞线程
|
||||
suspend fun fetchUser(id: Long): User {
|
||||
return withContext(Dispatchers.IO) { // 切换到 IO 线程
|
||||
api.getUser(id) // 网络请求
|
||||
} // 请求完成后自动切回原来的线程
|
||||
}
|
||||
|
||||
// 在 ViewModel 中调用
|
||||
viewModelScope.launch {
|
||||
val user = fetchUser(123) // 顺序写法,实际上是非阻塞的
|
||||
_uiState.value = UiState.Success(user)
|
||||
}
|
||||
```
|
||||
|
||||
**launch vs async**
|
||||
|
||||
```kotlin
|
||||
// launch: 不关心返回值,用于副作用操作(写数据库、发日志等)
|
||||
viewModelScope.launch {
|
||||
database.save(data) // 不等待结果
|
||||
Timber.d("保存完成")
|
||||
}
|
||||
|
||||
// async: 需要返回值,用于并行计算
|
||||
viewModelScope.launch {
|
||||
val userDef = async { api.getUser(id) } // 并行请求1
|
||||
val postsDef = async { api.getPosts(id) } // 并行请求2
|
||||
val user = userDef.await() // 等待两个结果
|
||||
val posts = postsDef.await()
|
||||
_uiState.value = UiState.Success(UserWithPosts(user, posts))
|
||||
}
|
||||
```
|
||||
|
||||
**Flow 冷流**
|
||||
|
||||
```kotlin
|
||||
// Flow 是冷流 — 每次 collect 都会重新执行
|
||||
val coldFlow = flow {
|
||||
Timber.d("开始发送") // 每次 collect 都会打印
|
||||
emit(1)
|
||||
delay(1000)
|
||||
emit(2)
|
||||
}
|
||||
|
||||
// 每次 collect 都是独立的数据流
|
||||
coldFlow.collect { Timber.d("collector1: $it") }
|
||||
coldFlow.collect { Timber.d("collector2: $it") } // 重新执行
|
||||
```
|
||||
|
||||
**StateFlow 热流 — ViewModel 中替代 LiveData**
|
||||
|
||||
```kotlin
|
||||
// StateFlow: 热流 + 始终有当前值,值不变不重复发射
|
||||
class MyViewModel : ViewModel() {
|
||||
private val _uiState = MutableStateFlow(UiState.Loading)
|
||||
val uiState: StateFlow<UiState> = _uiState.asStateFlow() // 只暴露不可变版本
|
||||
|
||||
fun loadData() {
|
||||
viewModelScope.launch {
|
||||
_uiState.value = UiState.Loading
|
||||
try {
|
||||
val data = repository.getData()
|
||||
_uiState.value = UiState.Success(data) // 值变了才通知
|
||||
} catch (e: Exception) {
|
||||
_uiState.value = UiState.Error(e.message ?: "未知错误")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// UI 层收集 — Compose 中超级简单
|
||||
// val state by viewModel.uiState.collectAsState()
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 1.5 面向对象
|
||||
|
||||

|
||||
|
||||
**data class — 一行代码搞定所有**
|
||||
|
||||
```kotlin
|
||||
// 自动生成: equals, hashCode, toString, copy, componentN
|
||||
data class User(val id: Long, val name: String, val email: String)
|
||||
|
||||
val u1 = User(1, "小明", "xm@mail.com")
|
||||
val u2 = u1.copy(name = "大明") // copy: 复制并修改部分字段
|
||||
println(u1) // User(id=1, name=小明, email=xm@mail.com)
|
||||
|
||||
// 解构声明
|
||||
val (id, name, email) = u1 // component1/2/3 自动生成
|
||||
```
|
||||
|
||||
**sealed class — 受限继承,when 可以穷尽所有分支**
|
||||
|
||||
```kotlin
|
||||
// 定义一组有限的可能状态
|
||||
sealed interface UiState {
|
||||
object Loading : UiState
|
||||
data class Success(val data: List<String>) : UiState
|
||||
data class Error(val message: String) : UiState
|
||||
}
|
||||
|
||||
// when 不需要 else,编译器会检查是否覆盖了所有分支
|
||||
fun render(state: UiState) = when (state) {
|
||||
UiState.Loading -> showLoading()
|
||||
is UiState.Success -> showList(state.data) // smart cast 自动解包
|
||||
is UiState.Error -> showError(state.message)
|
||||
}
|
||||
// 如果以后加了新状态,这里会编译报错提醒你处理,非常安全!
|
||||
```
|
||||
|
||||
**object — 单例模式**
|
||||
|
||||
```kotlin
|
||||
object NetworkConfig {
|
||||
const val BASE_URL = "https://api.example.com"
|
||||
const val TIMEOUT = 30_000L
|
||||
}
|
||||
// 直接使用
|
||||
val url = NetworkConfig.BASE_URL
|
||||
|
||||
// companion object — 类级别的静态成员
|
||||
class MyFragment {
|
||||
companion object {
|
||||
const val TAG = "MyFragment"
|
||||
fun newInstance(id: Long) = MyFragment().apply { arguments = bundleOf("id" to id) }
|
||||
}
|
||||
}
|
||||
MyFragment.TAG // 类似 Java 的 static
|
||||
val frag = MyFragment.newInstance(123)
|
||||
```
|
||||
|
||||
**by lazy — 懒加载,用到时才初始化**
|
||||
|
||||
```kotlin
|
||||
// 适用于: 初始化代价高、不一定会用到的对象
|
||||
val database by lazy {
|
||||
Room.databaseBuilder(context, AppDatabase::class.java, "app.db").build()
|
||||
}
|
||||
// 首次访问 database 时才执行初始化,之后返回缓存值
|
||||
// 线程安全: 默认 LazyThreadSafetyMode.SYNCHRONIZED
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 1.6 高级特性
|
||||
|
||||

|
||||
|
||||
**泛型型变 — 什么时候 List<Apple> 可以传给 List<Fruit>?**
|
||||
|
||||
```kotlin
|
||||
// out = 协变 = 只读不写(生产者)
|
||||
interface Source<out T> {
|
||||
fun next(): T // 只产出 T,不消费 T
|
||||
}
|
||||
val apples: Source<Apple> = SourceImpl()
|
||||
val fruits: Source<Fruit> = apples // OK: Apple 是 Fruit 的子类
|
||||
|
||||
// in = 逆变 = 只写不读(消费者)
|
||||
interface Sink<in T> {
|
||||
fun put(item: T) // 只消费 T,不产出 T
|
||||
}
|
||||
val sink: Sink<Fruit> = SinkImpl()
|
||||
val appleSink: Sink<Apple> = sink // 反过来: Fruit 的槽可以放 Apple
|
||||
|
||||
// List 源码就是: interface List<out E> — 所以 List<Apple> 可以赋值给 List<Fruit>
|
||||
// MutableList 就是: interface MutableList<E> — 没有 out/in,不可协变
|
||||
```
|
||||
|
||||
**reified — 运行时获取泛型类型**
|
||||
|
||||
```kotlin
|
||||
// 普通函数中无法获取泛型类型(JVM 类型擦除)
|
||||
// fun <T> parse(json: String): T = ... // 不知道 T 是什么
|
||||
|
||||
// inline + reified: 编译器把函数体复制到调用处,保留类型信息
|
||||
inline fun <reified T> Gson.fromJson(json: String): T {
|
||||
return fromJson(json, T::class.java) // T::class.java 在运行时可用!
|
||||
}
|
||||
|
||||
val user: User = gson.fromJson(jsonString) // 一行搞定
|
||||
```
|
||||
|
||||
**value class — 零开销包装类型**
|
||||
|
||||
```kotlin
|
||||
// 给基础类型加上语义,但运行时就是基础类型本身(无额外对象分配)
|
||||
@JvmInline
|
||||
value class UserId(val value: Long)
|
||||
|
||||
fun getUser(id: UserId) { } // 调用处明确这是用户ID
|
||||
getUser(UserId(123L)) // 运行时就是 123L,零开销!
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. 作用域函数速查
|
||||
|
||||

|
||||
|
||||
**apply — 初始化对象,返回对象本身**
|
||||
|
||||
```kotlin
|
||||
// 代替 Java 中"先 new 再 setN 个属性"
|
||||
val intent = Intent().apply {
|
||||
action = Intent.ACTION_VIEW
|
||||
data = Uri.parse("https://example.com")
|
||||
putExtra("key", "value")
|
||||
flags = Intent.FLAG_ACTIVITY_NEW_TASK
|
||||
}
|
||||
|
||||
// 编译后等价于:
|
||||
// val intent = Intent()
|
||||
// intent.action = ...
|
||||
// intent.data = ...
|
||||
// ... return intent
|
||||
```
|
||||
|
||||
**let — 空安全检查后执行操作,返回 lambda 结果**
|
||||
|
||||
```kotlin
|
||||
// ?.let: 非空才执行
|
||||
user?.let { u ->
|
||||
println("${u.name} 已登录")
|
||||
navigateToHome(u) // lambda 结果作为返回值
|
||||
}
|
||||
|
||||
// 链式处理: 一步接一步
|
||||
val result = data
|
||||
?.let { transform1(it) } // 非空 → 转换
|
||||
?.let { transform2(it) } // 非空 → 再转换
|
||||
?: "默认值" // 任意一步为 null → 兜底
|
||||
```
|
||||
|
||||
**also — 副作用操作(日志、校验),返回对象本身**
|
||||
|
||||
```kotlin
|
||||
val user = createUser().also {
|
||||
Timber.d("用户创建成功: ${it.name}") // 打印日志
|
||||
}
|
||||
|
||||
listOf(1, 2, 3)
|
||||
.filter { it > 0 }
|
||||
.also { Timber.d("过滤后有 ${it.size} 个元素") } // 中间调试
|
||||
.map { it * 2 }
|
||||
```
|
||||
|
||||
**run — 在对象上下文中执行代码块,返回 lambda 结果**
|
||||
|
||||
```kotlin
|
||||
val result = user?.run {
|
||||
if (age < 18) error("未成年") // this = user
|
||||
"${name} (${email})" // 最后一行是返回值
|
||||
} ?: "未知用户"
|
||||
```
|
||||
|
||||
### 对比速记
|
||||
|
||||
| | 引用方式 | 返回值 | 典型场景 |
|
||||
|:---|:---|:---|:---|
|
||||
| `apply` | `this` | 对象本身 | 对象初始化配置 |
|
||||
| `also` | `it` | 对象本身 | 日志、校验等副作用 |
|
||||
| `let` | `it` | lambda 结果 | 空安全链式转换 |
|
||||
| `run` | `this` | lambda 结果 | 对象内的计算 |
|
||||
|
||||
---
|
||||
|
||||
## 3. 协程核心模型
|
||||
|
||||

|
||||
|
||||
### 实际开发中的用法
|
||||
|
||||
**ViewModel 中的标准模式**
|
||||
|
||||
```kotlin
|
||||
class MusicViewModel(
|
||||
private val repository: MusicRepository
|
||||
) : ViewModel() {
|
||||
|
||||
private val _uiState = MutableStateFlow(MusicUiState())
|
||||
val uiState: StateFlow<MusicUiState> = _uiState.asStateFlow()
|
||||
|
||||
fun loadMusicList() {
|
||||
viewModelScope.launch { // 1. 绑定 ViewModel 生命周期
|
||||
_uiState.update { it.copy(isLoading = true) } // 2. 显示加载中
|
||||
try {
|
||||
val tracks = withContext(Dispatchers.IO) { // 3. IO线程读数据库
|
||||
repository.getAllTracks()
|
||||
}
|
||||
_uiState.update { // 4. 切回Main更新UI
|
||||
it.copy(isLoading = false, tracks = tracks)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
_uiState.update { it.copy(isLoading = false, error = e.message) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**并行请求 — 两个接口同时请求,等待两个都完成**
|
||||
|
||||
```kotlin
|
||||
viewModelScope.launch {
|
||||
val userDeferred = async { api.getUser(id) } // 并行发起
|
||||
val postsDeferred = async { api.getPosts(id) } // 并行发起
|
||||
val user = userDeferred.await() // 等待
|
||||
val posts = postsDeferred.await() // 等待
|
||||
_uiState.value = UiState.Success(UserProfile(user, posts))
|
||||
}
|
||||
```
|
||||
|
||||
**Flow 构建与转换**
|
||||
|
||||
```kotlin
|
||||
// 构建 Flow
|
||||
fun observeTracks(): Flow<List<Track>> = flow {
|
||||
while (true) {
|
||||
val tracks = database.getAllTracks() // 定期查询
|
||||
emit(tracks)
|
||||
delay(5000) // 5秒一次
|
||||
}
|
||||
}.flowOn(Dispatchers.IO) // 上游在IO执行
|
||||
|
||||
// Flow 操作符链
|
||||
repository.observeTracks()
|
||||
.map { tracks -> tracks.filter { it.isPlayable } } // 转换
|
||||
.catch { e -> Timber.e(e, "加载失败") } // 捕获异常
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
|
||||
// 转为 StateFlow,UI collect 时启动,无人订阅5秒后停止
|
||||
```
|
||||
|
||||
### 结构化并发速记
|
||||
|
||||
| 作用域 | 行为 | 何时用 |
|
||||
|:---|:---|:---|
|
||||
| `viewModelScope` | 自动随 ViewModel 清除取消 | ViewModel 中几乎所有协程 |
|
||||
| `lifecycleScope` | 自动随 Lifecycle 取消 | Activity/Fragment |
|
||||
| `coroutineScope { }` | 子协程失败传播到父协程 | 需要所有子协程都成功的场景 |
|
||||
| `supervisorScope { }` | 子协程独立失败 | 一个子协程失败不影响其他 |
|
||||
|
||||
---
|
||||
|
||||
## 4. Compose 声明式 UI
|
||||
|
||||

|
||||
|
||||
### Compose vs 传统 View 对比
|
||||
|
||||
```kotlin
|
||||
// 传统写法(命令式)— 你需要手动更新每个 View
|
||||
// textView.text = newName
|
||||
// progressBar.visibility = if (loading) VISIBLE else GONE
|
||||
// recyclerView.adapter?.submitList(newList)
|
||||
|
||||
// Compose 写法(声明式)— 描述"这个状态下的 UI 长什么样"
|
||||
@Composable
|
||||
fun ProfileScreen(viewModel: ProfileViewModel = viewModel()) {
|
||||
val state by viewModel.uiState.collectAsState() // 订阅状态
|
||||
|
||||
when (val s = state) { // 穷举所有状态
|
||||
is UiState.Loading -> CircularProgressIndicator()
|
||||
is UiState.Error -> Text("错误: ${s.message}", color = Color.Red)
|
||||
is UiState.Success -> {
|
||||
Text("欢迎, ${s.user.name}", style = MaterialTheme.typography.headlineMedium)
|
||||
Text(s.user.email)
|
||||
Button(onClick = { viewModel.onLogout() }) { Text("退出") }
|
||||
}
|
||||
}
|
||||
// 状态变化 → Compose 自动重组这个函数,你不需要写任何更新逻辑
|
||||
}
|
||||
```
|
||||
|
||||
### remember 和 derivedStateOf
|
||||
|
||||
```kotlin
|
||||
@Composable
|
||||
fun TrackList(tracks: List<Track>, query: String) {
|
||||
// remember: 跨越重组保留计算结果(除非 key 变化)
|
||||
val filtered = remember(tracks, query) { // tracks 或 query 变化时重新计算
|
||||
tracks.filter { it.title.contains(query, ignoreCase = true) }
|
||||
}
|
||||
|
||||
// derivedStateOf: 只在依赖的状态真正变化时才重新计算
|
||||
val isLongList by remember {
|
||||
derivedStateOf { filtered.size > 100 } // filtered 不变就不重算
|
||||
}
|
||||
|
||||
LazyColumn {
|
||||
items(filtered, key = { it.id }) { // key 让 Compose 复用 item
|
||||
TrackRow(track = it)
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 副作用 — LaunchedEffect / DisposableEffect
|
||||
|
||||
```kotlin
|
||||
// LaunchedEffect: key 变化时执行协程,自动取消上一个
|
||||
@Composable
|
||||
fun TrackDetail(trackId: Long, viewModel: TrackDetailViewModel = viewModel()) {
|
||||
LaunchedEffect(trackId) { // trackId 变化 → 取消旧协程,启动新协程
|
||||
viewModel.loadTrack(trackId)
|
||||
}
|
||||
|
||||
val track by viewModel.track.collectAsState()
|
||||
// 渲染 track...
|
||||
}
|
||||
|
||||
// DisposableEffect: 离开 Composable 时清理资源
|
||||
@Composable
|
||||
fun ObservePlayback(controller: PlaybackController) {
|
||||
DisposableEffect(controller) {
|
||||
val job = controller.observe()
|
||||
onDispose { job.cancel() } // 离开屏幕时取消订阅
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. Android MVVM 完整示例
|
||||
|
||||

|
||||
|
||||
### 完整 ViewModel 模板
|
||||
|
||||
```kotlin
|
||||
// 1. 定义状态 — 一个 sealed interface 表达所有可能的状态
|
||||
sealed interface MusicListUiState {
|
||||
object Loading : MusicListUiState
|
||||
data class Ready(
|
||||
val tracks: List<Track>,
|
||||
val isScanning: Boolean = false,
|
||||
val scanProgress: Int = 0
|
||||
) : MusicListUiState
|
||||
data class Error(val message: String) : MusicListUiState
|
||||
}
|
||||
|
||||
// 2. 定义事件 — 用户操作或系统事件
|
||||
sealed interface MusicListEvent {
|
||||
data class QueryChanged(val query: String) : MusicListEvent
|
||||
data class TrackClicked(val trackId: Long) : MusicListEvent
|
||||
object ScanRequested : MusicListEvent
|
||||
object RefreshRequested : MusicListEvent
|
||||
}
|
||||
|
||||
// 3. ViewModel — 状态容器
|
||||
class MusicListViewModel(
|
||||
private val repository: MusicRepository
|
||||
) : ViewModel() {
|
||||
|
||||
private val _uiState = MutableStateFlow<MusicListUiState>(MusicListUiState.Loading)
|
||||
val uiState: StateFlow<MusicListUiState> = _uiState.asStateFlow()
|
||||
|
||||
init { loadTracks() }
|
||||
|
||||
fun onEvent(event: MusicListEvent) = when (event) {
|
||||
is MusicListEvent.QueryChanged -> search(event.query)
|
||||
is MusicListEvent.TrackClicked -> playTrack(event.trackId)
|
||||
MusicListEvent.ScanRequested -> scanLibrary()
|
||||
MusicListEvent.RefreshRequested -> loadTracks()
|
||||
}
|
||||
|
||||
private fun loadTracks() {
|
||||
viewModelScope.launch {
|
||||
_uiState.value = MusicListUiState.Loading
|
||||
try {
|
||||
val tracks = withContext(Dispatchers.IO) { repository.getAllTracks() }
|
||||
_uiState.value = MusicListUiState.Ready(tracks = tracks)
|
||||
} catch (e: Exception) {
|
||||
_uiState.value = MusicListUiState.Error(e.message ?: "加载失败")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun search(query: String) { /* ... */ }
|
||||
private fun playTrack(id: Long) { /* ... */ }
|
||||
private fun scanLibrary() { /* ... */ }
|
||||
}
|
||||
|
||||
// 4. Screen — 纯渲染
|
||||
@Composable
|
||||
fun MusicListScreen(viewModel: MusicListViewModel = viewModel()) {
|
||||
val state by viewModel.uiState.collectAsState()
|
||||
|
||||
when (val s = state) {
|
||||
MusicListUiState.Loading -> LoadingIndicator()
|
||||
is MusicListUiState.Ready -> MusicListContent(
|
||||
tracks = s.tracks,
|
||||
onQueryChange = { viewModel.onEvent(MusicListEvent.QueryChanged(it)) },
|
||||
onTrackClick = { viewModel.onEvent(MusicListEvent.TrackClicked(it)) }
|
||||
)
|
||||
is MusicListUiState.Error -> ErrorCard(
|
||||
message = s.message,
|
||||
onRetry = { viewModel.onEvent(MusicListEvent.RefreshRequested) }
|
||||
)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 关键约束
|
||||
|
||||
| 规则 | 为什么 | 反面 |
|
||||
|:---|:---|:---|
|
||||
| ViewModel 不持有 Context | 内存泄漏 | `class VM(val ctx: Context)` |
|
||||
| 只暴露 `StateFlow` 不可变 | UI 不能改状态 | `val uiState = MutableStateFlow(...)` |
|
||||
| Repository 是唯一数据源 | UI 不直接调 API | `vmScope.launch { api.get() }` |
|
||||
| IO 操作用 `Dispatchers.IO` | 不阻塞主线程 | `runBlocking { db.load() }` |
|
||||
| 用 `viewModelScope` | 自动取消 | `GlobalScope.launch { }` |
|
||||
|
||||
---
|
||||
|
||||
## 6. Room 数据库核心用法
|
||||
|
||||
### 完整示例: 从定义到查询
|
||||
|
||||
```kotlin
|
||||
// 1. Entity — 定义表结构
|
||||
@Entity(
|
||||
tableName = "tracks",
|
||||
indices = [Index(value = ["title"])] // 给 title 字段建索引
|
||||
)
|
||||
data class TrackEntity(
|
||||
@PrimaryKey(autoGenerate = true) val id: Long = 0,
|
||||
@ColumnInfo(name = "file_path") val filePath: String, // 列名映射
|
||||
val title: String,
|
||||
val artist: String,
|
||||
val durationMs: Long
|
||||
)
|
||||
|
||||
// 2. DAO — 定义操作
|
||||
@Dao
|
||||
interface TrackDao {
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE) // 有则更新,无则插入
|
||||
suspend fun insertAll(tracks: List<TrackEntity>)
|
||||
|
||||
@Query("SELECT * FROM tracks ORDER BY title")
|
||||
fun observeAll(): Flow<List<TrackEntity>> // 返回 Flow,数据变化自动通知 UI
|
||||
|
||||
@Query("SELECT * FROM tracks WHERE title LIKE :query || '%'")
|
||||
fun searchPaged(query: String): PagingSource<Int, TrackEntity> // 分页加载大量数据
|
||||
|
||||
@Query("SELECT COUNT(*) FROM tracks")
|
||||
suspend fun count(): Int
|
||||
}
|
||||
|
||||
// 3. Database — 组装
|
||||
@Database(entities = [TrackEntity::class], version = 1)
|
||||
abstract class AppDatabase : RoomDatabase() {
|
||||
abstract fun trackDao(): TrackDao
|
||||
|
||||
companion object {
|
||||
@Volatile private var INSTANCE: AppDatabase? = null
|
||||
|
||||
fun getInstance(context: Context): AppDatabase {
|
||||
return INSTANCE ?: synchronized(this) { // 双重检查锁定
|
||||
INSTANCE ?: Room.databaseBuilder(
|
||||
context.applicationContext,
|
||||
AppDatabase::class.java,
|
||||
"app.db"
|
||||
).build().also { INSTANCE = it }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 使用
|
||||
class TrackRepository(private val dao: TrackDao) {
|
||||
fun observeTracks(): Flow<List<Track>> = dao.observeAll().map { entities ->
|
||||
entities.map { it.toDomainModel() } // 转为领域模型
|
||||
}
|
||||
|
||||
suspend fun searchTracks(query: String): PagingData<Track> =
|
||||
Pager(PagingConfig(pageSize = 50)) {
|
||||
dao.searchPaged(query) // Paging 3 集成
|
||||
}.flow.map { it.toDomainModel() }
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. Kotlin 集合操作速查
|
||||
|
||||
### 实际场景
|
||||
|
||||
```kotlin
|
||||
data class Track(val id: Long, val title: String, val artist: String, val duration: Long, val format: String)
|
||||
val tracks = listOf(
|
||||
Track(1, "晴天", "周杰伦", 269_000L, "FLAC"),
|
||||
Track(2, "七里香", "周杰伦", 300_000L, "MP3"),
|
||||
Track(3, "稻香", "周杰伦", 223_000L, "FLAC"),
|
||||
Track(4, "青花瓷", "周杰伦", 237_000L, "MP3"),
|
||||
)
|
||||
|
||||
// filter: 筛选 FLAC 格式的无损音质
|
||||
val flacTracks = tracks.filter { it.format == "FLAC" }
|
||||
|
||||
// map: 只需歌名列表
|
||||
val titles = tracks.map { it.title } // [晴天, 七里香, 稻香, 青花瓷]
|
||||
|
||||
// groupBy: 按格式分组
|
||||
val byFormat: Map<String, List<Track>> = tracks.groupBy { it.format }
|
||||
// {FLAC=[晴天, 稻香], MP3=[七里香, 青花瓷]}
|
||||
|
||||
// sortedByDescending: 按时长降序
|
||||
val longestFirst = tracks.sortedByDescending { it.duration }
|
||||
|
||||
// distinctBy: 去重(按艺术家)
|
||||
val uniqueArtists = tracks.distinctBy { it.artist }
|
||||
|
||||
// find: 找第一首 FLAC 格式的
|
||||
val firstFlac = tracks.find { it.format == "FLAC" } // Track(1, "晴天", ...)
|
||||
|
||||
// any / all / none: 条件判断
|
||||
val hasLossless = tracks.any { it.format == "FLAC" } // true
|
||||
val allFlac = tracks.all { it.format == "FLAC" } // false
|
||||
|
||||
// associate: 转为 Map
|
||||
val trackMap: Map<Long, String> = tracks.associate { it.id to it.title }
|
||||
// {1=晴天, 2=七里香, ...}
|
||||
|
||||
// partition: 一分为二
|
||||
val (flacList, mp3List) = tracks.partition { it.format == "FLAC" }
|
||||
```
|
||||
|
||||
### 链式调用 — Kotlin 最强大的集合操作方式
|
||||
|
||||
```kotlin
|
||||
// 找出时长最长的3首FLAC歌曲名称,用顿号连接
|
||||
val result = tracks
|
||||
.filter { it.format == "FLAC" } // 1. 筛选无损
|
||||
.sortedByDescending { it.duration } // 2. 按时长排序
|
||||
.take(3) // 3. 取前3
|
||||
.map { it.title } // 4. 只取歌名
|
||||
.joinToString("、") // 5. 连接为字符串
|
||||
// Result: "七里香、晴天、稻香" (假设七里香最长)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. 权限请求最佳实践
|
||||
|
||||

|
||||
|
||||
### 完整代码
|
||||
|
||||
```kotlin
|
||||
@Composable
|
||||
fun MusicManagerScreen() {
|
||||
val context = LocalContext.current
|
||||
|
||||
// 根据 Android 版本自动选择正确的权限
|
||||
val audioPermission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
Manifest.permission.READ_MEDIA_AUDIO // Android 13+
|
||||
} else {
|
||||
Manifest.permission.READ_EXTERNAL_STORAGE // Android 12-
|
||||
}
|
||||
|
||||
val audioPermissionLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.RequestPermission()
|
||||
) { granted ->
|
||||
if (granted) scanMusic() // 授予了,执行操作
|
||||
else showPermissionDenied() // 拒绝了,提示用户
|
||||
}
|
||||
|
||||
// 按钮点击时
|
||||
Button(onClick = {
|
||||
when {
|
||||
// 已有权限 → 直接扫描
|
||||
ContextCompat.checkSelfPermission(context, audioPermission) == PERMISSION_GRANTED -> scanMusic()
|
||||
// 需要解释原因(用户之前拒绝过但没选"不再询问")
|
||||
ActivityCompat.shouldShowRequestPermissionRationale(
|
||||
context as Activity, audioPermission
|
||||
) -> showRationaleDialog {
|
||||
audioPermissionLauncher.launch(audioPermission)
|
||||
}
|
||||
// 首次申请
|
||||
else -> audioPermissionLauncher.launch(audioPermission)
|
||||
}
|
||||
}) { Text("扫描音乐") }
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 附录: 常用速查索引
|
||||
|
||||
| 类别 | 关键词 |
|
||||
|:---|:---|
|
||||
| 协程 | `suspend` `launch` `async` `SupervisorJob` `coroutineScope` `withContext` |
|
||||
| Flow | `flow { }` `StateFlow` `SharedFlow` `stateIn` `shareIn` `combine` `flatMapLatest` |
|
||||
| Compose | `remember` `mutableStateOf` `derivedStateOf` `LaunchedEffect` `DisposableEffect` |
|
||||
| Room | `@Entity` `@Dao` `@Query` `@Transaction` `@Fts4` `PagingSource` |
|
||||
| 集合 | `map` `filter` `groupBy` `sortedBy` `fold` `flatMap` `distinctBy` `partition` |
|
||||
| 作用域函数 | `apply`(初始化) `let`(空安全) `also`(日志) `run`(计算) `takeIf`(条件) |
|
||||
120
docs/MUSIC_SCAN_FLOW.md
Normal file
@ -0,0 +1,120 @@
|
||||
# 音乐扫描流程
|
||||
|
||||
最后更新:2026-05-15
|
||||
|
||||
## 入口
|
||||
|
||||
音乐扫描由 `MusicManagerViewModel` 发起。
|
||||
|
||||
- `ScanRequested` 调用 `repository.scanAudio(...)`
|
||||
- `scanFolder(uri)` 调用 `repository.scanFolder(uri, ...)`
|
||||
- `ResetRequested` 会先对当前扫描任务执行 `cancelAndJoin()`,确认旧扫描停止后再清空 Room。
|
||||
|
||||
UI 应该在扫描过程中继续展示已有音乐库。扫描进度和分页列表是两条状态线,扫描写入 Room 后,Paging 列表应逐步反映新增歌曲。
|
||||
|
||||
## 系统音乐扫描
|
||||
|
||||
相关文件:
|
||||
|
||||
- `MediaStoreMusicScannerRepository.scanAudio`
|
||||
|
||||
流程:
|
||||
|
||||
1. 查询 MediaStore 中的音频候选文件。
|
||||
2. 为每个候选文件生成统一音乐库 key,也就是 `libraryPath()`。
|
||||
3. 根据 `sourcePath` 从 Room 读取缓存歌曲。
|
||||
4. 通过 `LocalAudioFile.needsLocalScan(...)` 过滤真正需要扫描的文件。
|
||||
5. 只有新增、修改或路径信息变化的文件进入元数据解析 worker。
|
||||
6. 多个 worker 并发解析歌曲信息。
|
||||
7. `TrackBatchWriter` 分批写入 Room。
|
||||
8. 写入后仓库重新加载并更新缓存流。
|
||||
|
||||
重要行为:
|
||||
|
||||
- 未变化的 MediaStore 缓存歌曲不应该计入本次扫描 `total`。
|
||||
- URI 或路径信息变化时仍应进入处理流程,以便 Room 中的记录保持最新。
|
||||
- 重复判断使用 `sourcePath`,不是原始 URI。
|
||||
|
||||
## SAF 文件夹 / 外置存储扫描
|
||||
|
||||
相关文件:
|
||||
|
||||
- `MediaStoreMusicScannerRepository.scanFolder`
|
||||
|
||||
流程:
|
||||
|
||||
1. 遍历用户选择的 SAF 目录树。
|
||||
2. 收集受支持的音频文件,包括 MediaStore 不一定索引的小众格式。
|
||||
3. 通过 `StoragePathResolver` 规范化存储路径。
|
||||
4. 根据 `sourcePath` 从 Room 读取缓存歌曲。
|
||||
5. 使用 `DocumentAudioFile.needsDocumentScan(...)` 过滤真正需要扫描的文件。
|
||||
6. 和系统扫描一样解析元数据并分批写入 Room。
|
||||
|
||||
重要行为:
|
||||
|
||||
- 同一首歌的 SAF URI 和 MediaStore URI 可能不同。
|
||||
- 去重必须使用规范化后的 `sourcePath`。
|
||||
- 不能假设外置存储路径一定是 `/sdcard`。
|
||||
- 需要考虑多张 SD 卡或多个 USB 存储设备。
|
||||
|
||||
## 歌曲信息解析策略
|
||||
|
||||
核心目标:在保证准确度的前提下控制扫描速度。
|
||||
|
||||
当前方向:
|
||||
|
||||
1. 对 jaudiotagger 支持较好的格式,优先使用 jaudiotagger。
|
||||
2. 对 jaudiotagger 不支持的格式,或关键技术字段缺失/异常的文件,使用 FFprobe。
|
||||
3. DSD 没有普通 PCM 位深概念,统一显示为 `1-bit DSD`。
|
||||
4. DSD 采样率规则:
|
||||
- DSD64:2822400
|
||||
- DSD128:5644800
|
||||
- DSD256:11289600
|
||||
- DSD512:22579200
|
||||
5. 元数据文本经过 `MetadataTextRepair` 修复,重点覆盖日语、韩语、俄语和 Google Play 常见国家语言。
|
||||
|
||||
## 能力标识
|
||||
|
||||
相关文件:
|
||||
|
||||
- `AudioFormatCapability.kt`
|
||||
|
||||
能力字段:
|
||||
|
||||
- `isPlayable`:是否可播放
|
||||
- `requiresFfmpeg`:是否必须走 FFmpeg 播放链路
|
||||
- `isTagReadable`:歌曲信息是否可读
|
||||
- `isTagWritable`:歌曲信息是否可写
|
||||
- `unavailableReason`:不可用原因
|
||||
- `parseFailureReason`:解析失败原因
|
||||
|
||||
注意:歌曲信息解析失败不等于歌曲不可播放。如果格式本身支持播放,即使元数据不完整,也应该保留播放能力。
|
||||
|
||||
## Room / FTS / Paging
|
||||
|
||||
相关文件:
|
||||
|
||||
- `MusicLibraryDatabase.kt`
|
||||
|
||||
当前模型:
|
||||
|
||||
- `music_tracks`:主表。
|
||||
- `music_tracks_fts`:FTS 表,声明了 `contentEntity = MusicTrackEntity::class`。
|
||||
- 列表查询返回 `PagingSource`。
|
||||
- 搜索查询使用 FTS。
|
||||
- 播放队列查询只返回 id。
|
||||
|
||||
重要 id 规则:
|
||||
|
||||
- 新扫描歌曲写入 `MusicTrackEntity` 时必须使用 `id = 0L`。
|
||||
- DAO 的 `upsertTracks` 会通过 `sourcePath` 查已有记录,并复用已有数据库 id。
|
||||
- 不要把路径 hash 或扫描临时 id 写入 Room 主键。
|
||||
|
||||
## 已知风险
|
||||
|
||||
- FFprobe 明显慢于 jaudiotagger,不能对所有普通歌曲都执行。
|
||||
- SAF 遍历 SD 卡或 U 盘时可能较慢,并发数需要受控。
|
||||
- 过多并行 FFmpeg 任务会影响存储、CPU 和电量。
|
||||
- MediaStore 与 SAF 的路径规范化必须保持一致。
|
||||
- DAO 写入策略变化时,需要重新确认 FTS 是否保持同步。
|
||||
|
||||
124
docs/PLAYBACK_FLOW.md
Normal file
@ -0,0 +1,124 @@
|
||||
# 播放流程
|
||||
|
||||
最后更新:2026-05-15
|
||||
|
||||
## 当前方向
|
||||
|
||||
播放由服务统一管理。
|
||||
|
||||
外部调用方只能使用 `PlaybackServiceController`,不能直接创建或持有 `AudioPlaybackController`。这样可以保证多个页面共用同一个播放引擎,并且生命周期由 `AudioPlaybackService` 控制。
|
||||
|
||||
## 音乐管理页到播放服务
|
||||
|
||||
相关文件:
|
||||
|
||||
- `MusicManagerScreen.kt`
|
||||
- `MusicManagerViewModel.kt`
|
||||
- `LazyPlaybackControllerProvider.kt`
|
||||
|
||||
流程:
|
||||
|
||||
1. 用户点击歌曲行的播放按钮。
|
||||
2. ViewModel 调用 `ensurePlaybackController()`。
|
||||
3. Provider 懒启动并绑定 `AudioPlaybackService`。
|
||||
4. Service 通过 Binder 返回 `PlaybackServiceController`。
|
||||
5. ViewModel 按当前搜索词和分类,从仓库查询播放队列 id。
|
||||
6. ViewModel 调用 `controller.playQueue(queueIds, startTrackId, repository::playbackTrack)`。
|
||||
7. ViewModel 观察 controller 的 `state`,并把当前播放歌曲映射到 UI 的 `playingId`。
|
||||
|
||||
重要行为:
|
||||
|
||||
- 进入音乐管理页不应该启动播放服务。
|
||||
- 如果绑定服务失败,UI 不能伪造正在播放状态。
|
||||
- 当前播放队列应该等于当前可见查询/分类顺序。
|
||||
- 播放队列只保存 id,歌曲详情播放时再从 Room 查询。
|
||||
|
||||
## Service 层
|
||||
|
||||
相关文件:
|
||||
|
||||
- `AudioPlaybackService.kt`
|
||||
|
||||
职责:
|
||||
|
||||
- 持有唯一的 `AudioPlaybackController`。
|
||||
- 只对外暴露 `PlaybackServiceController`。
|
||||
- 管理平台 `MediaSession`。
|
||||
- 创建和更新媒体通知栏。
|
||||
- 处理通知栏、锁屏、耳机按键触发的动作:
|
||||
- 播放 / 暂停
|
||||
- 下一首
|
||||
- 上一首
|
||||
- seek
|
||||
- 停止
|
||||
- App 任务被移除时,通过 `android:stopWithTask="true"` 和 `onTaskRemoved` 停止服务。
|
||||
|
||||
生命周期方向:
|
||||
|
||||
- App 退到后台时,服务可以继续存在,让通知栏能恢复暂停的播放。
|
||||
- 用户从后台任务中移除 App 时,服务应停止并释放播放资源。
|
||||
|
||||
## Controller 层
|
||||
|
||||
相关文件:
|
||||
|
||||
- `AudioPlaybackController.kt`
|
||||
|
||||
职责:
|
||||
|
||||
- 维护播放队列 id 和当前 index。
|
||||
- 根据 id 从 Room 懒加载 `PlaybackTrack`。
|
||||
- 选择 Media3 或 FFmpeg 播放链路。
|
||||
- 通过 `StateFlow` 发布 `PlaybackState`。
|
||||
- 处理下一首、上一首、seek、停止、释放。
|
||||
|
||||
播放后端:
|
||||
|
||||
- `Media3`:常见格式和系统解码链路。
|
||||
- `FfmpegAudioTrack`:FFmpeg 解码 PCM 后写入 AudioTrack,用于必须 FFmpeg 的格式或 Media3 不稳定参数。
|
||||
|
||||
## 格式路由
|
||||
|
||||
Media3 链路:
|
||||
|
||||
- MP3、FLAC、WAV、M4A、MP4、AAC、OGG、OPUS、ALAC、AIFF/AIF,以及稳定的常规音频。
|
||||
|
||||
FFmpeg 链路:
|
||||
|
||||
- `AudioFormatCapability` 中标记为 `requiresFfmpeg` 的格式。
|
||||
- WV、WMA、DTS、APE、TTA、TAK、MPC、AC3/EAC3、TrueHD/MLP、AMR/AWB、RA/RM、AU/SND、CAF、DSF/DFF/DSD/ISO、MKA/MKV/WebM 等。
|
||||
- 8-bit 或 64-bit 位深标签。
|
||||
- 可能不稳定的 24-bit packed PCM 容器。
|
||||
- 不在稳定 Media3 采样率集合里的采样率。
|
||||
|
||||
## 输出参数策略
|
||||
|
||||
播放应尽量保留原始采样率和位深。设备不支持时:
|
||||
|
||||
- 不为了“好看”向上转换低规格参数。
|
||||
- 只在实际播放兼容性需要时转换。
|
||||
- FFmpeg 输出当前通过 `OutputAudioCapabilities` 选择系统支持的采样率和编码。
|
||||
- 日志需要打印原始参数和实际输出参数。
|
||||
|
||||
## 通知栏 / MediaSession
|
||||
|
||||
当前优化方向:
|
||||
|
||||
- MediaSession 状态包含播放进度锚点。
|
||||
- 通知栏可见状态不包含高频变化的 position 字段。
|
||||
- 通知栏只在可见内容变化时刷新:
|
||||
- 标题
|
||||
- 歌手
|
||||
- 播放 / 暂停状态
|
||||
- 错误
|
||||
- 是否有队列
|
||||
- 连续进度推进交给 MediaSession 的播放状态,不要每秒调用 `NotificationManager.notify()`。
|
||||
|
||||
## 已知风险
|
||||
|
||||
- FFmpeg PCM 链路当前使用 AudioTrack,不是 Oboe。
|
||||
- seek 当前主要支持 Media3;FFmpeg seek 还需要单独扩展。
|
||||
- 服务绑定会启动服务,因此必须保持懒加载,只在播放动作发生时触发。
|
||||
- 通知栏动作文案仍需检查多语言。
|
||||
- Android 13+ 需要处理通知权限,否则通知栏可能不可见。
|
||||
|
||||
101
docs/PROJECT_CONTEXT.md
Normal file
@ -0,0 +1,101 @@
|
||||
# AudioVibe 项目上下文
|
||||
|
||||
最后更新:2026-05-15
|
||||
|
||||
## 产品定位
|
||||
|
||||
AudioVibe 是面向海外用户的 Android 音频编辑与变声 App。当前重点是本地音乐库扫描、歌曲信息解析、播放服务、通知栏控制和音乐管理页面。
|
||||
|
||||
产品方向已经移除云端能力,后续以本地优先为核心。音乐库需要支持常见格式,也要覆盖 DSD、WV、WMA、DTS、ISO、APE、TTA、TAK、MPC、AC3/EAC3、TrueHD、AMR、RA、CAF、AU、MKA/MKV/WebM 等小众格式。
|
||||
|
||||
## 技术栈
|
||||
|
||||
- Kotlin
|
||||
- Jetpack Compose,不新增 XML 布局
|
||||
- MVVM
|
||||
- Coroutine / Flow / StateFlow
|
||||
- Room + Paging 3
|
||||
- 常规播放使用 Media3 ExoPlayer
|
||||
- 小众格式播放使用 FFmpegKit 解码 PCM,再走 AudioTrack 输出
|
||||
- 歌曲信息解析使用 jaudiotagger + FFprobe
|
||||
- 日志统一使用 Timber
|
||||
|
||||
## 主要模块
|
||||
|
||||
- `common/text`
|
||||
- `MetadataTextRepair.kt`:修复歌曲标题、歌手、专辑等元数据乱码。
|
||||
|
||||
- `data/local`
|
||||
- `MusicLibraryDatabase.kt`:Room 数据库、`MusicTrackEntity`、FTS 表、DAO 查询、PagingSource、播放投影、实体映射。
|
||||
- `LanguagePreferences.kt`:保存 App 语言选项。
|
||||
|
||||
- `data/repository`
|
||||
- `MediaStoreMusicScannerRepository.kt`:音乐扫描、MediaStore 扫描、SAF 文件夹扫描、歌曲信息解析、能力标识、Room 写入。
|
||||
- `StoragePathResolver.kt`:统一解析内置存储、SD 卡、U 盘等路径。
|
||||
- `AudioScanFingerprint.kt`:判断文件是否需要重新扫描的纯函数。
|
||||
- `MusicScannerRepositoryProvider.kt`:音乐库仓库单例入口。
|
||||
|
||||
- `data/playback`
|
||||
- `AudioPlaybackService.kt`:Android 播放服务、MediaSession、通知栏、对外播放接口。
|
||||
- `AudioPlaybackController.kt`:真实播放引擎、播放队列、Media3、FFmpeg PCM 到 AudioTrack、播放状态。
|
||||
- `PlaybackServiceController.kt`:服务对外暴露的窄接口,外部不应该直接拿到 `AudioPlaybackController`。
|
||||
- `PlaybackSystemState.kt`:通知栏和 MediaSession 状态映射。
|
||||
|
||||
- `domain/model`
|
||||
- `ScannedAudioTrack.kt`:完整的已扫描歌曲模型。
|
||||
- `PlaybackTrack.kt`:播放专用的轻量歌曲投影。
|
||||
- `AudioFormatCapability.kt`:格式能力表,包含是否可播放、是否需要 FFmpeg、标签是否可读写等。
|
||||
|
||||
- `domain/repository`
|
||||
- `MusicScannerRepository.kt`:扫描、分页、摘要、播放队列 id 的仓库契约。
|
||||
|
||||
- `ui/musicmanager`
|
||||
- `MusicManagerScreen.kt`:Compose 音乐管理页面。
|
||||
- `MusicManagerViewModel.kt`:扫描状态、搜索/分类状态、播放状态接线。
|
||||
- `LazyPlaybackControllerProvider.kt`:只有真正播放时才启动并绑定播放服务。
|
||||
|
||||
## 当前数据模型方向
|
||||
|
||||
- Room 的 `MusicTrackEntity.id` 是数据库自增 id。
|
||||
- 扫描阶段可以临时生成 hash id,但新写入数据库时必须使用 `id = 0L`。
|
||||
- 已有歌曲通过规范化后的 `sourcePath` 匹配,并复用数据库里已有 id。
|
||||
- 播放队列只保存数据库 id,避免几万首歌曲时持有完整对象列表。
|
||||
- MediaStore 和 SAF 的重复判断统一使用 `sourcePath`,不能使用原始 URI。
|
||||
|
||||
## 当前交互方向
|
||||
|
||||
- 音乐管理页是扫描和展示音乐库的主入口。
|
||||
- 系统音乐扫描使用 MediaStore,覆盖常规系统已索引音频。
|
||||
- 文件夹/外置存储扫描使用 SAF,补充小众格式、SD 卡、U 盘。
|
||||
- 扫描过程中,已扫描歌曲应实时进入列表。
|
||||
- 摘要数量应和当前查询/列表状态一致。
|
||||
- 播放应通过服务和通知栏延续,不应因为退出音乐管理页就停止。
|
||||
|
||||
## 重要约束
|
||||
|
||||
- 所有回答和项目文档优先使用中文。
|
||||
- 新增 UI 文案应放到字符串资源或现有 i18n 管理里。
|
||||
- 不硬编码颜色、尺寸、用户可见文案。
|
||||
- 遵循现有项目结构,保持最小改动。
|
||||
- 禁用 LiveData,只用 Flow / StateFlow。
|
||||
- ViewModel 不持有 Context。
|
||||
- Repository 是音乐库唯一数据源,UI 不直接访问 MediaStore 或 Room。
|
||||
- 不执行 `git reset`、`git checkout` 等可能覆盖用户改动的操作。
|
||||
|
||||
## 验证基线
|
||||
|
||||
常用命令:
|
||||
|
||||
```bash
|
||||
./gradlew testDebugUnitTest
|
||||
```
|
||||
|
||||
近期重点测试覆盖:
|
||||
|
||||
- 歌曲信息乱码修复
|
||||
- 音频格式能力标识
|
||||
- 播放状态和系统状态映射
|
||||
- 播放服务懒绑定
|
||||
- 扫描缓存指纹过滤
|
||||
- Room 实体 id 映射
|
||||
|
||||
59
docs/REVIEW_CHECKLIST.md
Normal file
@ -0,0 +1,59 @@
|
||||
# Review 检查清单
|
||||
|
||||
最后更新:2026-05-15
|
||||
|
||||
检查扫描、播放、Room 或音乐管理相关改动时使用此清单。
|
||||
|
||||
## 扫描
|
||||
|
||||
- MediaStore 扫描不会把未变化缓存歌曲计入本次扫描进度。
|
||||
- SAF 扫描和 MediaStore 扫描使用同一套重复判断规则。
|
||||
- 重复判断使用规范化后的 `sourcePath`,不是原始 URI。
|
||||
- 外置存储逻辑不假设路径一定是 `/sdcard`。
|
||||
- 多张 SD 卡或多个 U 盘不会映射到同一个 key。
|
||||
- FFprobe 不会对每个普通文件都执行。
|
||||
- 歌曲信息解析失败不会直接让受支持格式变成不可播放。
|
||||
- DSD 位深按 `1-bit DSD` 处理。
|
||||
- DSD 采样率能映射到真实 DSD 采样率。
|
||||
- 乱码修复覆盖日语、韩语、俄语和 Google Play 常见语言样本。
|
||||
|
||||
## Room / Paging / FTS
|
||||
|
||||
- 新扫描记录不会把 hash id 写入 `MusicTrackEntity.id`。
|
||||
- 已有记录通过 `sourcePath` 复用数据库 id。
|
||||
- 搜索稳定使用 FTS。
|
||||
- DAO 写入策略变化时,要确认 FTS 新鲜度。
|
||||
- 分页查询返回 `PagingSource`,不要一次性返回完整列表。
|
||||
- 播放队列使用 id,不使用完整歌曲对象。
|
||||
|
||||
## 播放
|
||||
|
||||
- UI 不直接创建 `AudioPlaybackController`。
|
||||
- 只有 `AudioPlaybackService` 持有 controller。
|
||||
- 音乐管理页只在用户请求播放时启动/绑定服务。
|
||||
- 绑定失败时不伪造 `playingId`。
|
||||
- 播放队列顺序等于当前可见查询/分类顺序。
|
||||
- 歌曲详情通过 id 懒加载。
|
||||
- Media3 负责常规稳定格式。
|
||||
- FFmpeg PCM 链路负责必须 FFmpeg 的格式。
|
||||
- 不支持的输出参数只在播放兼容性需要时转换。
|
||||
- 日志打印原始参数和实际输出参数。
|
||||
|
||||
## 通知栏 / MediaSession
|
||||
|
||||
- 通知栏不会因为每次进度 tick 刷新。
|
||||
- MediaSession 在播放、暂停、seek、切歌、错误、时长变化时更新进度锚点。
|
||||
- 通知栏动作调用 service/controller,不依赖 UI。
|
||||
- Android 13+ 通知权限需要被考虑。
|
||||
- 前台服务类型是 `mediaPlayback`。
|
||||
- App 任务被移除时服务会停止。
|
||||
|
||||
## 音乐管理 UI
|
||||
|
||||
- 扫描过程中已有歌曲保持可见。
|
||||
- 摘要数量和当前查询/列表状态一致。
|
||||
- 搜索栏和分类栏不会因为扫描消失。
|
||||
- 重置会先取消扫描,再清空数据库。
|
||||
- 新增 UI 不硬编码用户可见字符串。
|
||||
- 新增页面或组件时保留 Compose Preview。
|
||||
|
||||
1
docs/diagrams/arch-1.svg
Normal file
|
After Width: | Height: | Size: 23 KiB |
1
docs/diagrams/arch-10.svg
Normal file
|
After Width: | Height: | Size: 22 KiB |
1
docs/diagrams/arch-11.svg
Normal file
|
After Width: | Height: | Size: 21 KiB |
1
docs/diagrams/arch-12.svg
Normal file
|
After Width: | Height: | Size: 26 KiB |
1
docs/diagrams/arch-13.svg
Normal file
|
After Width: | Height: | Size: 19 KiB |
1
docs/diagrams/arch-2.svg
Normal file
|
After Width: | Height: | Size: 28 KiB |
1
docs/diagrams/arch-3.svg
Normal file
|
After Width: | Height: | Size: 17 KiB |
1
docs/diagrams/arch-4.svg
Normal file
|
After Width: | Height: | Size: 19 KiB |
1
docs/diagrams/arch-5.svg
Normal file
|
After Width: | Height: | Size: 118 KiB |
1
docs/diagrams/arch-6.svg
Normal file
|
After Width: | Height: | Size: 16 KiB |
1
docs/diagrams/arch-7.svg
Normal file
|
After Width: | Height: | Size: 62 KiB |
1
docs/diagrams/arch-8.svg
Normal file
|
After Width: | Height: | Size: 15 KiB |
1
docs/diagrams/arch-9.svg
Normal file
|
After Width: | Height: | Size: 29 KiB |
1
docs/diagrams/knowledge-1.svg
Normal file
|
After Width: | Height: | Size: 12 KiB |
1
docs/diagrams/knowledge-10.svg
Normal file
|
After Width: | Height: | Size: 14 KiB |
1
docs/diagrams/knowledge-11.svg
Normal file
|
After Width: | Height: | Size: 16 KiB |
1
docs/diagrams/knowledge-2.svg
Normal file
|
After Width: | Height: | Size: 11 KiB |
1
docs/diagrams/knowledge-3.svg
Normal file
|
After Width: | Height: | Size: 11 KiB |
1
docs/diagrams/knowledge-4.svg
Normal file
|
After Width: | Height: | Size: 12 KiB |
1
docs/diagrams/knowledge-5.svg
Normal file
|
After Width: | Height: | Size: 11 KiB |
1
docs/diagrams/knowledge-6.svg
Normal file
|
After Width: | Height: | Size: 11 KiB |
1
docs/diagrams/knowledge-7.svg
Normal file
|
After Width: | Height: | Size: 12 KiB |
1
docs/diagrams/knowledge-8.svg
Normal file
|
After Width: | Height: | Size: 13 KiB |
1
docs/diagrams/knowledge-9.svg
Normal file
|
After Width: | Height: | Size: 10 KiB |
@ -20,6 +20,8 @@ ksp = "2.3.4"
|
||||
paging = "3.3.6"
|
||||
jaudiotagger = "3.0.1"
|
||||
ffmpegKit = "6.0.1"
|
||||
media3 = "1.10.0"
|
||||
timber = "5.0.1"
|
||||
|
||||
[libraries]
|
||||
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
|
||||
@ -54,6 +56,8 @@ androidx-paging-runtime = { group = "androidx.paging", name = "paging-runtime",
|
||||
androidx-paging-compose = { group = "androidx.paging", name = "paging-compose", version.ref = "paging" }
|
||||
jaudiotagger = { group = "net.jthink", name = "jaudiotagger", version.ref = "jaudiotagger" }
|
||||
ffmpeg-kit-min = { group = "io.github.maitrungduc1410", name = "ffmpeg-kit-min", version.ref = "ffmpegKit" }
|
||||
androidx-media3-exoplayer = { group = "androidx.media3", name = "media3-exoplayer", version.ref = "media3" }
|
||||
timber = { group = "com.jakewharton.timber", name = "timber", version.ref = "timber" }
|
||||
|
||||
[plugins]
|
||||
android-application = { id = "com.android.application", version.ref = "agp" }
|
||||
|
||||
@ -79,16 +79,22 @@ AI轻量化:本地AI变声(低延迟、保护隐私)+ 本地多格式播
|
||||
|
||||
文件导入:支持本地音频文件导入,可通过“文件夹选择”“全部扫描”两种方式,自动识别本地音频文件;MVP需覆盖 mp3、flac、wav、m4a/mp4、aac、ogg/opus,扩展支持 wv(WavPack)、ape、alac、aiff、DSD(dsf/dff)等小众/无损格式
|
||||
|
||||
入口与选歌:标签编辑模块应复用音乐库扫描结果,支持从 Music Manager 的歌曲列表、歌曲详情页和播放页直接进入编辑;也支持在标签编辑页内搜索/选择歌曲,避免用户重复导入同一批文件
|
||||
|
||||
单文件标签编辑:
|
||||
|
||||
基础标签:歌手、专辑名、歌曲名、流派、发行年份、歌词、曲目号、碟号、作曲、备注(支持手动输入/粘贴,自动保存草稿)
|
||||
|
||||
歌曲信息兼容:按音频格式展示可编辑字段与写回能力,至少覆盖 MP3 ID3、FLAC/Ogg/Opus Vorbis Comment、M4A/MP4 atoms、WAV INFO/BWF、WV/APE APEv2、DSF ID3;DFF 等写入风险高的格式允许只读查看或保存到本地资料库/sidecar 文件
|
||||
|
||||
编辑页结构:手机端采用“歌曲概览 + 分组表单 + 底部保存栏”的单列结构;平板端可采用左侧歌曲列表、右侧编辑表单的分栏结构;表单按“基础信息、专辑与封面、歌词、技术信息、格式能力”分组,技术信息默认只读
|
||||
|
||||
封面编辑:支持从本地相册选择图片、拍摄图片作为封面,支持裁剪、缩放,自动适配音频封面尺寸
|
||||
|
||||
乱码修复:一键修复标签乱码(适配海外多语言,支持英文、中文、日文、韩文等),支持常见编码误判修复与预览确认
|
||||
|
||||
乱码修复交互:修复前必须展示“原文本/修复后文本”对比,用户确认后才写入草稿;支持撤销本次修复,避免误伤已经正确的 Unicode 标签
|
||||
|
||||
批量标签编辑(免费版限制:最多5个文件/次;专业版无限制):
|
||||
|
||||
批量修改歌手、专辑名、流派
|
||||
@ -99,7 +105,7 @@ AI轻量化:本地AI变声(低延迟、保护隐私)+ 本地多格式播
|
||||
|
||||
保存与导出:编辑完成后,默认安全写回原文件(先写临时文件,成功后替换),可选择“另存为”;对写入能力受限的格式提供只读提示或本地 sidecar 标签文件,支持查看编辑历史
|
||||
|
||||
交互要求:导入文件速度≤3秒(10个常见格式文件以内),标签编辑实时保存草稿,封面预览清晰;遇到 DSD、WV、APE 等大文件/小众格式时显示解析进度与格式能力提示,操作流程简洁(最多3步完成单文件编辑)
|
||||
交互要求:导入文件速度≤3秒(10个常见格式文件以内),标签编辑实时保存草稿,封面预览清晰;遇到 DSD、WV、APE 等大文件/小众格式时显示解析进度与格式能力提示;单文件编辑核心路径应控制在“选歌 -> 修改 -> 保存”三步内;保存前展示写回风险、目标格式和失败恢复方式
|
||||
|
||||
4.1.3 变声工具模块(核心娱乐+实用功能)
|
||||
|
||||
@ -151,7 +157,15 @@ AI轻量化:本地AI变声(低延迟、保护隐私)+ 本地多格式播
|
||||
|
||||
高规格音频播放:支持高采样率与不同位深歌曲播放,优先保持原始采样率/位深输出;当设备或输出链路不支持时,自动进行高质量重采样/位深转换,并在播放详情中提示“原始规格”和“当前输出规格”
|
||||
|
||||
交互要求:扫描速度≤5秒(100首常见格式歌曲),分类清晰,搜索响应≤0.5秒;DSD、WV、高采样率 FLAC/WAV/ALAC 等大文件允许后台渐进式解析,不阻塞主界面
|
||||
底部播放条:音乐管理页底部固定展示迷你播放条,显示封面缩略图、歌曲名、歌手、播放/暂停按钮和基础进度;没有播放内容时隐藏或展示轻量空态;点击播放条进入完整播放页
|
||||
|
||||
完整播放页:播放页展示大封面、歌曲名、歌手、专辑、格式、采样率、位深、码率、时长、播放链路(Media3 直出、Media3 系统解码、FFmpeg PCM 兜底、重采样/位深转换等);支持进度拖动、播放/暂停、上一曲、下一曲;播放失败时展示失败原因和可尝试操作
|
||||
|
||||
通知栏与锁屏控制:播放时需要显示系统媒体通知,包含封面、歌曲名、歌手、播放/暂停、上一曲、下一曲和停止/关闭入口;通知栏、锁屏媒体控件、底部播放条和完整播放页必须共享同一播放状态;Android 13+ 需适配通知权限,Android 8.0+ 需使用前台服务通知渠道,用户拒绝通知权限时仍允许前台播放页控制,但后台播放能力需给出清晰提示
|
||||
|
||||
播放队列与状态:播放页和底部播放条共享同一播放状态;从搜索结果或分类列表播放时,应按当前列表顺序形成队列;切换搜索/分类不应打断正在播放的队列,除非用户主动播放新歌曲
|
||||
|
||||
交互要求:扫描速度≤5秒(100首常见格式歌曲),分类清晰,搜索响应≤0.5秒;底部播放条状态更新延迟≤300ms,通知栏媒体状态同步延迟≤500ms,进度拖动响应≤200ms;DSD、WV、高采样率 FLAC/WAV/ALAC 等大文件允许后台渐进式解析,不阻塞主界面
|
||||
|
||||
4.1.6 基础设置模块
|
||||
|
||||
@ -245,7 +259,9 @@ AI变声(2-3个自然款):真人女声、真人男声、旁白音(无机
|
||||
|
||||
5.2 关键页面交互细节
|
||||
|
||||
标签编辑页:点击标签输入框,弹出键盘(支持多语言输入);封面预览支持双击放大,点击“保存”后弹出“保存成功”提示,自动返回上一级
|
||||
标签编辑页:从音乐库、歌曲详情或播放页进入时直接加载当前歌曲;页面顶部展示歌曲概览和格式能力,中部按基础信息、专辑封面、歌词、技术信息分组编辑,底部固定保存栏展示保存、另存为、撤销草稿;点击标签输入框弹出键盘(支持多语言输入);封面预览支持双击放大;点击保存前展示写回方式和风险,保存成功后刷新音乐库和播放页信息,不强制返回上一级
|
||||
|
||||
音乐管理与播放页:音乐管理页底部固定迷你播放条,点击进入完整播放页;播放页支持拖动进度、播放/暂停、上一曲、下一曲,展示歌曲基础信息、原始规格、当前输出规格、播放链路和失败原因;播放状态应在列表、底部播放条、播放页之间保持一致
|
||||
|
||||
变声页:实时变声模式下,点击“开始录制”按钮变色,录制过程中显示时长,点击“停止”后自动预览变声效果,支持“重新录制”“保存”“分享”三个按钮
|
||||
|
||||
@ -333,7 +349,11 @@ Android版本:支持Android 8.0(API 26)及以上版本(覆盖90%以上
|
||||
|
||||
6. 文件访问:Android 10+ 使用 MediaStore + SAF 文件夹授权,持久化 URI 权限;大文件解析和波形生成统一在 Dispatchers.IO/后台任务执行,主线程只接收进度状态。
|
||||
|
||||
7. 播放状态架构:建立 AudioPlayerRepository,封装 Media3 Player、NativeDecoder、AudioFocus、播放队列和进度 Flow;UI 页面只订阅 PlayerUiState,不直接操作播放器实例。
|
||||
7. 播放状态架构:建立统一播放服务/播放仓库边界,封装 Media3 Player、FFmpeg PCM 兜底、AudioFocus、播放队列、播放进度和错误 Flow;Music Manager 底部播放条、完整播放页、后续变声/剪辑预览都应复用同一播放状态源,UI 页面只订阅 PlayerUiState,不直接操作播放器实例。
|
||||
|
||||
8. 播放页能力展示:播放页必须展示当前播放链路、原始音频规格、实际输出规格、是否发生重采样/位深转换、是否使用 FFmpeg 兜底;这些信息来自播放层和扫描层的结构化状态,不通过字符串拼接临时推断。
|
||||
|
||||
9. 通知栏与锁屏媒体控制:播放服务需要接入 MediaSession/媒体通知,保证通知栏、锁屏控件、耳机/蓝牙媒体按键、底部播放条和完整播放页共享同一队列与播放状态;通知栏必须支持播放/暂停、上一曲、下一曲、停止/关闭,并正确处理 Android 13+ 通知权限、Android 8.0+ 通知渠道和前台服务生命周期。
|
||||
|
||||
歌曲信息编辑方案:
|
||||
|
||||
@ -353,12 +373,14 @@ Android版本:支持Android 8.0(API 26)及以上版本(覆盖90%以上
|
||||
|
||||
8. 安全写入策略:所有可写格式统一走“读取原文件 -> 写入临时文件 -> 校验标签和音频头 -> 原子替换或另存为”的流程;SAF 文件无法原子替换时使用用户授权 URI 写回,并保留失败恢复提示。
|
||||
|
||||
9. 标签编辑与音乐库联动:标签保存成功后应刷新 Room 中对应歌曲的展示信息、搜索索引和播放页信息;若写回失败但 sidecar 保存成功,UI 需要显示“本地资料库已保存,原文件未修改”的状态。
|
||||
|
||||
七、迭代规划(3个月MVP上线,分3个迭代)
|
||||
|
||||
| 迭代周期 | 时间( weeks) | 核心开发内容 | 验收标准 |
|
||||
| --- | --- | --- | --- |
|
||||
| 迭代1(基础框架) | 1-4 | 1. 首页、设置、用户中心基础界面开发;2. 音频标签编辑模块(基础功能);3. 本地音乐管理模块;4. 基础权限适配、文件扫描功能 | 1. 界面流畅,无卡顿;2. 可正常扫描本地音频文件;3. 单文件标签编辑、乱码修复功能正常;4. 音乐分类、搜索功能正常 |
|
||||
| 迭代2(核心功能) | 5-8 | 1. 变声工具模块(免费版基础音效、实时/离线变声);2. 音频剪辑模块(基础功能);3. 多格式播放/转换能力;4. 分享功能(对接短视频平台) | 1. 变声效果正常,无杂音、低延迟;2. 基础剪辑、去噪功能正常;3. 格式转换成功;4. 可一键分享到目标平台 |
|
||||
| 迭代1(基础框架) | 1-4 | 1. 首页、设置、用户中心基础界面开发;2. 音频标签编辑模块(基础功能);3. 本地音乐管理模块;4. 基础权限适配、文件扫描功能;5. 底部播放条、完整播放页和通知栏媒体控制 | 1. 界面流畅,无卡顿;2. 可正常扫描本地音频文件;3. 单文件标签编辑、乱码修复功能正常;4. 音乐分类、搜索功能正常;5. 可播放、暂停、上一曲、下一曲和拖动进度,播放页展示基础信息与播放链路;6. 通知栏/锁屏控件可控制播放并与 App 内状态同步 |
|
||||
| 迭代2(核心功能) | 5-8 | 1. 变声工具模块(免费版基础音效、实时/离线变声);2. 音频剪辑模块(基础功能);3. 多格式播放/转换能力;4. 分享功能(对接短视频平台);5. 标签编辑批量能力和写回稳定性增强 | 1. 变声效果正常,无杂音、低延迟;2. 基础剪辑、去噪功能正常;3. 格式转换成功;4. 可一键分享到目标平台;5. 标签编辑失败可恢复,音乐库信息能同步刷新 |
|
||||
| 迭代3(高级功能+付费+合规) | 9-12 | 1. 高级本地功能开发(本地变声、批量编辑无限制、更多格式支持等);2. 付费模块对接(Google Play/App Store);3. 合规模块(隐私政策、版权提示);4. bug修复、性能优化、多语言适配 | 1. 高级功能正常解锁,付费流程顺畅;2. 隐私合规、版权合规达标;3. 多语言适配正常;4. 崩溃率≤0.5%,性能达标 |
|
||||
|
||||
八、风险与应对措施
|
||||
|
||||
@ -8,7 +8,7 @@ You动态色彩);无冗余元素、无强制广告,色调采用清新高
|
||||
3卡片式布局,顶部采用沉浸式状态栏设计,左侧显示App名称(AudioVibe,字体加粗,搭配轻微阴影提升层次感),右侧依次为设置入口(简约线性齿轮图标,24dp,hover时有轻微色彩变化)、用户中心入口(简约圆形头像图标,支持自定义头像预览,点击有波纹反馈),无任何多余装饰;核心区域为4个功能卡片,采用圆角10px设计(贴合海外主流审美),卡片采用轻微渐变底色+细边框,色彩区分明显且低饱和(如标签编辑用浅蓝、变声工具用浅紫),每个卡片搭配统一线性图标(24dp,线条粗细1.5px,与功能强关联,如标签编辑用简约标签图标、变声工具用人声波形图标,图标与文字居中对齐),卡片尺寸适配单手点击(宽度占屏幕1/2-2/3,间距均匀);底部为极简提示栏,浅灰色背景,包含“升级专业版”文字(浅灰色,字号12sp,无突兀感)、帮助入口(简约线性问号图标,20dp)、隐私政策文字链接(浅灰色,字号12sp);整体背景为低饱和纯色(浅色模式:米白#F8F9FA/浅灰#E9ECEF;深色模式:深灰#1E1E2E/黑色#121212),无任何广告弹窗或冗余元素,页面加载采用淡入动效,视觉层次清晰,核心功能入口有轻微悬浮感,提升点击欲望。
|
||||
2.2 音频标签编辑模块UI提示词
|
||||
简约高级的编辑界面,顶部采用沉浸式设计,左侧为线性返回按钮(24dp,点击有波纹反馈),中间为标题(Tag
|
||||
Editor,字体加粗,18sp),右侧为保存/另存为按钮(简约文字按钮,与主题色一致,hover时有背景色变化);采用左右分栏布局(平板适配更友好,手机端可切换为上下布局),左侧为本地音频文件列表(简洁列表样式,显示歌曲名、歌手,字体清晰,选中状态有主题色细边框+轻微背景色,无多余装饰),右侧为编辑区域;编辑区域留白充足,包含标签输入框(歌手、专辑名、歌曲名等,输入框采用圆角8px,浅灰细边框,聚焦时切换为主题色边框,无多余装饰,输入时显示简约光标)、封面预览区(方形,尺寸适中,采用轻微阴影提升立体感,支持双击放大,底部有“更换封面”“裁剪”简约文字按钮,按钮hover时有背景色变化)、乱码修复按钮(简约文字按钮,颜色与主题色一致,点击有轻微缩放反馈);批量编辑模式下,顶部新增“批量选择”“批量应用”按钮(线性图标+文字,布局紧凑不拥挤,按钮样式与整体统一);整体色调统一,操作区域分区明确,无冗余元素,标签编辑流程清晰,符合移动端操作习惯,支持多语言输入适配,文字无截断、无错乱,输入框有占位提示(浅灰色,简洁明了)。
|
||||
Editor,字体加粗,18sp),右侧为更多操作按钮(线性三点图标,24dp),保存不放在顶部孤立按钮中,而是使用底部固定保存栏;手机端采用单列编辑流程,顶部为歌曲概览区(封面缩略图、歌曲名、歌手、格式能力标签,如“MP3 可写入”“DSF 只读”“Sidecar”),下方为分组表单:基础信息、专辑与封面、歌词、技术信息、格式能力;基础信息分组包含歌曲名、歌手、专辑、流派、年份、曲目号等输入框,输入框采用圆角8px、浅灰细边框,聚焦时切换为主题色边框,键盘弹出时底部保存栏自动避让;专辑与封面分组提供大封面预览、更换封面、裁剪按钮,按钮用线性图标+短文字,保持紧凑;歌词分组使用多行输入框,支持长文本滚动;技术信息分组默认只读,展示格式、采样率、位深、码率、声道、时长和来源路径,不允许用户误改编码参数;格式能力分组展示可读、可写、可嵌入封面、可写歌词、需要 sidecar 等能力,使用低饱和标签和简短说明;乱码修复采用独立预览弹窗或底部面板,左右/上下展示“原文本”和“修复后文本”,用户确认后才写入草稿,必须提供撤销入口;底部固定保存栏包含保存、另存为、撤销草稿,保存时展示进度和写回结果,失败时给出保留原文件、保存到本地资料库或另存为的选项;平板端可采用左侧歌曲列表、右侧编辑表单的分栏结构,但手机端不使用拥挤的双栏;整体色调统一,操作区域分区明确,支持多语言输入,文字无截断、无错乱。
|
||||
2.3 变声工具模块UI提示词
|
||||
顶部采用沉浸式设计,左侧为线性返回按钮(24dp,点击有波纹反馈),中间为标题(Voice
|
||||
Changer,字体加粗,18sp);顶部下方为实时变声、离线变声切换标签(简约胶囊式切换按钮,选中状态采用主题色底色+白色文字,未选中状态为浅灰底色+深色文字,切换时有平滑过渡动效);核心区域分为音效选择区与音频预览区,音效选择区采用网格布局(2-3列,适配不同屏幕),每个音效对应简约线性图标+文字(图标24dp,文字14sp),免费版与专业版音效有轻微视觉区分(专业版音效加“Pro”标识,标识采用浅灰色小字体,无突兀感,或用细边框区分);音频预览区采用简约动态波形图(浅色模式为主题色,深色模式为高对比度亮色,波形流畅无卡顿),显示音频时长(字体12sp,浅灰色);实时变声模式下,新增圆形麦克风录制按钮(突出显示,直径48dp,主题色底色,搭配白色麦克风图标,点击有明显缩放+波纹反馈,录制时显示动态进度圈)、变声强度调节滑块(简约线性滑块,滑块头部为圆形,拖动流畅,有轻微阻尼感,底部有强度数值提示);离线变声模式下,新增文件导入按钮(简约线性图标+文字,图标24dp,与整体风格统一,点击有反馈);底部为音量调节、语速调节滑块(与变声强度滑块样式一致,排列紧凑,间距均匀),以及保存、分享按钮(分享按钮关联TikTok/Instagram/YouTube简约线性图标,24dp,排列整齐);整体设计简洁有质感,操作逻辑清晰,重点突出音效选择和录制/导入功能,无杂音、无冗余元素,深色模式下波形图显示清晰,适配夜间使用,所有按钮hover时有统一的视觉反馈,提升交互质感。
|
||||
@ -17,11 +17,15 @@ Changer,字体加粗,18sp);顶部下方为实时变声、离线变声切
|
||||
Cutter,字体加粗,18sp);底部为剪辑操作按钮栏(浅灰底色,无多余装饰),包含剪切、拼接、去噪、音量均衡功能(每个功能为“线性图标+文字”组合,图标24dp,文字14sp,排列紧凑,间距均匀,选中状态采用主题色,点击有轻微缩放反馈);核心区域为音频timeline(线性布局,占屏幕高度1/3,背景为浅灰,清晰显示动态音频波形,波形颜色与主题色一致),支持双指缩放、拖拽选择剪辑区域(选中区域采用主题色半透明底色,有细边框,区分明显);左侧为文件导入按钮(简约线性图标,24dp,点击有波纹反馈),右侧为格式转换选择框(简约圆角下拉框,无多余装饰,下拉选项采用简约列表,选中时有主题色提示);剪辑过程中显示“处理中”简约提示(无复杂动画,仅文字+简约加载图标,居中显示),处理完成后显示预览按钮(主题色文字按钮,点击有反馈);整体布局合理,timeline操作流畅,按钮大小适配单手点击,色调统一,无冗余元素,重点突出剪辑操作和timeline调整,适配不同屏幕尺寸(手机、平板),横屏/竖屏切换无界面错乱,timeline拖拽有轻微阻尼感,提升操作手感,参考GitHub高星音频剪辑项目UI质感。
|
||||
2.5 音乐管理模块UI提示词
|
||||
顶部采用沉浸式设计,左侧为线性返回按钮(24dp,点击有波纹反馈),中间为标题(Music
|
||||
Manager,字体加粗,18sp),右侧为简约圆角搜索框(占屏幕宽度2/3,placeholder提示“搜索歌曲/歌手”,浅灰色,无多余装饰,聚焦时有主题色边框,输入时显示清除按钮);核心区域为分类标签(专辑、歌手、流派,简约文字标签,字体14sp,选中状态有主题色下划线+轻微文字加粗,未选中状态为浅灰色,切换时有平滑过渡),下方为对应分类的音频列表(简约列表样式,每个列表项包含专辑封面缩略图、歌曲名、歌手,封面清晰无模糊,采用圆角8px,有轻微阴影);列表支持流畅滑动、批量选择(长按选中,显示删除、编辑标签按钮,按钮样式与整体统一,有视觉反馈),每个列表项右侧有播放/暂停按钮(简约线性图标,24dp,点击有波纹反馈);整体设计简洁有层次,分类清晰,搜索框视觉突出,列表加载流畅(有渐进式加载动效),无冗余元素,适配大量音频文件显示,深色/浅色模式下文字与背景对比度适中(符合无障碍设计),易读性强,列表项hover时有轻微背景色变化,提升交互体验,参考海外热门音乐管理App
|
||||
Manager,字体加粗,18sp),右侧为简约圆角搜索框(占屏幕宽度2/3,placeholder提示“搜索歌曲/歌手”,浅灰色,无多余装饰,聚焦时有主题色边框,输入时显示清除按钮);核心区域为分类标签(歌曲、专辑、歌手、流派、格式,简约文字标签,字体14sp,选中状态有主题色下划线+轻微文字加粗,未选中状态为浅灰色,切换时有平滑过渡),下方为音频列表(简约列表样式,每个列表项包含专辑封面缩略图、歌曲名、歌手、格式/高规格标签,封面清晰无模糊,采用圆角8px);列表支持流畅滑动、批量选择(长按选中,显示删除、编辑标签按钮,按钮样式与整体统一,有视觉反馈),每个列表项右侧有播放/暂停按钮(简约线性图标,24dp,点击有波纹反馈),点击歌曲主体进入歌曲详情或编辑入口;页面底部固定迷你播放条,位于系统导航栏上方,显示封面缩略图、歌曲名、歌手、播放/暂停按钮和细进度条,播放条高度控制在56-64dp,不遮挡列表最后一项,列表底部需预留同等 padding;迷你播放条点击进入完整播放页,左右滑动播放条可切换上一首/下一首(如实现成本高可后续迭代);整体设计简洁有层次,分类清晰,搜索框视觉突出,列表加载流畅(有渐进式加载动效),无冗余元素,适配大量音频文件显示,深色/浅色模式下文字与背景对比度适中(符合无障碍设计),易读性强,列表项hover时有轻微背景色变化,提升交互体验,参考海外热门音乐管理App
|
||||
UI设计。
|
||||
2.6 付费页面UI提示词
|
||||
2.6 播放页UI提示词
|
||||
完整播放页采用沉浸式音乐播放界面,顶部为返回按钮、标题或当前队列名称、更多操作按钮;主视觉区显示大尺寸专辑封面,封面为圆角12px以内,居中展示,不使用夸张阴影或复杂背景;封面下方展示歌曲名、歌手、专辑,标题最多两行,超长文本使用自然换行或省略,不能遮挡控制区;中部为播放进度条,支持拖动 seek,左右显示当前时间和总时长,拖动时显示准确时间反馈;核心控制区包含上一曲、播放/暂停、下一曲三个主按钮,播放/暂停按钮视觉最大但保持 Material 3 简洁风格,按钮使用线性或填充图标,不使用文字按钮代替常见图标;信息区展示格式、采样率、位深、码率、声道、原始规格、当前输出规格、播放链路(如 Media3、系统解码、FFmpeg PCM、重采样/位深转换),信息以紧凑列表或低饱和标签呈现,不做大面积卡片堆叠;播放失败时在信息区展示明确原因和可操作入口,如重试、另存为兼容格式、查看详情;播放页需要支持深色模式,夜间观看不刺眼,封面、文字和控制按钮保持足够对比度;从底部播放条进入和返回时使用轻量滑入/滑出动效,状态保持连续。
|
||||
2.7 通知栏与锁屏媒体控制UI提示词
|
||||
系统媒体通知采用 Android 标准 MediaStyle,不做自定义复杂布局;通知内容显示专辑封面、歌曲名、歌手,操作按钮包含上一曲、播放/暂停、下一曲,必要时提供停止/关闭入口;通知图标使用单色线性小图标,深浅色系统通知中都保持可读;通知状态必须与 App 内底部播放条和完整播放页同步,暂停、切歌、播放失败时文案和按钮状态及时更新;锁屏媒体控件沿用系统样式,显示封面、歌曲名、歌手和基础控制;Android 13+ 未授权通知权限时,App 内应以简洁提示说明后台控制受限,不使用强制弹窗或阻塞式引导;通知渠道名称和说明保持简洁,避免营销化文案;播放停止后通知应及时移除或切换为可恢复播放状态,不能残留错误歌曲信息。
|
||||
2.8 付费页面UI提示词
|
||||
简约高级,无冗余装饰,顶部采用沉浸式设计,左侧为线性返回按钮(24dp,点击有波纹反馈),中间为标题(Premium,字体加粗,18sp);核心区域为两种付费模式卡片(专业版、高级订阅),卡片采用圆角12px,轻微渐变底色+细边框,色彩与首页功能卡片色调一致(低饱和高级色),卡片有轻微悬浮感(阴影细腻),清晰显示付费价格(字体加粗,突出显示)、解锁权益(用简约对勾图标+文字,分点列出,清晰易读,对勾图标与主题色一致);免费版与付费版权益对比采用简约表格样式(无多余边框,文字清晰,付费版权益用主题色标注,对比鲜明);卡片下方为“购买”按钮(突出显示,主题色底色,白色文字,圆角8px,点击有明显缩放+波纹反馈),新增7天免费试用提示(浅灰色文字,12sp,标注“试用期结束自动扣费,可提前取消”,无突兀感);底部为退款政策、隐私政策文字链接(浅灰色,12sp,排列整齐,不突兀);整体设计无广告,重点突出付费权益和购买入口,流程清晰,符合海外用户付费习惯,视觉上简洁高级,无压迫感,卡片布局对称,间距均匀,加入细微动效(如卡片hover时有轻微上浮),提升质感,参考海外主流App付费页面设计逻辑。
|
||||
2.7 设置/基础功能UI提示词
|
||||
2.9 设置/基础功能UI提示词
|
||||
简约列表布局,顶部为标题(Settings,字体加粗,18sp),每个设置项为“线性图标+文字”样式(图标24dp,线条粗细1.5px,与功能强关联,统一居左),包含主题设置、语言设置、存储设置、帮助与反馈、隐私政策等;设置项排列整齐,间距均匀,选中状态有轻微主题色背景(低饱和),无多余装饰,点击有波纹反馈;语言选择、主题选择采用简约弹窗样式(圆角10px,浅灰底色,无复杂动画,选项排列整齐,选中时有主题色提示);帮助与反馈页面包含FAQ列表(简约列表,点击可展开详情,展开时有平滑过渡动效)、联系客服入口(邮箱线性图标+文字,文字与主题色一致)、意见反馈输入框(简约圆角8px,浅灰边框,聚焦时变色,有占位提示);整体设计简洁有层次,操作流畅,无冗余元素,适配多语言显示,文字无截断,符合移动端设置页面使用习惯,所有弹窗、列表切换有平滑过渡动效,提升交互质感,参考GitHub高星App设置页面布局与交互。
|
||||
三、视觉规范补充提示词(统一设计标准,强化设计感)
|
||||
•
|
||||
|
||||