Skip to content

Native Android client for Spotify, built with Jetpack Compose

Ads muted on the page's media element instead of the Connect volume; cover size back to the screen-height budget; cdp tool finds dev/stable builds

kota-zo7573cd79441e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 033e1865..2ab8c0e8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,8 @@ Each release on GitHub shows its section below. The app shows it too when it off
## Unreleased
- **Myspoti's icon in the notification** and in Samsung's Now Bar, instead of a generic music note.
+- **Ads that get through are silent**: they are muted on the page itself, no longer through a Spotify Connect volume command that some accounts refuse (the ad was heard).
+- **Cover back to its full size** in the player.
- **Music no longer stops for a minute**: a Web Player page that stops answering is reloaded at once, and playback goes on.
- **No more silent songs**: the sound comes back by itself if a skip or a muted ad left it at zero; after a skip it comes back as soon as the next song is there.
- **Smart shuffle** goes on from where the song is (no restart), adds songs to every playlist, and has its own icon in the player.
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt
index 2fc1bb53..75e3a5d5 100644
--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt
+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt
@@ -50,8 +50,12 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
val adPlaying: StateFlow<Boolean> = _adPlaying
@Volatile private var adSince = 0L
@Volatile private var adState: PlayerState? = null
- /** The page's volume before an ad muted it, put back when the ad is over. */
- @Volatile private var volumeBeforeAd: Double? = null
+ /**
+ * An ad is muted. The page's own media element is muted, not the player's volume: the
+ * volume goes through Spotify Connect, which refuses it on some accounts
+ * (DEVICE_DOES_NOT_SUPPORT_COMMAND) and leaves the ad audible.
+ */
+ @Volatile private var adMuted = false
/** A pause asked through [pause]; it holds until playback is asked for again, never expires. */
@Volatile private var pausedByUser = false
/** The order given to the last [play] (context uri to songs), kept for a stall restart. */
@@ -95,7 +99,9 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
if (!it) return@collect
if (audioQuality != "auto") applyAudioQuality()
// The page keeps its volume: an app closed during a muted ad must not stay silent.
- runCatching { if (volume() == 0.0) setVolume(volumeBeforeAd ?: 1.0) }
+ runCatching { if (volume() == 0.0) setVolume(wantedVolume?.takeIf { v -> v > 0.0 } ?: 1.0) }
+ // A reloaded page during an ad break plays the ad again: muted again at once.
+ if (_adPlaying.value) muteForAd()
}
}
}
@@ -188,12 +194,13 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
*/
private suspend fun guardVolume(s: PlayerState?) {
if (s == null || s.isPaused || s.isBuffering || _adPlaying.value || fadeBackTo != null || fadeBack?.isActive == true) return
+ // The unmute after an ad was lost (page busy): the song would play silent.
+ if (adMuted) unmuteAfterAd()
val wanted = wantedVolume ?: 1.0
if (wanted <= 0.0) return
val v = runCatching { volume() }.getOrNull() ?: return
- if (v > 0.0) { if (volumeBeforeAd != null) volumeBeforeAd = null; return }
+ if (v > 0.0) return
bridge.logger?.invoke("page silent during a song: volume back to $wanted")
- volumeBeforeAd = null
runCatching { setLevel(wanted) }
}
@@ -250,7 +257,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
private suspend fun withFade(block: suspend () -> Unit) {
val s = _state.value
// Nothing heard (paused, an ad muted): nothing to fade.
- if (s == null || s.isPaused || _adPlaying.value || volumeBeforeAd != null) { block(); return }
+ if (s == null || s.isPaused || _adPlaying.value || adMuted) { block(); return }
val target = fadeBackTo ?: runCatching { volume() }.getOrNull()?.takeIf { it > 0.0 }?.also { wantedVolume = it } ?: run { block(); return }
val from = s.item?.uri
fadeBackTo = target
@@ -267,7 +274,6 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
withTimeoutOrNull(FADE_BACK_MAX_MS) {
_state.first { it != null && !it.isPaused && (it.item?.uri != from || it.positionMs < 1_500) }
}
- if (_adPlaying.value) { if (volumeBeforeAd == null) volumeBeforeAd = target; fadeBackTo = null; return@launch }
val back = fadeBackTo ?: target
runCatching { for (f in FADE_STEPS.reversed().drop(1)) { setLevel(back * f); delay(FADE_STEP_MS) }; setLevel(back) }
.onFailure { runCatching { setLevel(back) } }
@@ -277,14 +283,15 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
}
private suspend fun muteForAd() = runCatching {
- if (volumeBeforeAd == null) volumeBeforeAd = fadeBackTo ?: volume().takeIf { it > 0.0 } ?: wantedVolume?.takeIf { it > 0.0 } ?: 1.0
- bridge.call("volume.set", buildJsonObject { put("level", 0.0) })
+ adMuted = true
+ val muted = bridge.call("media.mute", buildJsonObject { put("on", true) })
+ bridge.logger?.invoke("ad muted ($muted media elements)")
}
private suspend fun unmuteAfterAd() = runCatching {
- val v = volumeBeforeAd ?: return@runCatching
- bridge.call("volume.set", buildJsonObject { put("level", v) })
- volumeBeforeAd = null
+ if (!adMuted) return@runCatching
+ bridge.call("media.mute", buildJsonObject { put("on", false) })
+ adMuted = false
}
override suspend fun play(contextUri: Uri, trackUri: Uri?, index: Int?, positionMs: Long?, order: List<Uri>?) {
diff --git a/base/api-spotify/src/main/resources/bridge/player-bridge.js b/base/api-spotify/src/main/resources/bridge/player-bridge.js
index 6cf15e99..ef5b5a8e 100644
--- a/base/api-spotify/src/main/resources/bridge/player-bridge.js
+++ b/base/api-spotify/src/main/resources/bridge/player-bridge.js
@@ -171,6 +171,32 @@
return out;
};
+ // The page player's own media elements: kept inside its objects, never in the document.
+ const playerMedia = async () => {
+ const found = new Set();
+ const sdk = need().resolve('PlayerSDK');
+ const harmony = sdk && sdk.harmony;
+ const streamer = harmony && harmony._streamer;
+ const roots = [harmony];
+ if (streamer && streamer._playerPromise) roots.push(await streamer._playerPromise);
+ const seen = new WeakSet();
+ const walk = (o, depth) => {
+ if (!o || typeof o !== 'object' || seen.has(o) || depth > 6) return;
+ seen.add(o);
+ if (o instanceof HTMLMediaElement) { found.add(o); return; }
+ if (o instanceof Node || o instanceof Window) return;
+ let keys = [];
+ try { keys = Object.keys(o); } catch (e) { return; }
+ for (const k of keys.slice(0, 80)) {
+ let v;
+ try { v = o[k]; } catch (e) { continue; }
+ walk(v, depth + 1);
+ }
+ };
+ roots.forEach(r => walk(r, 0));
+ return [...found];
+ };
+
// --- commands -------------------------------------------------------------
const need = () => {
@@ -240,6 +266,16 @@
// {items: [{uri, uid}], before | after: {uri, uid}}
'queue.reorder': a => need().player.reorderQueue(a.items, a.after ? { after: a.after } : { before: a.before }),
+ // Mutes the page's own media elements (ads), whatever Spotify Connect says about the
+ // volume. Elements are known from the host's document-start hook (window.__mspMedia),
+ // or found in the document. {on} -> how many elements were set.
+ 'media.mute': async a => {
+ window.__mspMuted = !!a.on;
+ const els = new Set([...(window.__mspMedia || []), ...document.querySelectorAll('audio, video'), ...await playerMedia()]);
+ for (const el of els) el.muted = !!a.on;
+ return els.size;
+ },
+
'volume.get': () => need().playback.getVolume(),
'volume.set': a => need().playback.setVolume(a.level),
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt
index 3ad1a063..ad8c423f 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt
@@ -354,7 +354,10 @@ fun PlayerScreen(navController: NavController) {
) {
val wide = maxWidth > 600.dp && maxWidth > maxHeight
val contentWidth = if (wide) maxWidth.coerceAtMost(520.dp) else maxWidth
- val artSide = minOf(contentWidth, maxHeight - PLAYER_CONTROLS_DP.dp).coerceAtLeast(160.dp)
+ // Height budget from the screen, as before (the list item is shorter than the screen and
+ // gave a smaller cover); the width cap only matters on wide windows.
+ val screenHeight = androidx.compose.ui.platform.LocalConfiguration.current.screenHeightDp.dp
+ val artSide = minOf(contentWidth, screenHeight - PLAYER_CONTROLS_DP.dp).coerceAtLeast(160.dp)
Column(
modifier = Modifier
.fillMaxHeight()
diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt
index d9eda29f..ce92a54e 100644
--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt
+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt
@@ -111,6 +111,16 @@ internal class ControlRelay(private val view: WebView) {
(() => {
if (window.__mspNetInstalled || !window.MyspotiNet) return;
window.__mspNetInstalled = true;
+ // The player's media elements, often never added to the document: the bridge
+ // mutes them during an ad ("media.mute"); one started while muted starts muted.
+ const media = new Set();
+ window.__mspMedia = media;
+ const play = HTMLMediaElement.prototype.play;
+ HTMLMediaElement.prototype.play = function () {
+ media.add(this);
+ if (window.__mspMuted) this.muted = true;
+ return play.apply(this, arguments);
+ };
const relayed = /^https:\/\/[a-z0-9-]+(\.[a-z0-9-]+)*\.spotify\.com\/(connect-state|track-playback)\/v1\//;
const pending = new Map();
let seq = 0;
diff --git a/tools/cdp.py b/tools/cdp.py
index 644b6faa..7889ab01 100644
--- a/tools/cdp.py
+++ b/tools/cdp.py
@@ -78,7 +78,7 @@ def main():
a = ap.parse_args()
ps = adb(a.serial, "shell", "ps", "-A", "-o", "PID,NAME")
unix = adb(a.serial, "shell", "cat", "/proc/net/unix")
- pid = next((l.split()[0] for l in ps.splitlines()[1:] if l.split()[-1] in ("app.myspoti", "app.myspoti:engine")
+ pid = next((l.split()[0] for l in ps.splitlines()[1:] if l.split()[-1] in ("app.myspoti", "app.myspoti:engine", "app.myspoti.dev", "app.myspoti.stable")
and f"webview_devtools_remote_{l.split()[0]}" in unix), "")
if not pid:
raise SystemExit("engine process not running")