如何实现App后台停止主音轨播放并在前台恢复播放?
Got it, let's sort out this background audio playback issue for you. Here's exactly how to make your main track pause when the app goes to the background and resume when it comes back to the foreground:
Step 1: Add a Ref to Your Audio Component
First, you'll need a way to directly control the Audio component's playback state. Add a ref attribute to it so you can call its pause() and play() methods later.
Step 2: Listen for App State Changes
Next, you need to subscribe to your app's lifecycle events to detect when it moves between foreground and background. When the app goes to background, pause the audio; when it returns to foreground, resume playback.
Example Code (Adjust for Your Framework)
Here's a practical example using a React-based framework (like React Native or a web app with React):
import { useRef, useEffect } from 'react'; // For React Native, import AppState; for web, use document visibility API import { AppState } from 'react-native'; function YourRootAppComponent() { // Create a ref to access the Audio component instance const audioRef = useRef(null); useEffect(() => { // Handle app state changes const handleAppStateUpdate = (nextState) => { if (nextState === 'background') { // Pause audio when app goes to background audioRef.current?.pause(); } else if (nextState === 'active') { // Resume audio when app comes back to foreground audioRef.current?.play(); } }; // Subscribe to app state change events const stateSubscription = AppState.addEventListener('change', handleAppStateUpdate); // Clean up the subscription when component unmounts return () => { stateSubscription.remove(); }; }, []); return ( <App> <Audio ref={audioRef} source="../assets/Art Of Silence_V2.mp3" autoPlay={true} loops={Audio.Infinite} /> {/* Your other app components go here */} </App> ); }
Notes for Other Frameworks
- Web Apps: If you're building a web app, use the
document.visibilitychangeevent instead. Checkdocument.hiddento detect if the tab is in background:useEffect(() => { const handleVisibilityChange = () => { if (document.hidden) { audioRef.current?.pause(); } else { audioRef.current?.play(); } }; document.addEventListener('visibilitychange', handleVisibilityChange); return () => document.removeEventListener('visibilitychange', handleVisibilityChange); }, []); - Vue: Use
mountedandbeforeUnmounthooks to add/remove the visibility change listener, similar to the web example. - Ensure Audio Component APIs: Double-check that your
Audiocomponent exposespause()andplay()methods—most UI libraries or framework-native audio components include these by default.
内容的提问来源于stack exchange,提问作者Somayyah Mohammed

