如何构建Howler.js脚本实现SoundManager2同款按ID播放音频功能?
Convert SoundManager2 Audio Control to Howler.js
Got it! Let's replicate your existing SoundManager2 functionality with Howler.js, so you can keep using the same playAudio and stopAudio functions that reference audio IDs like "Song1". Here's a drop-in replacement setup that matches your workflow perfectly:
Full Working Code
<!DOCTYPE html> <script src="path/to/howler.min.js"></script> <script> // Store our Howler audio instances by their custom ID (mirrors your SoundManager2 "id" approach) const audioInstances = {}; // Initialize audio assets (equivalent to your soundManager.createSound in the onready callback) function initAudioAssets() { // Create and store your "Song1" audio instance audioInstances['Song1'] = new Howl({ src: ['audio/Song1.ogg'] // Add optional config here if needed: e.g., loop: false, volume: 1.0, preload: true }); // Add more audio instances here following the same pattern // audioInstances['Song2'] = new Howl({ src: ['audio/Song2.mp3'] }); } // Run initialization when the page is fully loaded (matches SoundManager's onready trigger) document.addEventListener('DOMContentLoaded', initAudioAssets); // Your familiar playAudio function (works with audio IDs like "Song1") function playAudio(snd) { if (audioInstances[snd]) { audioInstances[snd].play(); } else { console.warn(`No audio found with ID: "${snd}"`); } } // Your familiar stopAudio function (works with the same audio IDs) function stopAudio(snd) { if (audioInstances[snd]) { audioInstances[snd].stop(); } else { console.warn(`No audio found with ID: "${snd}"`); } } </script>
Key Details That Align With Your Original Setup
- Audio ID Mapping: The
audioInstancesobject acts like SoundManager2's internal storage, letting you reference audio by custom IDs (e.g., "Song1") just as you did before. - Initialization Flow:
initAudioAssetsruns once the page is ready, mirroring yoursoundManager.setuponreadycallback where you create all audio instances upfront. - Control Functions:
playAudioandstopAudiowork exactly like your original functions — pass an audio ID, and they'll handle play/stop actions. We added a quick error check to warn you if you reference an ID that doesn't exist, which helps with debugging.
Adding More Audio
To add additional sounds, just create new Howl instances inside initAudioAssets and store them in audioInstances with their own unique ID:
audioInstances['ButtonClick'] = new Howl({ src: ['audio/button-click.wav'], volume: 0.7 // Example of a Howler-specific configuration option });
Then you can control it the same way as before:
playAudio('ButtonClick'); stopAudio('ButtonClick');
内容的提问来源于stack exchange,提问作者taraz
相关产品推荐
相关产品推荐

