Howler.js多音频变量无法在onKeyDown事件中播放求助
Hey there! Let's troubleshoot this keyboard-triggered audio issue with Howler.js together—since you confirmed the audio plays fine alone, we just need to fix the connection between keystrokes and the sound playback.
First, let's start with a working example you can test
Here's a complete, minimal implementation that should work—we'll break down the potential issues after:
// 1. Create a map linking keys to Howler audio instances const keySoundMap = { 'a': new Howl({ src: ['sound.wav'], // Double-check this path matches your file's location relative to your HTML volume: 0.7 // Optional: adjust volume to avoid surprises }), 's': new Howl({ src: ['sound.wav'] }) // Add more key-audio pairs here as needed }; // 2. Make sure we bind events only after the DOM is ready document.addEventListener('DOMContentLoaded', () => { document.addEventListener('keydown', handleKeyPress); }); // 3. The keydown handler function function handleKeyPress(e) { // Normalize key to lowercase to avoid case sensitivity issues const pressedKey = e.key.toLowerCase(); // Debug: Log the pressed key to confirm we're capturing it correctly console.log('Pressed key:', pressedKey); // Check if our map has a sound for this key, then play it if (keySoundMap[pressedKey]) { keySoundMap[pressedKey].play(); // Optional: Prevent default browser behavior (e.g., spacebar scrolling) e.preventDefault(); } else { console.log('No sound mapped to this key:', pressedKey); } }
Now let's go through the most common issues that might be breaking your code:
Event binding timing is off
If your script runs before the DOM finishes loading, the event listener might not attach properly. Always wrap your event binding inDOMContentLoadedor place your<script>tag at the very end of the<body>tag.Key matching errors
Using deprecated properties likee.keyCodecan cause inconsistencies (since key codes don't map cleanly to actual keys). Stick toe.keyinstead, and normalize it to lowercase/uppercase to match your map entries (e.g., if your map uses 'a', a user pressing Shift+A will still trigger it with.toLowerCase()).Incorrect audio path in Howler
Even if the audio plays alone, double-check thesrcpath in your Howl instance. If your audio is in a subfolder likeassets/sound.wav, make sure the path reflects that—relative paths are based on your HTML file's location, not the JS file.Howler instances aren't cached
If you're creating a new Howl instance every time a key is pressed, it might cause delays or failures. Storing instances in an object (likekeySoundMapabove) ensures they're initialized once and ready to play instantly.Browser auto-play restrictions
Modern browsers block audio that isn't triggered by a user interaction. Sincekeydownis a valid user interaction, this should only be an issue if you tried to auto-play audio on page load before the first keypress. If that's the case, make sure your first audio playback is explicitly tied to a keystroke.
Debugging tips to narrow it down:
- Open your browser's dev tools (F12) and check the Console tab for errors.
- Add
console.log(e.key)in youronKeyDownfunction to confirm you're capturing the correct key value. - Log
keySoundMap[pressedKey]to verify the Howler instance exists for the pressed key.
内容的提问来源于stack exchange,提问作者iBim's da Michi

