fix(mobile): sync player volume with system audio
This commit is contained in:
14 files changed
+450
-176
No files matched your search
@@ -54,7 +54,7 @@
|
||||
"experiments": {
|
||||
"typedRoutes": true,
|
||||
"inlineModules": {
|
||||
"watchedDirectories": ["app-intents"]
|
||||
"watchedDirectories": ["app-intents", "native"]
|
||||
}
|
||||
},
|
||||
"extra": {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { DarkTheme, DefaultTheme, ThemeProvider } from "expo-router"
|
||||
import { NativeTabs } from "expo-router/native-tabs"
|
||||
import { DynamicColorIOS, Platform, useColorScheme } from "react-native"
|
||||
import { DynamicColorIOS, Platform, View, useColorScheme } from "react-native"
|
||||
import { useMemo } from "react"
|
||||
|
||||
import { TabBottomAccessory } from "@/components/mini-player"
|
||||
import { AndroidMiniPlayer, TabBottomAccessory } from "@/components/mini-player"
|
||||
import { usePlaybackQueue } from "@/contexts/playback"
|
||||
import { appleMusic, colors } from "@/lib/theme"
|
||||
|
||||
@@ -83,41 +83,44 @@ export default function TabsLayout() {
|
||||
|
||||
return (
|
||||
<ThemeProvider value={routerTheme}>
|
||||
<NativeTabs
|
||||
blurEffect={
|
||||
tabColors.blurEffect as
|
||||
"systemChromeMaterialDark" | "systemChromeMaterialLight"
|
||||
}
|
||||
backgroundColor={tabColors.backgroundColor}
|
||||
iconColor={tabColors.iconColor}
|
||||
labelStyle={tabColors.labelStyle}
|
||||
tintColor={appleMusic.pink}
|
||||
minimizeBehavior="onScrollDown"
|
||||
>
|
||||
{showBottomAccessory ? (
|
||||
<NativeTabs.BottomAccessory>
|
||||
<TabBottomAccessory />
|
||||
</NativeTabs.BottomAccessory>
|
||||
) : null}
|
||||
<View style={{ flex: 1 }}>
|
||||
<NativeTabs
|
||||
blurEffect={
|
||||
tabColors.blurEffect as
|
||||
"systemChromeMaterialDark" | "systemChromeMaterialLight"
|
||||
}
|
||||
backgroundColor={tabColors.backgroundColor}
|
||||
iconColor={tabColors.iconColor}
|
||||
labelStyle={tabColors.labelStyle}
|
||||
tintColor={appleMusic.pink}
|
||||
minimizeBehavior="onScrollDown"
|
||||
>
|
||||
{Platform.OS === "ios" && showBottomAccessory ? (
|
||||
<NativeTabs.BottomAccessory>
|
||||
<TabBottomAccessory />
|
||||
</NativeTabs.BottomAccessory>
|
||||
) : null}
|
||||
|
||||
<NativeTabs.Trigger name="home" disableTransparentOnScrollEdge>
|
||||
<NativeTabs.Trigger.Icon sf="house.fill" md="home" />
|
||||
<NativeTabs.Trigger.Label>Home</NativeTabs.Trigger.Label>
|
||||
</NativeTabs.Trigger>
|
||||
<NativeTabs.Trigger name="home" disableTransparentOnScrollEdge>
|
||||
<NativeTabs.Trigger.Icon sf="house.fill" md="home" />
|
||||
<NativeTabs.Trigger.Label>Home</NativeTabs.Trigger.Label>
|
||||
</NativeTabs.Trigger>
|
||||
|
||||
<NativeTabs.Trigger name="library" disableTransparentOnScrollEdge>
|
||||
<NativeTabs.Trigger.Icon
|
||||
sf="music.note.square.stack.fill"
|
||||
md="library_music"
|
||||
/>
|
||||
<NativeTabs.Trigger.Label>Library</NativeTabs.Trigger.Label>
|
||||
</NativeTabs.Trigger>
|
||||
<NativeTabs.Trigger name="library" disableTransparentOnScrollEdge>
|
||||
<NativeTabs.Trigger.Icon
|
||||
sf="music.note.square.stack.fill"
|
||||
md="library_music"
|
||||
/>
|
||||
<NativeTabs.Trigger.Label>Library</NativeTabs.Trigger.Label>
|
||||
</NativeTabs.Trigger>
|
||||
|
||||
<NativeTabs.Trigger name="search" disableTransparentOnScrollEdge>
|
||||
<NativeTabs.Trigger.Icon sf="magnifyingglass" md="search" />
|
||||
<NativeTabs.Trigger.Label>Search</NativeTabs.Trigger.Label>
|
||||
</NativeTabs.Trigger>
|
||||
</NativeTabs>
|
||||
<NativeTabs.Trigger name="search" disableTransparentOnScrollEdge>
|
||||
<NativeTabs.Trigger.Icon sf="magnifyingglass" md="search" />
|
||||
<NativeTabs.Trigger.Label>Search</NativeTabs.Trigger.Label>
|
||||
</NativeTabs.Trigger>
|
||||
</NativeTabs>
|
||||
<AndroidMiniPlayer />
|
||||
</View>
|
||||
</ThemeProvider>
|
||||
)
|
||||
}
|
||||
@@ -47,6 +47,7 @@ import { useServerConfig } from "@/contexts/server-config"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { useCoverPalette } from "@/hooks/use-cover-palette"
|
||||
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
|
||||
import { useSystemVolume } from "@/hooks/use-system-volume"
|
||||
import { formatDuration, formatRemainingDuration } from "@/lib/format"
|
||||
import {
|
||||
nowPlayingColors,
|
||||
@@ -80,14 +81,13 @@ export default function PlayerScreen() {
|
||||
repeatEnabled,
|
||||
currentTime,
|
||||
duration,
|
||||
volume,
|
||||
queueSongIds,
|
||||
setIsPlaying,
|
||||
setVolume,
|
||||
seekTo,
|
||||
skipNext,
|
||||
skipPrevious,
|
||||
} = usePlayback()
|
||||
const { volume, setVolume, available: volumeAvailable } = useSystemVolume()
|
||||
const [showQueue, setShowQueue] = useState(false)
|
||||
const [stageHeight, setStageHeight] = useState(0)
|
||||
const [scrubTime, setScrubTime] = useState<number | null>(null)
|
||||
@@ -377,31 +377,34 @@ export default function PlayerScreen() {
|
||||
</TransportButton>
|
||||
</View>
|
||||
|
||||
<PlayerSlider
|
||||
accessibilityLabel="Volume"
|
||||
value={volume}
|
||||
maximumValue={1}
|
||||
fillColor={colors.sliderFill}
|
||||
activeFillColor={colors.foreground}
|
||||
trackColor={colors.sliderTrack}
|
||||
onValueChange={setVolume}
|
||||
leading={
|
||||
<PlayerSymbol
|
||||
name="speaker.fill"
|
||||
fallback="volume-low"
|
||||
size={14}
|
||||
color={colors.secondaryForeground}
|
||||
/>
|
||||
}
|
||||
trailing={
|
||||
<PlayerSymbol
|
||||
name="speaker.wave.3.fill"
|
||||
fallback="volume-high"
|
||||
size={14}
|
||||
color={colors.secondaryForeground}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{volumeAvailable ? (
|
||||
<PlayerSlider
|
||||
accessibilityLabel="Volume"
|
||||
commitHoldMs={0}
|
||||
value={volume}
|
||||
maximumValue={1}
|
||||
fillColor={colors.sliderFill}
|
||||
activeFillColor={colors.foreground}
|
||||
trackColor={colors.sliderTrack}
|
||||
onValueChange={setVolume}
|
||||
leading={
|
||||
<PlayerSymbol
|
||||
name="speaker.fill"
|
||||
fallback="volume-low"
|
||||
size={14}
|
||||
color={colors.secondaryForeground}
|
||||
/>
|
||||
}
|
||||
trailing={
|
||||
<PlayerSymbol
|
||||
name="speaker.wave.3.fill"
|
||||
fallback="volume-high"
|
||||
size={14}
|
||||
color={colors.secondaryForeground}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<View style={styles.footer}>
|
||||
<Pressable
|
||||
|
||||
@@ -3,6 +3,8 @@ import { NativeTabs } from "expo-router/native-tabs"
|
||||
import { useRouter } from "expo-router"
|
||||
import { Platform, Pressable, StyleSheet, Text, View } from "react-native"
|
||||
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context"
|
||||
|
||||
import { CoverImage } from "@/components/cover-image"
|
||||
|
||||
import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback"
|
||||
@@ -178,43 +180,31 @@ export function TabBottomAccessory() {
|
||||
|
||||
return content
|
||||
}
|
||||
//
|
||||
// function useFloatingMiniPlayerLayout() {
|
||||
// const segments = useSegments() as string[]
|
||||
// const insets = useSafeAreaInsets()
|
||||
//
|
||||
// const onPlayerModal = segments.includes("player")
|
||||
// const onAuthFlow =
|
||||
// segments.includes("signin") ||
|
||||
// segments.includes("signup") ||
|
||||
// segments.includes("server")
|
||||
// const onTabs = segments.includes("(tabs)")
|
||||
//
|
||||
// const bottom = insets.bottom + (onTabs ? 0 : 0)
|
||||
//
|
||||
// return {
|
||||
// bottom,
|
||||
// hidden: onPlayerModal || onAuthFlow || onTabs,
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// export function FloatingMiniPlayer() {
|
||||
// const router = useRouter()
|
||||
// const { bottom, hidden } = useFloatingMiniPlayerLayout()
|
||||
// const { currentSong, queueSongIds } = usePlayback()
|
||||
//
|
||||
// if (hidden || !currentSong || queueSongIds.length === 0) {
|
||||
// return null
|
||||
// }
|
||||
//
|
||||
// return (
|
||||
// <View pointerEvents="box-none" style={[styles.floatingContainer, { bottom }]}>
|
||||
// <MiniPlayerChrome>
|
||||
// <MiniPlayerContent onOpenPlayer={() => router.push("/player")} />
|
||||
// </MiniPlayerChrome>
|
||||
// </View>
|
||||
// )
|
||||
// }
|
||||
/** NativeTabs.BottomAccessory only renders on iOS. */
|
||||
export function AndroidMiniPlayer() {
|
||||
const router = useRouter()
|
||||
const insets = useSafeAreaInsets()
|
||||
const { currentSong, queueSongIds } = usePlaybackQueue()
|
||||
if (Platform.OS !== "android" || !currentSong || queueSongIds.length === 0) {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
<View
|
||||
style={[
|
||||
styles.floatingContainer,
|
||||
{ bottom: tabBarHeight + insets.bottom },
|
||||
]}
|
||||
>
|
||||
<MiniPlayerChrome>
|
||||
<MiniPlayerContent
|
||||
placement="regular"
|
||||
variant="bar"
|
||||
onOpenPlayer={() => router.push("/player")}
|
||||
/>
|
||||
</MiniPlayerChrome>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
floatingContainer: {
|
||||
|
||||
@@ -34,6 +34,7 @@ export function PlayerSlider({
|
||||
leading,
|
||||
trailing,
|
||||
accessibilityLabel,
|
||||
commitHoldMs = COMMIT_HOLD_MS,
|
||||
}: {
|
||||
value: number
|
||||
maximumValue: number
|
||||
@@ -46,6 +47,8 @@ export function PlayerSlider({
|
||||
leading?: ReactNode
|
||||
trailing?: ReactNode
|
||||
accessibilityLabel: string
|
||||
/** Seeking needs a hold while playback catches up; system volume does not. */
|
||||
commitHoldMs?: number
|
||||
}) {
|
||||
const max = maximumValue > 0 ? maximumValue : 1
|
||||
const fraction = useSharedValue(clamp(value / max))
|
||||
@@ -64,16 +67,28 @@ export function PlayerSlider({
|
||||
onValueChange,
|
||||
onSlidingStart,
|
||||
onSlidingComplete,
|
||||
value,
|
||||
commitHoldMs,
|
||||
max,
|
||||
})
|
||||
callbacks.current = { onValueChange, onSlidingStart, onSlidingComplete, max }
|
||||
callbacks.current = {
|
||||
onValueChange,
|
||||
onSlidingStart,
|
||||
onSlidingComplete,
|
||||
value,
|
||||
commitHoldMs,
|
||||
max,
|
||||
}
|
||||
|
||||
const gesture = useMemo(() => {
|
||||
const start = () => callbacks.current.onSlidingStart?.()
|
||||
const change = (next: number) =>
|
||||
callbacks.current.onValueChange?.(next * callbacks.current.max)
|
||||
const complete = (next: number) => {
|
||||
holdUntil.current = Date.now() + COMMIT_HOLD_MS
|
||||
holdUntil.current = Date.now() + callbacks.current.commitHoldMs
|
||||
if (callbacks.current.commitHoldMs === 0) {
|
||||
fraction.value = clamp(callbacks.current.value / callbacks.current.max)
|
||||
}
|
||||
callbacks.current.onSlidingComplete?.(next * callbacks.current.max)
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,6 @@ import {
|
||||
type ReactNode,
|
||||
} from "react"
|
||||
import { AppState } from "react-native"
|
||||
import AsyncStorage from "@react-native-async-storage/async-storage"
|
||||
|
||||
import {
|
||||
ANONYMOUS_CACHE_SCOPE,
|
||||
@@ -57,8 +56,6 @@ import {
|
||||
const PREVIOUS_TRACK_RESTART_THRESHOLD_SECONDS = 5
|
||||
const PROGRESS_SAVE_INTERVAL_MS = 5000
|
||||
const PREFETCH_UPCOMING_SONGS = 5
|
||||
const VOLUME_STORAGE_KEY = "otunes:volume"
|
||||
const DEFAULT_VOLUME = 0.8
|
||||
|
||||
function lockScreenMetadata(
|
||||
song: BrowseSong,
|
||||
@@ -79,13 +76,11 @@ type PlaybackContextValue = {
|
||||
shuffleEnabled: boolean
|
||||
repeatEnabled: RepeatMode
|
||||
isPlaying: boolean
|
||||
volume: number
|
||||
currentTime: number
|
||||
duration: number
|
||||
seekTo: (seconds: number) => void
|
||||
waitForPlaybackReady: (playing?: boolean) => Promise<void>
|
||||
setIsPlaying: (playing: boolean) => void
|
||||
setVolume: (volume: number) => void
|
||||
playInOrder: (songIds: Id<"songs">[]) => Promise<void>
|
||||
playShuffled: (songIds: Id<"songs">[]) => Promise<void>
|
||||
addToQueueNext: (songIds: Id<"songs">[]) => Promise<void>
|
||||
@@ -268,9 +263,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
const seekInFlightRef = useRef(false)
|
||||
const loadRequestIdRef = useRef(0)
|
||||
const playRequestRef = useRef(0)
|
||||
const volumeRef = useRef(DEFAULT_VOLUME)
|
||||
const volumeChangedRef = useRef(false)
|
||||
const volumeSaveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const ignoreTrackChangeTimerRef = useRef<ReturnType<
|
||||
typeof setTimeout
|
||||
> | null>(null)
|
||||
@@ -278,7 +270,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
const [isPlaying, setIsPlayingState] = useState(false)
|
||||
const [currentTime, setCurrentTime] = useState(0)
|
||||
const [measuredDuration, setDuration] = useState(0)
|
||||
const [volume, setVolumeState] = useState(DEFAULT_VOLUME)
|
||||
const [progressToRestore, setProgressToRestore] = useState<number | null>(
|
||||
null
|
||||
)
|
||||
@@ -466,7 +457,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
updateInterval: 500,
|
||||
loop: repeatToPlaylistLoop(storeRef.current.getState().repeatEnabled),
|
||||
})
|
||||
playlist.volume = volumeRef.current
|
||||
// System volume controls loudness; keep the player gain at full scale.
|
||||
playlist.volume = 1
|
||||
statusSubscriptionRef.current = playlist.addListener(
|
||||
"playlistStatusUpdate",
|
||||
handlePlaylistStatusUpdate
|
||||
@@ -498,42 +490,12 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
}
|
||||
})
|
||||
|
||||
void AsyncStorage.getItem(VOLUME_STORAGE_KEY)
|
||||
.then((stored) => {
|
||||
if (!cancelled && !volumeChangedRef.current && stored) {
|
||||
const parsed = Number(stored)
|
||||
if (Number.isFinite(parsed)) {
|
||||
const restoredVolume = Math.min(1, Math.max(0, parsed))
|
||||
volumeRef.current = restoredVolume
|
||||
setVolumeState(restoredVolume)
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch(() => {})
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
if (volumeSaveTimerRef.current) {
|
||||
clearTimeout(volumeSaveTimerRef.current)
|
||||
volumeSaveTimerRef.current = null
|
||||
}
|
||||
if (volumeChangedRef.current) {
|
||||
void AsyncStorage.setItem(
|
||||
VOLUME_STORAGE_KEY,
|
||||
String(volumeRef.current)
|
||||
).catch(() => {})
|
||||
}
|
||||
destroyPlaylist()
|
||||
}
|
||||
}, [destroyPlaylist])
|
||||
|
||||
useEffect(() => {
|
||||
volumeRef.current = volume
|
||||
if (playlistRef.current) {
|
||||
playlistRef.current.volume = volume
|
||||
}
|
||||
}, [volume])
|
||||
|
||||
useEffect(() => {
|
||||
const playlist = playlistRef.current
|
||||
if (playlist) {
|
||||
@@ -553,25 +515,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
}
|
||||
}, [])
|
||||
|
||||
const setVolume = useCallback((nextVolume: number) => {
|
||||
const clamped = Math.min(1, Math.max(0, nextVolume))
|
||||
volumeChangedRef.current = true
|
||||
volumeRef.current = clamped
|
||||
setVolumeState(clamped)
|
||||
if (volumeSaveTimerRef.current) {
|
||||
clearTimeout(volumeSaveTimerRef.current)
|
||||
}
|
||||
volumeSaveTimerRef.current = setTimeout(() => {
|
||||
volumeSaveTimerRef.current = null
|
||||
void AsyncStorage.setItem(VOLUME_STORAGE_KEY, String(clamped)).catch(
|
||||
() => {}
|
||||
)
|
||||
}, 250)
|
||||
if (playlistRef.current) {
|
||||
playlistRef.current.volume = clamped
|
||||
}
|
||||
}, [])
|
||||
|
||||
const seekTo = useCallback(
|
||||
async (seconds: number) => {
|
||||
const playlist = playlistRef.current
|
||||
@@ -704,7 +647,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
playlist.skipTo(currentIndex)
|
||||
}
|
||||
playlist.loop = repeatToPlaylistLoop(repeatEnabled)
|
||||
playlist.volume = volumeRef.current
|
||||
if (metadata) {
|
||||
updatePlaylistLockScreenMetadata(playlist, metadata)
|
||||
}
|
||||
@@ -818,7 +760,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
}
|
||||
loadedSongIdsRef.current = windowSongIds
|
||||
loadedLoadKeyRef.current = loadKey
|
||||
playlist.volume = volumeRef.current
|
||||
playlist.loop = repeatToPlaylistLoop(repeatEnabled)
|
||||
activatePlaylistLockScreen(
|
||||
playlist,
|
||||
@@ -1345,11 +1286,9 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
shuffleEnabled: playback.shuffleEnabled,
|
||||
repeatEnabled,
|
||||
isPlaying: isPlaybackActive,
|
||||
volume,
|
||||
currentTime,
|
||||
duration,
|
||||
seekTo,
|
||||
setVolume,
|
||||
}),
|
||||
[
|
||||
actionsValue,
|
||||
@@ -1363,8 +1302,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
queueSongIds,
|
||||
repeatEnabled,
|
||||
seekTo,
|
||||
setVolume,
|
||||
volume,
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { requireOptionalNativeModule, type EventEmitter } from "expo"
|
||||
import { useCallback, useEffect, useState } from "react"
|
||||
import { AppState } from "react-native"
|
||||
|
||||
type VolumeState = { volume: number; available: boolean }
|
||||
type VolumeEvents = { onVolumeChange: (state: VolumeState) => void }
|
||||
interface SystemVolumeModule extends EventEmitter<VolumeEvents> {
|
||||
getState(): Promise<VolumeState>
|
||||
setVolume(volume: number): Promise<void>
|
||||
}
|
||||
|
||||
const native = requireOptionalNativeModule<SystemVolumeModule>("SystemVolume")
|
||||
|
||||
/** The device owns volume. Never restore an app-specific level on launch. */
|
||||
export function useSystemVolume() {
|
||||
const [state, setState] = useState<VolumeState>({
|
||||
volume: 0,
|
||||
available: false,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (!native) return
|
||||
let active = true
|
||||
let revision = 0
|
||||
const listener = native.addListener("onVolumeChange", (next) => {
|
||||
revision++
|
||||
if (active) setState(next)
|
||||
})
|
||||
const refresh = async () => {
|
||||
const requestedRevision = ++revision
|
||||
try {
|
||||
const next = await native.getState()
|
||||
if (active && requestedRevision === revision) setState(next)
|
||||
} catch {
|
||||
if (active && requestedRevision === revision) {
|
||||
setState((value) => ({ ...value, available: false }))
|
||||
}
|
||||
}
|
||||
}
|
||||
void refresh()
|
||||
const foreground = AppState.addEventListener("change", (next) => {
|
||||
if (next === "active") void refresh()
|
||||
})
|
||||
return () => {
|
||||
active = false
|
||||
listener.remove()
|
||||
foreground.remove()
|
||||
}
|
||||
}, [])
|
||||
|
||||
const setVolume = useCallback((value: number) => {
|
||||
if (!native || !Number.isFinite(value)) return
|
||||
const volume = Math.min(1, Math.max(0, value))
|
||||
void native.setVolume(volume).catch(() => {
|
||||
setState((current) => ({ ...current, available: false }))
|
||||
})
|
||||
}, [])
|
||||
|
||||
return { ...state, setVolume }
|
||||
}
|
||||
@@ -84,13 +84,13 @@ export const radius = {
|
||||
} as const
|
||||
|
||||
export const miniPlayerHeight = 56
|
||||
export const tabBarHeight = Platform.OS === "ios" ? 49 : 56
|
||||
export const tabBarHeight = Platform.OS === "ios" ? 49 : 80
|
||||
export const playerBarHeight = miniPlayerHeight
|
||||
export const carouselCardWidth = 160
|
||||
|
||||
export function useTwoColumnCardWidth(
|
||||
horizontalPadding = spacing.lg,
|
||||
gap = spacing.md,
|
||||
gap = spacing.md
|
||||
) {
|
||||
const { width } = useWindowDimensions()
|
||||
return Math.floor((width - horizontalPadding * 2 - gap) / 2)
|
||||
|
||||
@@ -86,8 +86,13 @@ export function songAudioSource(
|
||||
: undefined
|
||||
const name = options?.songTitle
|
||||
|
||||
if (headers || name) {
|
||||
return { uri, ...(name ? { name } : {}), ...(headers ? { headers } : {}) }
|
||||
if (headers || name || useHls) {
|
||||
return {
|
||||
uri,
|
||||
...(useHls ? { mimeType: "application/x-mpegURL" } : {}),
|
||||
...(name ? { name } : {}),
|
||||
...(headers ? { headers } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
return uri
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.abunchofknowitalls.otunes
|
||||
|
||||
import android.content.Context
|
||||
import android.database.ContentObserver
|
||||
import android.media.AudioManager
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.provider.Settings
|
||||
import expo.modules.kotlin.functions.Queues
|
||||
import expo.modules.kotlin.modules.Module
|
||||
import expo.modules.kotlin.modules.ModuleDefinition
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
class SystemVolume : Module() {
|
||||
private val context get() = requireNotNull(appContext.reactContext)
|
||||
private val audio get() = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
|
||||
private var observer: ContentObserver? = null
|
||||
private var lastState: Map<String, Any>? = null
|
||||
|
||||
override fun definition() = ModuleDefinition {
|
||||
Name("SystemVolume")
|
||||
Events("onVolumeChange")
|
||||
|
||||
AsyncFunction("getState") { state() }.runOnQueue(Queues.MAIN)
|
||||
|
||||
AsyncFunction("setVolume") { value: Double ->
|
||||
if (value.isFinite() && available()) {
|
||||
val maximum = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
|
||||
val minimum = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||
audio.getStreamMinVolume(AudioManager.STREAM_MUSIC)
|
||||
} else {
|
||||
0
|
||||
}
|
||||
val index = (value.coerceIn(0.0, 1.0) * maximum).roundToInt().coerceIn(minimum, maximum)
|
||||
audio.setStreamVolume(AudioManager.STREAM_MUSIC, index, 0)
|
||||
publishState()
|
||||
}
|
||||
}.runOnQueue(Queues.MAIN)
|
||||
|
||||
OnStartObserving {
|
||||
lastState = null
|
||||
observer = object : ContentObserver(Handler(Looper.getMainLooper())) {
|
||||
override fun onChange(selfChange: Boolean) = publishState()
|
||||
}.also {
|
||||
context.contentResolver.registerContentObserver(Settings.System.CONTENT_URI, true, it)
|
||||
}
|
||||
}
|
||||
|
||||
OnStopObserving { stopObserving() }
|
||||
OnDestroy { stopObserving() }
|
||||
}
|
||||
|
||||
private fun available(): Boolean =
|
||||
!audio.isVolumeFixed && audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC) > 0
|
||||
|
||||
private fun state(): Map<String, Any> {
|
||||
val maximum = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
|
||||
return mapOf(
|
||||
"volume" to if (maximum > 0) audio.getStreamVolume(AudioManager.STREAM_MUSIC).toDouble() / maximum else 0.0,
|
||||
"available" to available()
|
||||
)
|
||||
}
|
||||
|
||||
private fun publishState() {
|
||||
val next = state()
|
||||
if (next != lastState) {
|
||||
lastState = next
|
||||
sendEvent("onVolumeChange", next)
|
||||
}
|
||||
}
|
||||
|
||||
private fun stopObserving() {
|
||||
observer?.let { context.contentResolver.unregisterContentObserver(it) }
|
||||
observer = null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import AVFAudio
|
||||
import MediaPlayer
|
||||
import UIKit
|
||||
internal import ExpoModulesCore
|
||||
|
||||
/// Bridges system volume without changing the playback audio session or player gain.
|
||||
final class SystemVolume: Module {
|
||||
private var volumeView: MPVolumeView?
|
||||
private var observation: NSKeyValueObservation?
|
||||
|
||||
public func definition() -> ExpoModulesCore.ModuleDefinition {
|
||||
Name("SystemVolume")
|
||||
Events("onVolumeChange")
|
||||
|
||||
AsyncFunction("getState") { () -> [String: Any] in
|
||||
self.prepareVolumeView()
|
||||
return self.state()
|
||||
}.runOnQueue(.main)
|
||||
|
||||
AsyncFunction("setVolume") { (value: Double) in
|
||||
self.prepareVolumeView()
|
||||
guard value.isFinite,
|
||||
let slider = self.volumeView?.subviews.compactMap({ $0 as? UISlider }).first
|
||||
else { return }
|
||||
slider.setValue(Float(min(1, max(0, value))), animated: false)
|
||||
slider.sendActions(for: .valueChanged)
|
||||
slider.sendActions(for: .touchUpInside)
|
||||
}.runOnQueue(.main)
|
||||
|
||||
OnStartObserving {
|
||||
self.observation = AVAudioSession.sharedInstance().observe(
|
||||
\.outputVolume, options: [.new]
|
||||
) { [weak self] _, _ in
|
||||
guard let self else { return }
|
||||
self.sendEvent("onVolumeChange", self.state())
|
||||
}
|
||||
}
|
||||
|
||||
OnStopObserving {
|
||||
self.observation = nil
|
||||
}
|
||||
|
||||
OnDestroy {
|
||||
self.observation = nil
|
||||
let view = self.volumeView
|
||||
self.volumeView = nil
|
||||
DispatchQueue.main.async { view?.removeFromSuperview() }
|
||||
}
|
||||
}
|
||||
|
||||
private func prepareVolumeView() {
|
||||
#if !targetEnvironment(simulator)
|
||||
if volumeView == nil {
|
||||
// MPVolumeView must belong to a window to control the device's volume.
|
||||
let view = MPVolumeView(frame: CGRect(x: -200, y: -200, width: 120, height: 30))
|
||||
view.showsRouteButton = false
|
||||
volumeView = view
|
||||
}
|
||||
if volumeView?.window == nil {
|
||||
let window = UIApplication.shared.connectedScenes
|
||||
.compactMap { $0 as? UIWindowScene }
|
||||
.flatMap { $0.windows }
|
||||
.first { $0.isKeyWindow }
|
||||
if let volumeView { window?.addSubview(volumeView) }
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
private func state() -> [String: Any] {
|
||||
#if targetEnvironment(simulator)
|
||||
// Simulator's host audio controls do not update AVAudioSession.outputVolume.
|
||||
let available = false
|
||||
#else
|
||||
// The control remains visible on physical iPhones, including during route changes.
|
||||
let available = true
|
||||
#endif
|
||||
return ["volume": AVAudioSession.sharedInstance().outputVolume, "available": available]
|
||||
}
|
||||
}
|
||||
@@ -57,5 +57,12 @@
|
||||
"@types/react": "~19.3.0",
|
||||
"babel-preset-expo": "^58.0.18",
|
||||
"typescript": "~6.0.3"
|
||||
},
|
||||
"expo": {
|
||||
"autolinking": {
|
||||
"buildFromSource": [
|
||||
"expo-audio"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ diff --git a/ios/AudioPlaylist.swift b/ios/AudioPlaylist.swift
|
||||
@@ -179,20 +179,31 @@
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
- let wasPlaying = isPlaying
|
||||
- let resumeIndex: Int
|
||||
- if ref.currentItem != nil {
|
||||
@@ -13,7 +13,7 @@ diff --git a/ios/AudioPlaylist.swift b/ios/AudioPlaylist.swift
|
||||
- resumeIndex = index
|
||||
- }
|
||||
sources.insert(source, at: index)
|
||||
|
||||
|
||||
- previousTrackIndex = resumeIndex
|
||||
- rebuildPlaylist(startingAt: resumeIndex)
|
||||
- if wasPlaying {
|
||||
@@ -43,7 +43,7 @@ diff --git a/ios/AudioPlaylist.swift b/ios/AudioPlaylist.swift
|
||||
+
|
||||
updateStatus(with: ["trackCount": trackCount])
|
||||
}
|
||||
|
||||
|
||||
@@ -213,12 +224,11 @@
|
||||
play(at: currentRate)
|
||||
}
|
||||
@@ -61,3 +61,101 @@ diff --git a/ios/AudioPlaylist.swift b/ios/AudioPlaylist.swift
|
||||
} else if index < playerItems.count {
|
||||
if let item = playerItems[index] {
|
||||
ref.remove(item)
|
||||
diff --git a/android/src/main/java/expo/modules/audio/AudioPlaylist.kt b/android/src/main/java/expo/modules/audio/AudioPlaylist.kt
|
||||
--- a/android/src/main/java/expo/modules/audio/AudioPlaylist.kt
|
||||
+++ b/android/src/main/java/expo/modules/audio/AudioPlaylist.kt
|
||||
@@ -9,2 +9,3 @@
|
||||
import androidx.media3.exoplayer.ExoPlayer
|
||||
+import androidx.media3.exoplayer.source.MediaSource
|
||||
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
|
||||
@@ -53,3 +54,3 @@
|
||||
|
||||
- private var createMediaItemForSource: ((AudioSource) -> MediaItem?)? = null
|
||||
+ private var createMediaSourceForSource: ((AudioSource) -> MediaSource?)? = null
|
||||
|
||||
@@ -60,4 +61,4 @@
|
||||
|
||||
- fun setMediaItemCreator(creator: (AudioSource) -> MediaItem?) {
|
||||
- this.createMediaItemForSource = creator
|
||||
+ fun setMediaSourceCreator(creator: (AudioSource) -> MediaSource?) {
|
||||
+ this.createMediaSourceForSource = creator
|
||||
}
|
||||
@@ -67,5 +68,5 @@
|
||||
sources.forEach { source ->
|
||||
- createMediaItemForSource?.invoke(source)?.let { mediaItem ->
|
||||
+ createMediaSourceForSource?.invoke(source)?.let { mediaItem ->
|
||||
validSources.add(source)
|
||||
- ref.addMediaItem(mediaItem)
|
||||
+ ref.addMediaSource(mediaItem)
|
||||
}
|
||||
@@ -151,5 +152,5 @@
|
||||
fun add(source: AudioSource) {
|
||||
- val mediaItem = createMediaItemForSource?.invoke(source) ?: return
|
||||
+ val mediaItem = createMediaSourceForSource?.invoke(source) ?: return
|
||||
sources.add(source)
|
||||
- ref.addMediaItem(mediaItem)
|
||||
+ ref.addMediaSource(mediaItem)
|
||||
sendStatusUpdate(mapOf("trackCount" to trackCount))
|
||||
@@ -161,5 +162,5 @@
|
||||
}
|
||||
- val mediaItem = createMediaItemForSource?.invoke(source) ?: return
|
||||
+ val mediaItem = createMediaSourceForSource?.invoke(source) ?: return
|
||||
sources.add(index, source)
|
||||
- ref.addMediaItem(index, mediaItem)
|
||||
+ ref.addMediaSource(index, mediaItem)
|
||||
sendStatusUpdate(mapOf("trackCount" to trackCount))
|
||||
diff --git a/android/src/main/java/expo/modules/audio/AudioModule.kt b/android/src/main/java/expo/modules/audio/AudioModule.kt
|
||||
--- a/android/src/main/java/expo/modules/audio/AudioModule.kt
|
||||
+++ b/android/src/main/java/expo/modules/audio/AudioModule.kt
|
||||
@@ -909,14 +909,4 @@
|
||||
playlist.loopMode = loop
|
||||
- playlist.setMediaItemCreator { source ->
|
||||
- source.uri?.let { uriString ->
|
||||
- val uri = uriString.toUri()
|
||||
- when {
|
||||
- isRawResource(uri) -> {
|
||||
- val file = getResourceName(uri, uriString)
|
||||
- MediaItem.fromUri(getRawResourceURI(file))
|
||||
- }
|
||||
- else -> MediaItem.fromUri(uri)
|
||||
- }
|
||||
- }
|
||||
- }
|
||||
+ // Use the same per-source headers and stream type as standalone players.
|
||||
+ playlist.setMediaSourceCreator { source -> createMediaItem(source) }
|
||||
playlist.loadInitialPlaylist()
|
||||
@@ -1130,3 +1120,3 @@
|
||||
}
|
||||
- else -> MediaItem.fromUri(uri)
|
||||
+ else -> MediaItem.Builder().setUri(uri).setMimeType(source.mimeType).build()
|
||||
}
|
||||
@@ -1196,3 +1186,3 @@
|
||||
val uri = mediaItem.localConfiguration?.uri
|
||||
- return when (val type = uri?.let { retrieveStreamType(it) }) {
|
||||
+ return when (val type = uri?.let { Util.inferContentTypeForUriAndMimeType(it, mediaItem.localConfiguration?.mimeType) }) {
|
||||
CONTENT_TYPE_SS -> SsMediaSource.Factory(factory)
|
||||
diff --git a/android/src/main/java/expo/modules/audio/AudioRecords.kt b/android/src/main/java/expo/modules/audio/AudioRecords.kt
|
||||
--- a/android/src/main/java/expo/modules/audio/AudioRecords.kt
|
||||
+++ b/android/src/main/java/expo/modules/audio/AudioRecords.kt
|
||||
@@ -15,3 +15,4 @@
|
||||
@Field val headers: Map<String, String>?,
|
||||
- @Field val name: String? = null
|
||||
+ @Field val name: String? = null,
|
||||
+ @Field val mimeType: String? = null
|
||||
) : Record
|
||||
diff --git a/src/Audio.types.ts b/src/Audio.types.ts
|
||||
--- a/src/Audio.types.ts
|
||||
+++ b/src/Audio.types.ts
|
||||
@@ -38,2 +38,4 @@
|
||||
headers?: Record<string, string>;
|
||||
+ /** MIME type for streams whose URL has no file extension, such as HLS. */
|
||||
+ mimeType?: string;
|
||||
/**
|
||||
diff --git a/build/Audio.types.d.ts b/build/Audio.types.d.ts
|
||||
--- a/build/Audio.types.d.ts
|
||||
+++ b/build/Audio.types.d.ts
|
||||
@@ -31,2 +31,4 @@
|
||||
headers?: Record<string, string>;
|
||||
+ /** MIME type for streams whose URL has no file extension, such as HLS. */
|
||||
+ mimeType?: string;
|
||||
/**
|
||||
Generated
+3
-3
@@ -6,7 +6,7 @@ settings:
|
||||
|
||||
patchedDependencies:
|
||||
expo-audio@58.0.10:
|
||||
hash: 316b70cb0213ecf24723e4074c1bde7ef15a627e8bf5d8f938c0be9965f1b4e8
|
||||
hash: e01ad6e484db76d810c2df5bf9c376eccf8d4c5359736b626868ea8bd8dac566
|
||||
path: patches/expo-audio@58.0.10.patch
|
||||
|
||||
importers:
|
||||
@@ -63,7 +63,7 @@ importers:
|
||||
version: 58.0.18(expo@58.0.17)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0)(typescript@6.0.3)
|
||||
expo-audio:
|
||||
specifier: ~58.0.10
|
||||
version: 58.0.10(patch_hash=316b70cb0213ecf24723e4074c1bde7ef15a627e8bf5d8f938c0be9965f1b4e8)(expo-asset@58.0.18(expo@58.0.17)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0)(typescript@6.0.3))(expo@58.0.17)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0)
|
||||
version: 58.0.10(patch_hash=e01ad6e484db76d810c2df5bf9c376eccf8d4c5359736b626868ea8bd8dac566)(expo-asset@58.0.18(expo@58.0.17)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0)(typescript@6.0.3))(expo@58.0.17)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0)
|
||||
expo-blur:
|
||||
specifier: ~58.0.5
|
||||
version: 58.0.5(expo@58.0.17)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0)
|
||||
@@ -11050,7 +11050,7 @@ snapshots:
|
||||
- supports-color
|
||||
- typescript
|
||||
|
||||
expo-audio@58.0.10(patch_hash=316b70cb0213ecf24723e4074c1bde7ef15a627e8bf5d8f938c0be9965f1b4e8)(expo-asset@58.0.18(expo@58.0.17)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0)(typescript@6.0.3))(expo@58.0.17)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0):
|
||||
expo-audio@58.0.10(patch_hash=e01ad6e484db76d810c2df5bf9c376eccf8d4c5359736b626868ea8bd8dac566)(expo-asset@58.0.18(expo@58.0.17)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0)(typescript@6.0.3))(expo@58.0.17)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0):
|
||||
dependencies:
|
||||
expo: 58.0.17(@babel/core@7.29.7)(@expo/dom-webview@58.0.2)(@expo/metro-runtime@58.0.15)(expo-router@58.0.25)(react-dom@19.3.0(react@19.3.0))(react-native-worklets@0.13.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7))(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0))(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0)(typescript@6.0.3)
|
||||
expo-asset: 58.0.18(expo@58.0.17)(react-native@0.88.0(@babel/core@7.29.7)(@react-native/metro-config@0.88.0(@babel/core@7.29.7))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0)(typescript@6.0.3)
|
||||
|
||||
Reference in new issue
Block a user