You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何构建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 audioInstances object acts like SoundManager2's internal storage, letting you reference audio by custom IDs (e.g., "Song1") just as you did before.
  • Initialization Flow: initAudioAssets runs once the page is ready, mirroring your soundManager.setup onready callback where you create all audio instances upfront.
  • Control Functions: playAudio and stopAudio work 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:35:52