commit
APK
diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml
new file mode 100644
index 0000000..32e1e2b
--- /dev/null
+++ b/.github/workflows/android.yml
@@ -0,0 +1,100 @@
+name: android
+
+# Builds and publishes the SIGNED native Android APK (apps/android) on its own,
+# independently of the Tauri desktop `release` workflow. This is the real
+# music-player APK: a WebView shell around the site plus a native Media3
+# playback service (background/locked playback + a media notification), which
+# the Tauri build could not provide.
+#
+# Reuses the SAME repo secrets the Tauri android job uses:
+# ANDROID_KEY_ALIAS, ANDROID_KEY_PASSWORD, ANDROID_KEY_BASE64
+#
+# Trigger manually from the Actions tab and give it a tag (e.g. android-v1.0.0).
+on:
+ workflow_dispatch:
+ inputs:
+ version:
+ description: "Release tag to create, e.g. android-v1.0.0"
+ required: true
+ type: string
+ siteUrl:
+ description: "Override the site the WebView loads (optional)"
+ required: false
+ type: string
+
+jobs:
+ apk:
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write # create the release + upload the APK
+
+ steps:
+ - uses: actions/checkout@v7
+
+ # Gradle + AGP need JDK 17.
+ - uses: actions/setup-java@v5
+ with:
+ distribution: temurin
+ java-version: "17"
+
+ # Provides sdkmanager and accepts the SDK licenses.
+ - uses: android-actions/setup-android@v3
+
+ # Make sure the exact platform + build-tools the module targets are present.
+ - name: install SDK packages
+ run: sdkmanager "platform-tools" "platforms;android-35" "build-tools;35.0.0"
+
+ - uses: gradle/actions/setup-gradle@v4
+ with:
+ gradle-version: "8.9"
+
+ # Write keystore.properties + decode the keystore from repo secrets so the
+ # release build signs automatically (same pattern as patch-android-signing).
+ - name: set up signing
+ working-directory: apps/android
+ run: |
+ echo "keyAlias=${{ secrets.ANDROID_KEY_ALIAS }}" > keystore.properties
+ echo "password=${{ secrets.ANDROID_KEY_PASSWORD }}" >> keystore.properties
+ base64 -d <<< "${{ secrets.ANDROID_KEY_BASE64 }}" > "$RUNNER_TEMP/keystore.jks"
+ echo "storeFile=$RUNNER_TEMP/keystore.jks" >> keystore.properties
+
+ - name: build signed APK
+ working-directory: apps/android
+ run: |
+ ARGS="-PversionName=${VERSION#*v} -PversionCode=${{ github.run_number }}"
+ if [ -n "${SITE_URL}" ]; then ARGS="$ARGS -PsiteUrl=${SITE_URL}"; fi
+ gradle assembleRelease --no-daemon $ARGS
+ env:
+ VERSION: ${{ inputs.version }}
+ SITE_URL: ${{ inputs.siteUrl }}
+
+ # Fail loudly if only an unsigned APK exists (signing silently didn't apply).
+ - name: locate signed APK
+ id: apk
+ working-directory: apps/android
+ run: |
+ APK=$(find app/build/outputs/apk/release -name "*-release.apk" ! -name "*unsigned*" | head -1)
+ if [ -z "$APK" ]; then
+ echo "::error::No signed release APK found — did the ANDROID_KEY_* secrets apply?"
+ find app/build/outputs/apk -name "*.apk" || true
+ exit 1
+ fi
+ OUT="doughmination-music-${{ inputs.version }}-android.apk"
+ cp "$APK" "$OUT"
+ echo "path=apps/android/$OUT" >> "$GITHUB_OUTPUT"
+
+ # Always attach the APK to the run so it's downloadable even without a release.
+ - uses: actions/upload-artifact@v4
+ with:
+ name: android-apk
+ path: ${{ steps.apk.outputs.path }}
+
+ - name: publish release
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ TAG: ${{ inputs.version }}
+ run: |
+ gh release view "$TAG" >/dev/null 2>&1 || \
+ gh release create "$TAG" --title "Doughmination Music (Android) $TAG" \
+ --notes "Native Android APK with background playback + media notification."
+ gh release upload "$TAG" "${{ steps.apk.outputs.path }}" --clobber
diff --git a/apps/android/.gitignore b/apps/android/.gitignore
new file mode 100644
index 0000000..43c6482
--- /dev/null
+++ b/apps/android/.gitignore
@@ -0,0 +1,9 @@
+.gradle/
+build/
+/local.properties
+/keystore.properties
+*.jks
+*.keystore
+.idea/
+.DS_Store
+/captures/
diff --git a/apps/android/BRIDGE.md b/apps/android/BRIDGE.md
new file mode 100644
index 0000000..e5fef78
--- /dev/null
+++ b/apps/android/BRIDGE.md
@@ -0,0 +1,61 @@
+# Native ⇄ Web bridge contract
+
+The native Android app is a **WebView shell** (UI = the existing web player at
+`https://doughmination.me`) plus a **native Media3/ExoPlayer** engine that owns
+the actual audio, the foreground service, and the media notification / lock
+screen controls.
+
+The web player keeps owning the *library, queue, shuffle/repeat, and UI*. It no
+longer produces sound on Android — instead it drives a native audio element
+(`NativeAudio`, see `packages/player/src/native-audio.ts`) that forwards every
+call across this bridge. Native is the single source of truth for playback
+position and play/pause state, and reports both back to the web layer.
+
+## Web → Native (`window.DmndNative`, an injected `@JavascriptInterface`)
+
+All arguments are JS primitives (strings / numbers / booleans) — the only
+types that cross an Android JavascriptInterface safely.
+
+| Method | Meaning |
+| --- | --- |
+| `setTrack(url, metadataJson, autoplay)` | Load a new stream. `metadataJson` = `{"title","artist","album","coverUrl","durationS"}`. If `autoplay` is true, start playing once buffered. |
+| `play()` | Resume the current track. |
+| `pause()` | Pause. |
+| `seek(seconds)` | Seek within the current track (double). |
+| `setVolume(v)` | 0.0–1.0. |
+| `ready()` | Returns `true` — lets the web layer feature-detect the host synchronously. |
+
+`setTrack` carries the metadata so the notification/lock screen can render the
+title, artist and cover **immediately**, without a second round trip. The cover
+and stream are fetched by native using the WebView's own session cookie (see
+`CookieDataSourceFactory` / `CookieBitmapLoader`), so auth "just works".
+
+## Native → Web (`window.__dmndNative.*`, called via `evaluateJavascript`)
+
+The web layer installs this object at startup. Native invokes it on the UI
+thread. Every method is null-guarded on the native side (`window.__dmndNative && …`).
+
+| Method | Meaning |
+| --- | --- |
+| `onReady()` | The track is prepared and seekable → web dispatches `loadedmetadata` + `canplay`. |
+| `onPosition(positionSec, durationSec)` | Playback clock tick (~2 Hz while playing) → `timeupdate` (+ `durationchange` on change). |
+| `onPlay()` | Playback started/resumed → `play`. |
+| `onPause()` | Paused → `pause`. |
+| `onEnded()` | Track finished → `ended` (web advances the queue). |
+| `onError(message)` | Native playback error → surfaced to the web player. |
+| `onTransport(cmd)` | A **notification / lock-screen** button was pressed. `cmd` ∈ `"next" \| "prev"`. Web runs `player.next()` / `player.prev()`, which then calls `setTrack` for the new song. |
+
+`play` / `pause` from the notification are handled natively (they act on
+ExoPlayer directly) and merely echoed back via `onPlay` / `onPause`, so the web
+UI stays in sync. Only `next` / `prev` need routing back to the web queue,
+because the native engine only ever holds the *one* current track.
+
+## Why this split
+
+* Background + locked playback is rock-solid: it's a real foreground
+ `MediaSessionService`, not a WebView that Android suspends.
+* The notification/lock-screen media controls come essentially for free from
+ Media3 — the web `navigator.mediaSession` API is **not** surfaced by a bare
+ Android WebView, which is why the Tauri build showed no controls.
+* The web app stays the single UI/queue implementation across web, desktop and
+ Android; only the audio *backend* is swapped.
diff --git a/apps/android/README.md b/apps/android/README.md
new file mode 100644
index 0000000..22be7cd
--- /dev/null
+++ b/apps/android/README.md
@@ -0,0 +1,96 @@
+# Doughmination Music — native Android app
+
+A standalone native Android app that replaces the Tauri Android APK. It hosts
+the existing web player in a WebView but plays audio through a native
+**Media3 / ExoPlayer** foreground service, so playback keeps going when the app
+is backgrounded or the screen is locked, and shows a real **now-playing
+notification** with cover art and play / pause / next / previous controls.
+
+## Why this exists
+
+The Tauri APK ran the whole player inside a bare WebView. A bare Android WebView
+does **not** surface the web `navigator.mediaSession` API to the OS, so Android
+never saw an active media session — no notification, no lock-screen controls,
+and it suspended the WebView's audio the moment the app lost focus. That's why
+audio "kept playing" in the UI but produced no sound once backgrounded/locked.
+
+The fix is to let a native media service own the audio. See `BRIDGE.md` for the
+web ⇄ native contract.
+
+## Architecture
+
+```
+┌─────────────────────────── MainActivity ───────────────────────────┐
+│ WebView (doughmination.me — the existing UI, queue, shuffle…) │
+│ │ window.DmndNative.setTrack/play/pause/seek/setVolume │
+│ ▼ │
+│ WebBridge ──► MediaController ──► PlaybackService (foreground) │
+│ └─ ExoPlayer (+ cookie data src) │
+│ ▲ │ │
+│ └── window.__dmndNative.onPlay/onPosition/onEnded/onTransport ───┘
+```
+
+* **WebView** keeps owning the library, queue, shuffle/repeat and all UI.
+* **`packages/player`** detects the native host and swaps its `<audio>` element
+ for a native-backed shim (`native-audio.ts`) — the Player logic is unchanged.
+* **`PlaybackService`** is a Media3 `MediaSessionService`; Media3 builds the
+ media notification/lock-screen controls for us.
+* **`CookieDataSourceFactory`** injects the WebView's session cookie into
+ ExoPlayer's requests, so auth-gated streams and cover art load.
+* **`QueuePlayer`** forwards notification next/prev back to the web queue,
+ since native only holds the single current track.
+
+## Requirements to actually work end-to-end
+
+1. **The site must be redeployed with the web-side changes** in this repo
+ (`packages/player/src/native-audio.ts`, `apps/web/src/native.ts`, and the
+ Player/app wiring). The APK loads the live site, so until those ship, the
+ native bridge is dormant and audio falls back to the (suspended) WebView.
+2. Sign-in happens **inside the WebView** (normal web OIDC flow); the resulting
+ session cookie is what native reuses for streams/artwork.
+
+## Build
+
+Requires JDK 17 and the Android SDK (platform 35, build-tools 35).
+
+```bash
+cd apps/android
+
+# Debug build (unsigned, installs as uk.doughmination.music.debug):
+gradle assembleDebug
+
+# Release build. Point it at a different site if needed:
+gradle assembleRelease -PsiteUrl=https://doughmination.me
+```
+
+Opening `apps/android/` in Android Studio also works and will generate the
+Gradle wrapper for you.
+
+### Signing
+
+Release signing reads `apps/android/keystore.properties` (git-ignored):
+
+```properties
+keyAlias=your-alias
+password=your-key-and-store-password
+storeFile=/absolute/path/to/keystore.jks
+```
+
+If that file is absent, `assembleRelease` falls back to the debug key so the
+build still succeeds locally.
+
+## CI
+
+`.github/workflows/android.yml` builds and publishes the signed APK on manual
+dispatch, reusing the existing `ANDROID_KEY_ALIAS` / `ANDROID_KEY_PASSWORD` /
+`ANDROID_KEY_BASE64` secrets. It's fully independent of the Tauri `release`
+workflow.
+
+## Notes / limitations
+
+* App id is `uk.doughmination.music` (the Tauri build was
+ `uk.doughmination.music.desktop`), so this installs **alongside** the old
+ APK rather than upgrading it. Uninstall the old one if you want just this.
+* The audio visualizer (Web Audio) is disabled on Android — native owns the
+ audio pipeline, which Web Audio can't tap.
+* Not yet compiled on-device here; expect a round or two of on-device iteration.
diff --git a/apps/android/app/build.gradle.kts b/apps/android/app/build.gradle.kts
new file mode 100644
index 0000000..9ca8b73
--- /dev/null
+++ b/apps/android/app/build.gradle.kts
@@ -0,0 +1,94 @@
+import java.io.FileInputStream
+import java.util.Properties
+
+plugins {
+ id("com.android.application")
+ id("org.jetbrains.kotlin.android")
+}
+
+// Release signing is driven by a `keystore.properties` at the module root,
+// written from CI secrets (see .github/workflows/android.yml) — the same
+// ANDROID_KEY_* secrets the Tauri release workflow already uses. When the file
+// is absent (local dev), release falls back to the debug key so a plain
+// `assembleRelease` still succeeds instead of failing to sign.
+val keystorePropertiesFile = rootProject.file("keystore.properties")
+val hasReleaseKeystore = keystorePropertiesFile.exists()
+
+android {
+ namespace = "uk.doughmination.music"
+ compileSdk = 35
+
+ defaultConfig {
+ applicationId = "uk.doughmination.music"
+ minSdk = 26
+ targetSdk = 35
+ // Overridable from CI: -PversionName=1.2.0 -PversionCode=42
+ versionCode = (project.findProperty("versionCode") as String?)?.toIntOrNull() ?: 1
+ versionName = (project.findProperty("versionName") as String?) ?: "1.0.0"
+
+ // The site the WebView loads. Overridable per build via
+ // -PsiteUrl=https://staging.example.com
+ val siteUrl = (project.findProperty("siteUrl") as String?) ?: "https://doughmination.me"
+ buildConfigField("String", "SITE_URL", "\"$siteUrl\"")
+ }
+
+ signingConfigs {
+ if (hasReleaseKeystore) {
+ create("release") {
+ val props = Properties().apply { load(FileInputStream(keystorePropertiesFile)) }
+ keyAlias = props["keyAlias"] as String
+ keyPassword = props["password"] as String
+ storeFile = file(props["storeFile"] as String)
+ storePassword = props["password"] as String
+ }
+ }
+ }
+
+ buildTypes {
+ release {
+ isMinifyEnabled = false
+ isShrinkResources = false
+ signingConfig = if (hasReleaseKeystore) {
+ signingConfigs.getByName("release")
+ } else {
+ signingConfigs.getByName("debug")
+ }
+ proguardFiles(
+ getDefaultProguardFile("proguard-android-optimize.txt"),
+ "proguard-rules.pro",
+ )
+ }
+ debug {
+ applicationIdSuffix = ".debug"
+ }
+ }
+
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_17
+ targetCompatibility = JavaVersion.VERSION_17
+ }
+
+ kotlinOptions {
+ jvmTarget = "17"
+ }
+
+ buildFeatures {
+ buildConfig = true
+ }
+}
+
+dependencies {
+ val media3 = "1.4.1"
+
+ implementation("androidx.core:core-ktx:1.13.1")
+ implementation("androidx.appcompat:appcompat:1.7.0")
+ implementation("androidx.webkit:webkit:1.11.0")
+ implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.4")
+
+ implementation("androidx.media3:media3-exoplayer:$media3")
+ implementation("androidx.media3:media3-session:$media3")
+ implementation("androidx.media3:media3-datasource:$media3")
+
+ implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.1")
+ implementation("com.google.guava:guava:33.2.1-android")
+}
diff --git a/apps/android/app/proguard-rules.pro b/apps/android/app/proguard-rules.pro
new file mode 100644
index 0000000..d603383
--- /dev/null
+++ b/apps/android/app/proguard-rules.pro
@@ -0,0 +1,11 @@
+# Minification is disabled (see build.gradle.kts), so these are belt-and-braces
+# for anyone who flips isMinifyEnabled on later.
+
+# The JS bridge is called reflectively by the WebView — keep its methods.
+-keepclassmembers class uk.doughmination.music.WebBridge {
+ @android.webkit.JavascriptInterface <methods>;
+}
+
+# Media3 / ExoPlayer.
+-keep class androidx.media3.** { *; }
+-dontwarn androidx.media3.**
diff --git a/apps/android/app/src/main/AndroidManifest.xml b/apps/android/app/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..081ef97
--- /dev/null
+++ b/apps/android/app/src/main/AndroidManifest.xml
@@ -0,0 +1,47 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+
+ <uses-permission android:name="android.permission.INTERNET" />
+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+ <uses-permission android:name="android.permission.WAKE_LOCK" />
+
+ <!-- Foreground media service so audio keeps playing when backgrounded /
+ locked. FOREGROUND_SERVICE_MEDIA_PLAYBACK is required for apps
+ targeting API 34+. POST_NOTIFICATIONS is requested at runtime on
+ API 33+ so the media notification can show. -->
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
+
+ <application
+ android:allowBackup="true"
+ android:icon="@mipmap/ic_launcher"
+ android:label="@string/app_name"
+ android:roundIcon="@mipmap/ic_launcher_round"
+ android:supportsRtl="true"
+ android:usesCleartextTraffic="false"
+ android:theme="@style/Theme.DoughminationMusic">
+
+ <activity
+ android:name=".MainActivity"
+ android:exported="true"
+ android:launchMode="singleTask"
+ android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|keyboard|keyboardHidden|navigation|uiMode|density|fontScale">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+ </activity>
+
+ <!-- Media3 media session / foreground playback service. -->
+ <service
+ android:name=".playback.PlaybackService"
+ android:exported="true"
+ android:foregroundServiceType="mediaPlayback">
+ <intent-filter>
+ <action android:name="androidx.media3.session.MediaSessionService" />
+ </intent-filter>
+ </service>
+
+ </application>
+</manifest>
diff --git a/apps/android/app/src/main/java/uk/doughmination/music/MainActivity.kt b/apps/android/app/src/main/java/uk/doughmination/music/MainActivity.kt
new file mode 100644
index 0000000..8c9a034
--- /dev/null
+++ b/apps/android/app/src/main/java/uk/doughmination/music/MainActivity.kt
@@ -0,0 +1,258 @@
+package uk.doughmination.music
+
+import android.Manifest
+import android.annotation.SuppressLint
+import android.content.ComponentName
+import android.content.pm.PackageManager
+import android.net.Uri
+import android.os.Build
+import android.os.Bundle
+import android.os.Handler
+import android.os.Looper
+import android.webkit.CookieManager
+import android.webkit.WebView
+import android.webkit.WebViewClient
+import androidx.activity.OnBackPressedCallback
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.appcompat.app.AppCompatActivity
+import androidx.core.content.ContextCompat
+import androidx.media3.common.C
+import androidx.media3.common.MediaItem
+import androidx.media3.common.MediaMetadata
+import androidx.media3.common.PlaybackException
+import androidx.media3.common.Player
+import androidx.media3.common.util.UnstableApi
+import androidx.media3.session.MediaController
+import androidx.media3.session.SessionToken
+import com.google.common.util.concurrent.ListenableFuture
+import com.google.common.util.concurrent.MoreExecutors
+import org.json.JSONObject
+import uk.doughmination.music.playback.PlaybackBus
+import uk.doughmination.music.playback.PlaybackService
+
+/**
+ * Hosts the web player in a WebView and bridges its transport calls to a native
+ * Media3 [MediaController]. The WebView owns the UI + queue; native owns audio,
+ * the foreground service, and the notification / lock-screen controls.
+ *
+ * See BRIDGE.md for the web ⇄ native contract.
+ */
+@UnstableApi
+class MainActivity : AppCompatActivity(), WebBridge.Host {
+
+ private lateinit var webView: WebView
+
+ private var controller: MediaController? = null
+ private lateinit var controllerFuture: ListenableFuture<MediaController>
+
+ // Commands that arrived before the controller finished connecting.
+ private val pending = ArrayList<(MediaController) -> Unit>()
+
+ private val mainHandler = Handler(Looper.getMainLooper())
+ private var ticking = false
+
+ // Fire onReady() once per new track (STATE_READY can re-fire after seeks).
+ private var awaitingReady = false
+
+ private val requestNotifications =
+ registerForActivityResult(ActivityResultContracts.RequestPermission()) { /* best-effort */ }
+
+ private val transportListener = PlaybackBus.TransportListener { cmd ->
+ // From a notification/lock-screen button → hand to the web queue.
+ runOnUiThread { evalNative("onTransport", JSONObject.quote(cmd)) }
+ }
+
+ @SuppressLint("SetJavaScriptEnabled")
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+
+ webView = WebView(this)
+ setContentView(webView)
+
+ CookieManager.getInstance().apply {
+ setAcceptCookie(true)
+ setAcceptThirdPartyCookies(webView, true)
+ }
+
+ webView.settings.apply {
+ javaScriptEnabled = true
+ domStorageEnabled = true
+ databaseEnabled = true
+ mediaPlaybackRequiresUserGesture = false
+ loadsImagesAutomatically = true
+ useWideViewPort = true
+ loadWithOverviewMode = true
+ }
+ // Keep all navigation (including the OIDC login redirect) inside the
+ // WebView so the session cookie is set on our origin.
+ webView.webViewClient = WebViewClient()
+ webView.addJavascriptInterface(WebBridge(this), "DmndNative")
+
+ if (savedInstanceState == null) {
+ webView.loadUrl(BuildConfig.SITE_URL)
+ } else {
+ webView.restoreState(savedInstanceState)
+ }
+
+ onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
+ override fun handleOnBackPressed() {
+ if (webView.canGoBack()) webView.goBack() else finish()
+ }
+ })
+
+ requestNotificationPermission()
+ PlaybackBus.addListener(transportListener)
+ }
+
+ override fun onStart() {
+ super.onStart()
+ val token = SessionToken(this, ComponentName(this, PlaybackService::class.java))
+ controllerFuture = MediaController.Builder(this, token).buildAsync()
+ controllerFuture.addListener({
+ val c = controllerFuture.get()
+ controller = c
+ c.addListener(playerListener)
+ // Flush anything the web layer asked for while we were connecting.
+ pending.forEach { it(c) }
+ pending.clear()
+ }, ContextCompat.getMainExecutor(this))
+ }
+
+ override fun onStop() {
+ stopTicker()
+ controller?.removeListener(playerListener)
+ MediaController.releaseFuture(controllerFuture)
+ controller = null
+ super.onStop()
+ }
+
+ override fun onDestroy() {
+ PlaybackBus.removeListener(transportListener)
+ webView.destroy()
+ super.onDestroy()
+ }
+
+ override fun onSaveInstanceState(outState: Bundle) {
+ super.onSaveInstanceState(outState)
+ webView.saveState(outState)
+ }
+
+ // ---- WebBridge.Host: web → native (marshalled onto the main thread) ----
+
+ override fun cmdSetTrack(url: String, metadataJson: String, autoplay: Boolean) =
+ withController { c ->
+ val meta = runCatching { JSONObject(metadataJson) }.getOrNull()
+ val builder = MediaMetadata.Builder()
+ meta?.optString("title")?.takeIf { it.isNotEmpty() }?.let { builder.setTitle(it) }
+ meta?.optString("artist")?.takeIf { it.isNotEmpty() }?.let { builder.setArtist(it) }
+ meta?.optString("album")?.takeIf { it.isNotEmpty() }?.let { builder.setAlbumTitle(it) }
+ meta?.optString("coverUrl")?.takeIf { it.isNotEmpty() }
+ ?.let { builder.setArtworkUri(Uri.parse(it)) }
+
+ val item = MediaItem.Builder()
+ .setUri(url)
+ .setMediaMetadata(builder.build())
+ .build()
+
+ awaitingReady = true
+ c.setMediaItem(item)
+ c.prepare()
+ c.playWhenReady = autoplay
+ }
+
+ override fun cmdPlay() = withController { it.play() }
+
+ override fun cmdPause() = withController { it.pause() }
+
+ override fun cmdSeek(seconds: Double) =
+ withController { it.seekTo((seconds * 1000).toLong().coerceAtLeast(0)) }
+
+ override fun cmdSetVolume(volume: Double) =
+ withController { it.volume = volume.toFloat().coerceIn(0f, 1f) }
+
+ // ---- native → web ----
+
+ private val playerListener = object : Player.Listener {
+ override fun onPlaybackStateChanged(playbackState: Int) {
+ when (playbackState) {
+ Player.STATE_READY -> {
+ if (awaitingReady) {
+ awaitingReady = false
+ evalNative("onReady")
+ }
+ pushPosition()
+ }
+ Player.STATE_ENDED -> {
+ stopTicker()
+ evalNative("onEnded")
+ }
+ }
+ }
+
+ override fun onIsPlayingChanged(isPlaying: Boolean) {
+ if (isPlaying) {
+ evalNative("onPlay")
+ startTicker()
+ } else {
+ evalNative("onPause")
+ stopTicker()
+ pushPosition()
+ }
+ }
+
+ override fun onPlayerError(error: PlaybackException) {
+ evalNative("onError", JSONObject.quote(error.errorCodeName))
+ }
+ }
+
+ private val ticker = object : Runnable {
+ override fun run() {
+ pushPosition()
+ if (ticking) mainHandler.postDelayed(this, 500)
+ }
+ }
+
+ private fun startTicker() {
+ if (ticking) return
+ ticking = true
+ mainHandler.post(ticker)
+ }
+
+ private fun stopTicker() {
+ ticking = false
+ mainHandler.removeCallbacks(ticker)
+ }
+
+ private fun pushPosition() {
+ val c = controller ?: return
+ val pos = c.currentPosition.coerceAtLeast(0) / 1000.0
+ val rawDur = c.duration
+ val dur = if (rawDur == C.TIME_UNSET || rawDur < 0) 0.0 else rawDur / 1000.0
+ evalNative("onPosition", pos.toString(), dur.toString())
+ }
+
+ /** Calls window.__dmndNative.<method>(<args>) on the page, if present. */
+ private fun evalNative(method: String, vararg args: String) {
+ val js = "window.__dmndNative && window.__dmndNative.$method(${args.joinToString(", ")});"
+ webView.evaluateJavascript(js, null)
+ }
+
+ // JS-bridge calls arrive on a WebView binder thread, but MediaController
+ // must be used on the main thread — so every command hops here first.
+ // `pending` and `controller` are therefore only touched on the main thread.
+ private inline fun withController(crossinline action: (MediaController) -> Unit) {
+ runOnUiThread {
+ val c = controller
+ if (c != null) action(c) else pending.add { action(it) }
+ }
+ }
+
+ private fun requestNotificationPermission() {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
+ ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS)
+ != PackageManager.PERMISSION_GRANTED
+ ) {
+ requestNotifications.launch(Manifest.permission.POST_NOTIFICATIONS)
+ }
+ }
+}
diff --git a/apps/android/app/src/main/java/uk/doughmination/music/WebBridge.kt b/apps/android/app/src/main/java/uk/doughmination/music/WebBridge.kt
new file mode 100644
index 0000000..12bea6e
--- /dev/null
+++ b/apps/android/app/src/main/java/uk/doughmination/music/WebBridge.kt
@@ -0,0 +1,44 @@
+package uk.doughmination.music
+
+import android.webkit.JavascriptInterface
+
+/**
+ * The `window.DmndNative` object the web player calls. Every method just hands
+ * off to [Host] (implemented by [MainActivity]), which marshals the call onto
+ * the main thread and drives the Media3 MediaController.
+ *
+ * JavascriptInterface methods run on a WebView JS thread — never touch the
+ * player or any UI here directly; that's [Host]'s job.
+ *
+ * See BRIDGE.md for the full contract.
+ */
+class WebBridge(private val host: Host) {
+
+ interface Host {
+ fun cmdSetTrack(url: String, metadataJson: String, autoplay: Boolean)
+ fun cmdPlay()
+ fun cmdPause()
+ fun cmdSeek(seconds: Double)
+ fun cmdSetVolume(volume: Double)
+ }
+
+ @JavascriptInterface
+ fun setTrack(url: String, metadataJson: String, autoplay: Boolean) =
+ host.cmdSetTrack(url, metadataJson, autoplay)
+
+ @JavascriptInterface
+ fun play() = host.cmdPlay()
+
+ @JavascriptInterface
+ fun pause() = host.cmdPause()
+
+ @JavascriptInterface
+ fun seek(seconds: Double) = host.cmdSeek(seconds)
+
+ @JavascriptInterface
+ fun setVolume(volume: Double) = host.cmdSetVolume(volume)
+
+ /** Lets the web layer feature-detect the native host synchronously. */
+ @JavascriptInterface
+ fun ready(): Boolean = true
+}
diff --git a/apps/android/app/src/main/java/uk/doughmination/music/playback/CookieDataSourceFactory.kt b/apps/android/app/src/main/java/uk/doughmination/music/playback/CookieDataSourceFactory.kt
new file mode 100644
index 0000000..72e8deb
--- /dev/null
+++ b/apps/android/app/src/main/java/uk/doughmination/music/playback/CookieDataSourceFactory.kt
@@ -0,0 +1,41 @@
+package uk.doughmination.music.playback
+
+import android.webkit.CookieManager
+import androidx.media3.common.util.UnstableApi
+import androidx.media3.datasource.DataSource
+import androidx.media3.datasource.DataSpec
+import androidx.media3.datasource.DefaultHttpDataSource
+import androidx.media3.datasource.HttpDataSource
+
+/**
+ * HTTP data source factory that injects the WebView's session cookie into every
+ * request, so ExoPlayer (and the notification's cover-art loader) can fetch the
+ * same auth-gated URLs the logged-in WebView can.
+ *
+ * `CookieManager` is process-global and the service shares the WebView's
+ * process, so the cookie set during the in-WebView login is visible here. The
+ * cookie is read per-`open()` because it depends on the request host and can be
+ * refreshed at any time.
+ */
+@UnstableApi
+class CookieDataSourceFactory : DataSource.Factory {
+
+ override fun createDataSource(): DataSource {
+ val http: HttpDataSource = DefaultHttpDataSource.Factory()
+ .setAllowCrossProtocolRedirects(true)
+ .setUserAgent("DoughminationMusic/1.0 (Android)")
+ .createDataSource()
+
+ // Delegate everything to the real HTTP source; only hook open() to set
+ // the Cookie header just-in-time for the URL being requested.
+ return object : DataSource by http {
+ override fun open(dataSpec: DataSpec): Long {
+ val cookie = CookieManager.getInstance().getCookie(dataSpec.uri.toString())
+ if (!cookie.isNullOrEmpty()) {
+ http.setRequestProperty("Cookie", cookie)
+ }
+ return http.open(dataSpec)
+ }
+ }
+ }
+}
diff --git a/apps/android/app/src/main/java/uk/doughmination/music/playback/PlaybackBus.kt b/apps/android/app/src/main/java/uk/doughmination/music/playback/PlaybackBus.kt
new file mode 100644
index 0000000..f5264aa
--- /dev/null
+++ b/apps/android/app/src/main/java/uk/doughmination/music/playback/PlaybackBus.kt
@@ -0,0 +1,26 @@
+package uk.doughmination.music.playback
+
+import java.util.concurrent.CopyOnWriteArrayList
+
+/**
+ * Tiny in-process event bus so the playback service can tell the Activity that
+ * a **notification / lock-screen** transport button was pressed.
+ *
+ * The native engine only ever holds the single current track, so "next"/"prev"
+ * can't be resolved natively — they have to go back to the web layer, which
+ * owns the queue. Service and Activity run in the same process (no
+ * android:process on the service), so a plain singleton is enough; no IPC.
+ */
+object PlaybackBus {
+ fun interface TransportListener {
+ /** cmd is "next" or "prev". */
+ fun onTransport(cmd: String)
+ }
+
+ private val listeners = CopyOnWriteArrayList<TransportListener>()
+
+ fun addListener(listener: TransportListener) = listeners.add(listener)
+ fun removeListener(listener: TransportListener) = listeners.remove(listener)
+
+ fun emitTransport(cmd: String) = listeners.forEach { it.onTransport(cmd) }
+}
diff --git a/apps/android/app/src/main/java/uk/doughmination/music/playback/PlaybackService.kt b/apps/android/app/src/main/java/uk/doughmination/music/playback/PlaybackService.kt
new file mode 100644
index 0000000..666de42
--- /dev/null
+++ b/apps/android/app/src/main/java/uk/doughmination/music/playback/PlaybackService.kt
@@ -0,0 +1,83 @@
+package uk.doughmination.music.playback
+
+import android.content.Intent
+import androidx.media3.common.AudioAttributes
+import androidx.media3.common.C
+import androidx.media3.common.util.UnstableApi
+import androidx.media3.datasource.DataSourceBitmapLoader
+import androidx.media3.exoplayer.ExoPlayer
+import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
+import androidx.media3.session.DefaultMediaNotificationProvider
+import androidx.media3.session.MediaSession
+import androidx.media3.session.MediaSessionService
+import com.google.common.util.concurrent.MoreExecutors
+import uk.doughmination.music.R
+import java.util.concurrent.Executors
+
+/**
+ * Foreground media service that actually plays audio. Media3 turns this into a
+ * real system MediaSession, which is what gives us reliable background/locked
+ * playback plus the notification and lock-screen controls — the things a bare
+ * WebView can't provide.
+ */
+@UnstableApi
+class PlaybackService : MediaSessionService() {
+
+ private var mediaSession: MediaSession? = null
+
+ override fun onCreate() {
+ super.onCreate()
+
+ val audioAttributes = AudioAttributes.Builder()
+ .setUsage(C.USAGE_MEDIA)
+ .setContentType(C.AUDIO_CONTENT_TYPE_MUSIC)
+ .build()
+
+ val exoPlayer = ExoPlayer.Builder(this)
+ .setMediaSourceFactory(DefaultMediaSourceFactory(CookieDataSourceFactory()))
+ // handleAudioFocus = true: pause on calls / other apps, duck, etc.
+ .setAudioAttributes(audioAttributes, /* handleAudioFocus = */ true)
+ .setHandleAudioBecomingNoisy(true) // pause when headphones unplugged
+ .setWakeMode(C.WAKE_MODE_NETWORK) // keep CPU + wifi alive while playing
+ .build()
+
+ // Cover art for the notification is fetched with the WebView's cookie
+ // too, so auth-gated artwork loads.
+ val bitmapLoader = DataSourceBitmapLoader(
+ MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor()),
+ CookieDataSourceFactory(),
+ )
+
+ mediaSession = MediaSession.Builder(this, QueuePlayer(exoPlayer))
+ .setBitmapLoader(bitmapLoader)
+ .build()
+
+ setMediaNotificationProvider(
+ DefaultMediaNotificationProvider.Builder(this).build().apply {
+ setSmallIcon(R.drawable.ic_stat_music)
+ },
+ )
+ }
+
+ override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession? =
+ mediaSession
+
+ // If the user swipes the app from recents while nothing is playing, tear the
+ // service down so no stale notification lingers. If music is still playing,
+ // let it keep going in the background.
+ override fun onTaskRemoved(rootIntent: Intent?) {
+ val player = mediaSession?.player
+ if (player == null || !player.playWhenReady || player.mediaItemCount == 0) {
+ stopSelf()
+ }
+ }
+
+ override fun onDestroy() {
+ mediaSession?.run {
+ player.release()
+ release()
+ }
+ mediaSession = null
+ super.onDestroy()
+ }
+}
diff --git a/apps/android/app/src/main/java/uk/doughmination/music/playback/QueuePlayer.kt b/apps/android/app/src/main/java/uk/doughmination/music/playback/QueuePlayer.kt
new file mode 100644
index 0000000..af78c93
--- /dev/null
+++ b/apps/android/app/src/main/java/uk/doughmination/music/playback/QueuePlayer.kt
@@ -0,0 +1,45 @@
+package uk.doughmination.music.playback
+
+import androidx.media3.common.ForwardingPlayer
+import androidx.media3.common.Player
+import androidx.media3.common.util.UnstableApi
+
+/**
+ * The native engine holds only the *current* track, so by default Media3 would
+ * hide the previous/next buttons and never fire them. This wrapper always
+ * advertises the seek-to-next / seek-to-previous commands (so the notification
+ * and lock screen show both buttons) and, instead of moving within a native
+ * playlist, forwards the press to the web layer via [PlaybackBus]. The web
+ * player then picks the correct next/previous song and calls `setTrack` again.
+ *
+ * play / pause / seek-within-track fall through to the real ExoPlayer unchanged.
+ */
+@UnstableApi
+class QueuePlayer(player: Player) : ForwardingPlayer(player) {
+
+ override fun getAvailableCommands(): Player.Commands =
+ super.getAvailableCommands()
+ .buildUpon()
+ .add(Player.COMMAND_SEEK_TO_NEXT)
+ .add(Player.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM)
+ .add(Player.COMMAND_SEEK_TO_PREVIOUS)
+ .add(Player.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM)
+ .build()
+
+ override fun isCommandAvailable(command: Int): Boolean = when (command) {
+ Player.COMMAND_SEEK_TO_NEXT,
+ Player.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM,
+ Player.COMMAND_SEEK_TO_PREVIOUS,
+ Player.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM,
+ -> true
+ else -> super.isCommandAvailable(command)
+ }
+
+ override fun hasNextMediaItem(): Boolean = true
+ override fun hasPreviousMediaItem(): Boolean = true
+
+ override fun seekToNext() = PlaybackBus.emitTransport("next")
+ override fun seekToNextMediaItem() = PlaybackBus.emitTransport("next")
+ override fun seekToPrevious() = PlaybackBus.emitTransport("prev")
+ override fun seekToPreviousMediaItem() = PlaybackBus.emitTransport("prev")
+}
diff --git a/apps/android/app/src/main/res/drawable/ic_launcher_background.xml b/apps/android/app/src/main/res/drawable/ic_launcher_background.xml
new file mode 100644
index 0000000..0dfe2b4
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/ic_launcher_background.xml
@@ -0,0 +1,9 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="108dp"
+ android:height="108dp"
+ android:viewportWidth="108"
+ android:viewportHeight="108">
+ <path android:fillColor="#0E0E12" android:pathData="M0,0h108v108h-108z" />
+ <path android:fillColor="#171725" android:pathData="M0,0h108v108h-108z"
+ android:fillAlpha="0" />
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/ic_launcher_foreground.xml b/apps/android/app/src/main/res/drawable/ic_launcher_foreground.xml
new file mode 100644
index 0000000..8b496bd
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/ic_launcher_foreground.xml
@@ -0,0 +1,12 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="108dp"
+ android:height="108dp"
+ android:viewportWidth="108"
+ android:viewportHeight="108">
+ <!-- Simple music note, centred within the adaptive-icon safe zone. -->
+ <group android:translateX="30" android:translateY="30">
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M40,6 L40,32.5 A9,9 0 1 1 34,24.1 L34,15 L20,18.2 L20,40.5 A9,9 0 1 1 14,32.1 L14,10.5 A3,3 0 0 1 16.3,7.6 L37,3 A2.4,2.4 0 0 1 40,6 Z" />
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/ic_stat_music.xml b/apps/android/app/src/main/res/drawable/ic_stat_music.xml
new file mode 100644
index 0000000..16f47ad
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/ic_stat_music.xml
@@ -0,0 +1,11 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24"
+ android:tint="#FFFFFF">
+ <!-- Monochrome status-bar icon for the media notification. -->
+ <path
+ android:fillColor="#FFFFFF"
+ android:pathData="M12,3V13.55A4,4 0 1 0 14,17V7H18V3H12Z" />
+</vector>
diff --git a/apps/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/apps/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
new file mode 100644
index 0000000..b3e26b4
--- /dev/null
+++ b/apps/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
+ <background android:drawable="@drawable/ic_launcher_background" />
+ <foreground android:drawable="@drawable/ic_launcher_foreground" />
+ <monochrome android:drawable="@drawable/ic_launcher_foreground" />
+</adaptive-icon>
diff --git a/apps/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/apps/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
new file mode 100644
index 0000000..b3e26b4
--- /dev/null
+++ b/apps/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
+ <background android:drawable="@drawable/ic_launcher_background" />
+ <foreground android:drawable="@drawable/ic_launcher_foreground" />
+ <monochrome android:drawable="@drawable/ic_launcher_foreground" />
+</adaptive-icon>
diff --git a/apps/android/app/src/main/res/values/colors.xml b/apps/android/app/src/main/res/values/colors.xml
new file mode 100644
index 0000000..2de4240
--- /dev/null
+++ b/apps/android/app/src/main/res/values/colors.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <color name="ic_launcher_background">#0E0E12</color>
+ <color name="brand">#8B5CF6</color>
+ <color name="black">#000000</color>
+</resources>
diff --git a/apps/android/app/src/main/res/values/strings.xml b/apps/android/app/src/main/res/values/strings.xml
new file mode 100644
index 0000000..c8a5115
--- /dev/null
+++ b/apps/android/app/src/main/res/values/strings.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Doughmination Music</string>
+ <string name="playback_channel_name">Playback</string>
+ <string name="playback_channel_description">Now playing controls</string>
+</resources>
diff --git a/apps/android/app/src/main/res/values/themes.xml b/apps/android/app/src/main/res/values/themes.xml
new file mode 100644
index 0000000..3c7ed67
--- /dev/null
+++ b/apps/android/app/src/main/res/values/themes.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <!-- Parented on AppCompat so we don't need the full Material Components
+ dependency; the UI is a WebView, so the theme only controls the window
+ chrome. Black background avoids a white flash before the page paints. -->
+ <style name="Theme.DoughminationMusic" parent="Theme.AppCompat.DayNight.NoActionBar">
+ <item name="android:windowBackground">@color/black</item>
+ <item name="android:statusBarColor">@color/black</item>
+ <item name="android:navigationBarColor">@color/black</item>
+ </style>
+</resources>
diff --git a/apps/android/build.gradle.kts b/apps/android/build.gradle.kts
new file mode 100644
index 0000000..9b636ac
--- /dev/null
+++ b/apps/android/build.gradle.kts
@@ -0,0 +1,5 @@
+// Root build file — versions declared here, applied in :app.
+plugins {
+ id("com.android.application") version "8.6.1" apply false
+ id("org.jetbrains.kotlin.android") version "2.0.20" apply false
+}
diff --git a/apps/android/gradle.properties b/apps/android/gradle.properties
new file mode 100644
index 0000000..71e8721
--- /dev/null
+++ b/apps/android/gradle.properties
@@ -0,0 +1,5 @@
+org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
+org.gradle.caching=true
+android.useAndroidX=true
+android.nonTransitiveRClass=true
+kotlin.code.style=official
diff --git a/apps/android/settings.gradle.kts b/apps/android/settings.gradle.kts
new file mode 100644
index 0000000..9ffddfd
--- /dev/null
+++ b/apps/android/settings.gradle.kts
@@ -0,0 +1,21 @@
+// Standalone Gradle build for the native Android app. It is intentionally NOT
+// wired into the Tauri desktop project under apps/desktop — this is a separate
+// artifact with its own release workflow (.github/workflows/android.yml).
+pluginManagement {
+ repositories {
+ google()
+ mavenCentral()
+ gradlePluginPortal()
+ }
+}
+
+dependencyResolutionManagement {
+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+
+rootProject.name = "DoughminationMusic"
+include(":app")
diff --git a/apps/web/src/app.ts b/apps/web/src/app.ts
index 05188b5..cd936a9 100644
--- a/apps/web/src/app.ts
+++ b/apps/web/src/app.ts
@@ -25,11 +25,15 @@ import {
isDesktop,
syncDiscordPresence,
} from "./desktop.ts";
+import { initNative } from "./native.ts";
initDesktopBridge();
const root = document.getElementById("app")!;
const player = new Player();
+// Inside the native Android shell, route lock-screen/notification transport
+// buttons into the queue. No-op on web/desktop.
+initNative(player);
type View =
| { kind: "library" }
diff --git a/apps/web/src/native.ts b/apps/web/src/native.ts
new file mode 100644
index 0000000..14d6cd7
--- /dev/null
+++ b/apps/web/src/native.ts
@@ -0,0 +1,28 @@
+// Native Android shell integration, mirroring desktop.ts for the Tauri build.
+//
+// When the web app runs inside apps/android, audio is played by a native
+// Media3 engine and the Player already routes playback through it (see
+// packages/player/src/native-audio.ts). The one thing the audio backend can't
+// do on its own is resolve "next"/"prev" pressed on the *notification / lock
+// screen*, because those must run the web queue. That's wired here.
+
+import { hasNativeHost, type Player } from "@musicapp/player";
+
+export const isNativeAndroid = hasNativeHost();
+
+// Route notification/lock-screen transport buttons back into the web queue.
+// The Player then loads the new song, which calls setTrack() on native again.
+export function initNative(player: Player): void {
+ if (!isNativeAndroid) return;
+
+ const w = window as unknown as {
+ __dmndNative?: Record<string, unknown>;
+ };
+ w.__dmndNative = {
+ ...(w.__dmndNative ?? {}),
+ onTransport: (cmd: string) => {
+ if (cmd === "next") player.next();
+ else if (cmd === "prev") player.prev();
+ },
+ };
+}
diff --git a/packages/player/src/index.ts b/packages/player/src/index.ts
index 9cf9862..ece727c 100644
--- a/packages/player/src/index.ts
+++ b/packages/player/src/index.ts
@@ -1,3 +1,4 @@
export * from "./player.ts";
export * from "./events.ts";
export * from "./storage.ts";
+export * from "./native-audio.ts";
diff --git a/packages/player/src/native-audio.ts b/packages/player/src/native-audio.ts
new file mode 100644
index 0000000..461b2c7
--- /dev/null
+++ b/packages/player/src/native-audio.ts
@@ -0,0 +1,274 @@
+// Native (Android) audio backend.
+//
+// On the web and in the Tauri desktop webview the Player drives a real
+// HTMLAudioElement. Inside the native Android shell (apps/android) a bare
+// WebView can't do reliable background/locked playback or surface a media
+// notification, so audio is played by a native Media3/ExoPlayer engine instead.
+//
+// `NativeAudio` implements exactly the slice of HTMLAudioElement the Player
+// uses, but every call is forwarded across the JS ⇄ native bridge
+// (`window.DmndNative`), and playback state comes back from native via
+// `window.__dmndNative.*`. The Player itself is unchanged — it just talks to a
+// different "audio element". See apps/android/BRIDGE.md for the contract.
+
+// The subset of HTMLAudioElement the Player relies on. A real HTMLAudioElement
+// already satisfies this; NativeAudio emulates it.
+export interface MediaEl {
+ volume: number;
+ preload: string;
+ src: string;
+ currentTime: number;
+ readonly duration: number;
+ readonly paused: boolean;
+ readonly playbackRate: number;
+ readonly readyState: number;
+ readonly error: { readonly code: number } | null;
+ readonly style: { display: string };
+ setAttribute(name: string, value: string): void;
+ play(): Promise<void>;
+ pause(): void;
+ load(): void;
+ addEventListener(type: string, cb: (ev?: unknown) => void, opts?: { once?: boolean }): void;
+ removeEventListener(type: string, cb: (ev?: unknown) => void): void;
+ // Native-only: hand the current track's metadata to the OS notification.
+ setMetadata?(meta: NativeTrackMeta): void;
+}
+
+export interface NativeTrackMeta {
+ title: string;
+ artist: string;
+ album: string;
+ coverUrl: string | null;
+ durationS: number | null;
+}
+
+// The injected native interface (Android @JavascriptInterface).
+interface NativeHost {
+ setTrack(url: string, metadataJson: string, autoplay: boolean): void;
+ play(): void;
+ pause(): void;
+ seek(seconds: number): void;
+ setVolume(v: number): void;
+ ready(): boolean;
+}
+
+type Listener = (ev?: unknown) => void;
+
+export function hasNativeHost(): boolean {
+ return (
+ typeof window !== "undefined" &&
+ typeof (window as unknown as { DmndNative?: NativeHost }).DmndNative !== "undefined" &&
+ typeof (window as unknown as { DmndNative?: NativeHost }).DmndNative?.ready === "function"
+ );
+}
+
+// Return the element the Player should drive: native-backed inside the Android
+// shell, a real <audio> everywhere else.
+export function createAudioElement(): MediaEl {
+ if (hasNativeHost()) {
+ return new NativeAudio((window as unknown as { DmndNative: NativeHost }).DmndNative);
+ }
+ return new Audio() as unknown as MediaEl;
+}
+
+function toAbsolute(url: string): string {
+ try {
+ return new URL(url, typeof location !== "undefined" ? location.href : undefined).href;
+ } catch {
+ return url;
+ }
+}
+
+export class NativeAudio implements MediaEl {
+ // Emulated element state — kept in sync from native callbacks.
+ private _src = "";
+ private _dirty = false; // src changed since the last setTrack()
+ private _currentTime = 0;
+ private _duration = 0;
+ private _paused = true;
+ private _volume = 1;
+ private _meta = "{}";
+ private _error: { code: number } | null = null;
+ private listeners = new Map<string, Set<Listener>>();
+
+ preload = "metadata";
+ readonly style = { display: "" };
+
+ constructor(private host: NativeHost) {
+ installNativeCallbacks(this);
+ }
+
+ get volume(): number {
+ return this._volume;
+ }
+ set volume(v: number) {
+ this._volume = v;
+ this.host.setVolume(v);
+ this.emit("volumechange");
+ }
+
+ get src(): string {
+ return this._src;
+ }
+ set src(url: string) {
+ const abs = toAbsolute(url);
+ if (abs !== this._src) {
+ this._src = abs;
+ this._dirty = true;
+ this._duration = 0;
+ this._currentTime = 0;
+ this._error = null;
+ }
+ }
+
+ get currentTime(): number {
+ return this._currentTime;
+ }
+ set currentTime(t: number) {
+ this._currentTime = t;
+ this.host.seek(t);
+ }
+
+ get duration(): number {
+ return this._duration;
+ }
+ get paused(): boolean {
+ return this._paused;
+ }
+ get error(): { code: number } | null {
+ return this._error;
+ }
+ get playbackRate(): number {
+ return 1;
+ }
+ // Native owns buffering/recovery, so always report "enough to play through"
+ // (HAVE_ENOUGH_DATA) once we have a duration — this keeps the Player's web
+ // stall-watchdog from firing against state it can't see.
+ get readyState(): number {
+ return this._duration > 0 ? 4 : 0;
+ }
+
+ setAttribute(): void {
+ /* playsinline / controlsList etc. are meaningless natively */
+ }
+
+ setMetadata(meta: NativeTrackMeta): void {
+ this._meta = JSON.stringify(meta);
+ // Metadata that arrives for an already-loaded track (rare) → refresh the
+ // notification in place. The normal path is src → setMetadata → play(),
+ // where play() sends the combined setTrack.
+ if (!this._dirty && this._src) {
+ this.host.setTrack(this._src, this._meta, !this._paused);
+ }
+ }
+
+ load(): void {
+ if (!this._src) return;
+ this._dirty = false;
+ this.host.setTrack(this._src, this._meta, false);
+ }
+
+ play(): Promise<void> {
+ if (this._dirty) {
+ this._dirty = false;
+ this.host.setTrack(this._src, this._meta, true);
+ } else {
+ this.host.play();
+ }
+ // Native play never throws the way HTMLMediaElement.play() can, so there's
+ // nothing for the Player's AbortError/autoplay handling to catch.
+ return Promise.resolve();
+ }
+
+ pause(): void {
+ this.host.pause();
+ }
+
+ addEventListener(type: string, cb: Listener, opts?: { once?: boolean }): void {
+ const wrapped: Listener = opts?.once
+ ? (ev) => {
+ this.removeEventListener(type, wrapped);
+ cb(ev);
+ }
+ : cb;
+ // Track under the original cb so removeEventListener(cb) still works.
+ let set = this.listeners.get(type);
+ if (!set) {
+ set = new Set();
+ this.listeners.set(type, set);
+ }
+ set.add(wrapped);
+ if (wrapped !== cb) this.onceMap.set(cb, wrapped);
+ }
+
+ removeEventListener(type: string, cb: Listener): void {
+ const set = this.listeners.get(type);
+ if (!set) return;
+ set.delete(cb);
+ const wrapped = this.onceMap.get(cb);
+ if (wrapped) {
+ set.delete(wrapped);
+ this.onceMap.delete(cb);
+ }
+ }
+
+ private onceMap = new Map<Listener, Listener>();
+
+ // ---- called by native via window.__dmndNative ----
+ _onReady(): void {
+ this.emit("loadedmetadata");
+ this.emit("canplay");
+ }
+ _onPosition(pos: number, dur: number): void {
+ this._currentTime = pos;
+ if (dur > 0 && dur !== this._duration) {
+ this._duration = dur;
+ this.emit("durationchange");
+ this.emit("loadedmetadata");
+ }
+ this.emit("timeupdate");
+ }
+ _onPlay(): void {
+ this._paused = false;
+ this.emit("play");
+ }
+ _onPause(): void {
+ this._paused = true;
+ this.emit("pause");
+ }
+ _onEnded(): void {
+ this.emit("ended");
+ }
+ _onError(_message: string): void {
+ // Present it like a recoverable HTMLMediaElement network error (code 2) so
+ // the Player's existing error handler re-fetches and resumes via native.
+ this._error = { code: 2 };
+ this.emit("error");
+ }
+
+ private emit(type: string, ev?: unknown): void {
+ this.listeners.get(type)?.forEach((cb) => {
+ try {
+ cb(ev);
+ } catch {
+ /* a listener throwing must not break the bridge */
+ }
+ });
+ }
+}
+
+// Expose the native → web callbacks. Merges rather than overwrites so the
+// app-level transport handler (window.__dmndNative.onTransport, set in
+// apps/web/src/native.ts) survives, and vice-versa.
+function installNativeCallbacks(a: NativeAudio): void {
+ const w = window as unknown as { __dmndNative?: Record<string, unknown> };
+ w.__dmndNative = {
+ ...(w.__dmndNative ?? {}),
+ onReady: () => a._onReady(),
+ onPosition: (p: number, d: number) => a._onPosition(p, d),
+ onPlay: () => a._onPlay(),
+ onPause: () => a._onPause(),
+ onEnded: () => a._onEnded(),
+ onError: (m: string) => a._onError(m),
+ };
+}
diff --git a/packages/player/src/player.ts b/packages/player/src/player.ts
index 7d9251f..888c0ab 100644
--- a/packages/player/src/player.ts
+++ b/packages/player/src/player.ts
@@ -6,6 +6,7 @@
import type { Song } from "@musicapp/shared";
import { Emitter } from "./events.ts";
+import { createAudioElement, hasNativeHost, type MediaEl } from "./native-audio.ts";
import { localStoragePrefs, type Prefs, type PrefsStorage } from "./storage.ts";
export type RepeatMode = Prefs["repeat"];
@@ -19,7 +20,10 @@ type PlayerEvents = {
export class Player {
readonly events = new Emitter<PlayerEvents>();
- private audio = new Audio();
+ // A real <audio> on web/desktop; a native Media3-backed shim inside the
+ // Android shell (see native-audio.ts). The Player logic is identical either
+ // way — only the backend differs.
+ private audio: MediaEl = createAudioElement();
private storage: PrefsStorage;
private queue: Song[] = []; // playback order (shuffled or not)
private originalOrder: Song[] = []; // order as given to playQueue, never shuffled
@@ -50,7 +54,8 @@ export class Player {
this.audio.setAttribute("controlsList", "nodownload");
if (typeof document !== "undefined") {
this.audio.style.display = "none";
- document.body.appendChild(this.audio);
+ // Only a real <audio> is a DOM node; the native shim isn't appended.
+ if (this.audio instanceof HTMLElement) document.body.appendChild(this.audio);
}
this.audio.addEventListener("ended", () => this.onEnded());
@@ -113,6 +118,17 @@ export class Player {
}
private updateMediaMetadata(song: Song): void {
+ // Hand metadata to the native backend first (its OS notification needs it),
+ // independently of whether the web MediaSession API is available. No-op on
+ // a real <audio> element.
+ this.audio.setMetadata?.({
+ title: song.title,
+ artist: song.artist,
+ album: song.album ?? "",
+ coverUrl: song.coverUrl ? absoluteUrl(song.coverUrl) : null,
+ durationS: song.durationS,
+ });
+
if (typeof navigator === "undefined" || !("mediaSession" in navigator)) return;
try {
navigator.mediaSession.metadata = new MediaMetadata({
@@ -343,13 +359,20 @@ export class Player {
// any failure leaves plain <audio> playback untouched.
private setupGraph(): void {
if (this.ctx) return;
+ // Native (Android) audio can't be tapped by Web Audio; skip entirely so we
+ // don't construct a throwaway AudioContext on every track (which would leak
+ // contexts and eventually hit the browser's hard limit).
+ if (hasNativeHost()) return;
try {
const Ctx =
window.AudioContext ||
(window as unknown as { webkitAudioContext: typeof AudioContext })
.webkitAudioContext;
const ctx = new Ctx();
- const src = ctx.createMediaElementSource(this.audio);
+ // Only a real HTMLMediaElement can feed Web Audio. With the native
+ // backend this throws and we fall through to the catch — the visualizer
+ // is simply disabled on Android (native owns the audio pipeline).
+ const src = ctx.createMediaElementSource(this.audio as unknown as HTMLMediaElement);
const analyser = ctx.createAnalyser();
analyser.fftSize = 128;
analyser.smoothingTimeConstant = 0.8;