PHP中如何阻止页面跳转至音频路径?实现每日一词音频当前页播放
Got it, let's resolve this issue where clicking the word link redirects to the audio file instead of playing it directly on the page. We'll use a mix of PHP (for dynamic audio path handling) and vanilla JavaScript (to intercept clicks and handle playback with HTML5's <audio> element).
Step 1: Add a Hidden Audio Player to Your Page
First, insert a hidden <audio> element somewhere in your HTML (preferably before the closing </body> tag). This will handle the audio playback without needing to navigate away:
<audio id="wordAudioPlayer" style="display: none;"></audio>
Step 2: Modify Your Word Link & Add Playback Logic
Update your existing HTML (with PHP for dynamic content if needed) and add JavaScript to intercept the link click, prevent the redirect, and trigger playback.
Here's the full integrated code:
<?php // Example: Fetch dynamic word and audio path from your data source (database, API, etc.) $currentWord = "jocose"; $audioFilePath = "audio (1).mp3"; // Adjust this to your actual audio path (can be built dynamically, e.g., "audio/{$currentWord[0]}/{$currentWord}.mp3") ?> <div class="word-and-pronunciation"> <!-- Updated word link: we'll keep the href for fallback, but intercept clicks --> <a href="<?php echo $audioFilePath; ?>" tabindex="0" class="word-play-link"> <h2 class="word-l-hover"><?php echo $currentWord; ?></h2> </a> <!-- Existing pronunciation play button --> <a class="play-pron converted" data-lang="en_us" data-file="<?php echo $currentWord; ?>" data-dir="j" href="javascript:void(0)" title="How to pronounce jocose(audio)" tabindex="0"> play <span class="play-box">.</span> </a> </div> <!-- Hidden audio player --> <audio id="wordAudioPlayer" style="display: none;"></audio> <script> document.addEventListener('DOMContentLoaded', function() { const audioPlayer = document.getElementById('wordAudioPlayer'); // Handle clicks on the word link const wordPlayLink = document.querySelector('.word-play-link'); if (wordPlayLink) { wordPlayLink.addEventListener('click', function(e) { // Prevent the default redirect to the audio file e.preventDefault(); // Get the audio path from the link's href attribute const audioSrc = this.getAttribute('href'); // Load and play the audio audioPlayer.src = audioSrc; audioPlayer.play().catch(error => { console.error('Failed to play audio:', error); // Fallback: if playback fails, open the audio file in a new tab (optional) window.open(audioSrc, '_blank'); }); }); } // Optional: Make the existing "play" button use the same audio player const pronPlayButtons = document.querySelectorAll('.play-pron'); pronPlayButtons.forEach(button => { button.addEventListener('click', function(e) { e.preventDefault(); // Build the audio path using the button's data attributes const dir = this.getAttribute('data-dir'); const fileName = this.getAttribute('data-file'); const audioSrc = `audio/${dir}/${fileName}.mp3`; // Adjust this path to match your file structure audioPlayer.src = audioSrc; audioPlayer.play().catch(error => { console.error('Failed to play pronunciation:', error); }); }); }); }); </script>
Key Explanations:
- Prevent Redirect: The
e.preventDefault()in the click handler stops the browser from navigating to the audio file URL. - HTML5 Audio Element: The hidden
<audio>element handles playback directly on the page—no new tab or redirect needed. - Dynamic PHP Integration: If your daily word and audio paths are pulled from a database or generated dynamically, PHP can inject those values into the HTML and audio paths seamlessly.
- Fallback Option: We added a fallback to open the audio file in a new tab if playback fails (useful for older browsers or unexpected errors).
Notes:
- Ensure your audio file paths are correct (relative to your web root). If you're using a different structure (e.g.,
audio/en_us/j/jocose.mp3), adjust the path building logic in the JavaScript. - Modern browsers require user interaction (like a click) to play audio, which our solution respects—so playback will work as expected.
内容的提问来源于stack exchange,提问作者Rajendra Jadhav

