如何用Howler.js以最少代码实现多音频文件播放?
Simplifying Multi-Audio Playback with Less Code
Absolutely! You can eliminate repetitive code by using a data-driven approach—define all your audio-button mappings in a single array, then loop through it to set up everything automatically. This way, adding a new audio file only requires adding one line to the array, no duplicate logic needed.
Refactored Code
First, keep your HTML buttons (add as many as you need):
<button class="btn" id="playBtn">play</button> <br> <button class="btn" id="playBtn2">play2</button> <!-- Add more buttons here, e.g.: --> <!-- <button class="btn" id="playBtn3">play3</button> -->
Then the JavaScript becomes concise and scalable:
// Define all your audio-button pairs in one place const audioPairs = [ { btnId: 'playBtn', audioUrl: 'https://www.oxfordlearnersdictionaries.com/media/english/uk_pron/f/f_1/f_1_g/f_1_gb_1_abbr.mp3' }, { btnId: 'playBtn2', audioUrl: 'https://www.oxfordlearnersdictionaries.com/media/english/us_pron/l/lov/love_/love__us_1.mp3' }, // Add new entries here for more audio files! // { btnId: 'playBtn3', audioUrl: 'your-new-audio-url.mp3' }, ]; // Loop through each pair to set up playback audioPairs.forEach(pair => { const button = document.getElementById(pair.btnId); const sound = new Howl({ src: [pair.audioUrl] }); button.addEventListener('click', () => sound.play()); });
How This Works
- Centralized Data: All your audio-button mappings live in the
audioPairsarray. This makes it easy to manage, edit, or add new entries without hunting through repeated code. - Automated Setup: The
forEachloop handles creating the Howl instance and attaching the click listener for every pair. No more copying and pasting the same script block for each audio file. - Scalability: Adding a new audio file takes two simple steps:
- Add a new button to your HTML with a unique ID.
- Add a new object to the
audioPairsarray linking that button ID to the new audio URL.
This approach keeps your code DRY (Don’t Repeat Yourself) and much easier to maintain as you add more audio files.
内容的提问来源于stack exchange,提问作者baha zou
相关产品推荐
相关产品推荐

