Sound 音频系统

为 Game Object 添加音频控制的能力,使用 Web Audio API 播放。

安装

使用 NPM

  1. npm install @eva/plugin-sound

在浏览器中

  1. <script src="https://unpkg.com/@eva/plugin-sound@1.1.x/dist/EVA.plugin.sound.min.js"></script>

使用

  1. import { Game, GameObject, resource, RESOURCE_TYPE } from '@eva/eva.js';
  2. import { RendererSystem } from '@eva/plugin-renderer';
  3. import { Sound, SoundSystem } from '@eva/plugin-sound';
  4. // 添加音频资源
  5. resource.addResource([
  6. {
  7. name: 'bgSound',
  8. type: RESOURCE_TYPE.AUDIO,
  9. src: {
  10. audio: {
  11. type: 'audio',
  12. url: 'https://g.alicdn.com/ltao-fe/duck_assets/0.0.1/assets/duckBg.mp3',
  13. },
  14. },
  15. preload: true,
  16. },
  17. {
  18. name: 'successSound',
  19. src: {
  20. audio: {
  21. type: 'audio',
  22. url:
  23. 'https://g.alicdn.com/ltao-fe/factory/1.1.3/assets/game/sound/success.mp3',
  24. },
  25. },
  26. preload: true,
  27. },
  28. ]);
  29. const game = new Game({
  30. systems: [
  31. new RendererSystem({
  32. canvas: document.querySelector('#canvas'),
  33. width: 750,
  34. height: 1000,
  35. }),
  36. new SoundSystem();
  37. ],
  38. autoStart: true,
  39. frameRate: 60,
  40. });
  41. const bgSoundObj = new GameObject('sound');
  42. const bgSound = bgSoundObj.addComponent(
  43. new Sound({ resource: 'bgSound', loop: true, autoplay: true, volume: 0.5 })
  44. );
  45. bgSound.play();

如果想播放一部分音频,可以通过 seek 属性和 duration 属性来控制,具体参考属性表格,下面这个例子表示该 Component 从 1.2 秒开始播放,播放 3 秒后停止。

  1. const bgSound = bgSoundObj.addComponent(
  2. new Sound({ resource: 'bgSound', autoplay: true, volume: 0.5, seek: 1.2, duration: 3 })
  3. );

API

Sound

Constructor

| | resource | string | ‘’ | 在 resource 注册的音频资源名称 | | autoplay | boolean | false | 是否自动播放 | | muted | boolean | false | 是否被静音 | | loop | boolean | false | 播放结束时是否重新开始 | | volume | number | 1 | 播放时的音量(整体音量) ,取值范围0-1 | | seek | number | 0 | ArrayBufferSourceNode.start(when, seek, duration) MDN | | duration | number | | ArrayBufferSourceNode.start(when, seek, duration) MDN | | onEnd | () => void | - | 播放结束时触发 |

属性

| | muted | boolean | false | 可设置是否被静音 | | volume | number | 1 | 可设置播放时的音量,取值范围0-1 | | play | () => void | - | 尝试播放音频 | | pause | () => void | - | 用来暂停音频的播放,如果音频已经处于暂停状态,该方法没有效果。 | | stop | () => void | - | 停止播放音频 |

SoundSystem

Constructor

| | autoPauseAndStart | boolean | true | 是否和eva game同步暂停和启动 | | onError | (error) => void | - | 错误处理事件 |

属性

| | muted | boolean | false | 可设置是否被静音(所有音频) | | volume | number | 1 | 可设置播放时的音量(整体音量) ,取值范围0-1 | | resumeAll | () => void | - | 恢复播放所有被暂停的音频 | | pauseAll | () => void | - | 暂停所有正在播放的音频 | | stopAll | () => void | - | 停止播放所有正在播放的音频 |

提示

如果浏览器限制需要进行交互才可以开始播放音频,插件会自动尝试在页面进行交互后启用音频。