网页应用中实现切换音频时自动暂停当前播放音频的技术求助
Hey there! I totally get where you're coming from—when you're just starting out with front-end development, handling audio playback can feel tricky. Let's break down why your current code is having that "multiple audio playing at once" problem, and how to fix it so you can pause/resume tracks smoothly.
The Problem with Your Current Code
Every time you click an artist image, you're creating a new Audio object from scratch. That means you lose all control over the previous audio instance—so it keeps playing in the background because you can't access it to pause it anymore. Also, since you're creating a new instance every time, you can't pick up where you left off if you pause and come back to the same artist.
Solution 1: Track the Current Audio Instance
First, we'll add a variable to keep track of the currently active audio. Then, we'll update your function to pause the current audio before starting a new one, and handle pause/resume for the same track.
Here's the updated code:
// Keep track of the currently playing audio instance let currentAudio = null; function switchCase(key){ // Pause any currently playing audio first if (currentAudio) { currentAudio.pause(); } // Map each image key to its audio file path (cleaner than a switch!) const audioPaths = { 'mozart-img': 'sounds/mozart.mp3', 'beethoven-img': 'sounds/beethoven.mp3', 'chopin-img': 'sounds/chopin.mp3', 'schumann-img': 'sounds/schumann.mp3' }; // Check if we're clicking the same artist again if (currentAudio && currentAudio.src.includes(audioPaths[key])) { // Toggle play/pause if it's the same track if (currentAudio.paused) { currentAudio.play(); } else { currentAudio.pause(); } return; } // Create a new audio instance for the new artist and play it currentAudio = new Audio(audioPaths[key]); currentAudio.play(); }
How This Works:
currentAudiostores the active audio object, so we can always pause it when switching tracks.- We use an object (
audioPaths) to map image keys to their audio files—this is more maintainable than a long switch statement (you can easily add more artists later!). - If you click the same artist again, it toggles between play and pause, so you can resume from where you left off.
Even Better: Preload All Audio Instances
If you want to make sure each artist's audio remembers its exact playback position (even after switching to other tracks), preload all your audio instances upfront. This way, you're not creating new objects every time—you're just reusing existing ones.
// Preload all audio instances once (keeps track of playback position!) const audioInstances = { 'mozart-img': new Audio('sounds/mozart.mp3'), 'beethoven-img': new Audio('sounds/beethoven.mp3'), 'chopin-img': new Audio('sounds/chopin.mp3'), 'schumann-img': new Audio('sounds/schumann.mp3') }; // Track which artist is currently playing let currentArtistKey = null; function switchCase(key){ const targetAudio = audioInstances[key]; if (!targetAudio) return; // Exit if the key doesn't match any artist // If clicking the same artist, toggle play/pause if (currentArtistKey === key) { targetAudio.paused ? targetAudio.play() : targetAudio.pause(); return; } // Pause the previous artist's audio if (currentArtistKey) { audioInstances[currentArtistKey].pause(); } // Play the new artist's audio and update the current key targetAudio.play(); currentArtistKey = key; }
This version is even more robust:
- Each audio file is loaded once when the page loads (so no delay when clicking an artist for the first time).
- Every track retains its playback position—if you pause Mozart, switch to Beethoven, then come back to Mozart, it starts right where you left off.
Give either of these a try, and you'll have that smooth audio switching you're looking for!
内容的提问来源于stack exchange,提问作者bkaya0897

