简体   繁体   English

Gamedesign将html5音频元素“分组”以静音和取消静音

[英]Gamedesign “group” html5 audio elements to mute and unmute

I am making a game, and I want to give the player the possibility to mute all sounds. 我正在做一个游戏,我想给玩家静音所有声音的可能性。

I call my audiofiles as following: 我将我的音频文件称为:

var STARTSCREEN     = new Audio('sounds/soundtrack-idle-24s.wav');
var GAMEPLAY        = new Audio('sounds/soundtrack-active-24s.wav');
var FX_BREAK        = new Audio('sounds/effect-break.wav');
var FX_BUBBLE       = new Audio('sounds/effect-bubble.wav');
var FX_EXPLOSION    = new Audio('sounds/effect-explosion.wav');

This works fine when I call the audio, for example, like this: 例如,当我调用音频时,这可以正常工作:

function startButtonClickHandler(event){
    GAMEPLAY.play();
}

I found a function to mute all sound with a button 我发现了一个功能,可以通过按钮使所有声音静音

muteButton = document.getElementById('mute-button');

function muteButtonClickHandler(event) {
    audio.muted = !audio.muted;
    event.preventDefault();
}

So I have to get all the audio 'grouped' as a var called audio . 所以,我必须让“组合”的所有音频var称为audio

But if i do the following, the whole thing breaks ('Uncaught TypeError: Cannot read property 'play' of undefined'): 但是,如果我执行以下操作,整个过程就会中断(“未捕获的TypeError:无法读取未定义的属性” play”):

var audio = {
    STARTSCREEN     = new Audio('sounds/soundtrack-idle-24s.wav');
    GAMEPLAY        = new Audio('sounds/soundtrack-active-24s.wav');
    FX_BREAK        = new Audio('sounds/effect-break.wav');
    FX_BUBBLE       = new Audio('sounds/effect-bubble.wav');
    FX_EXPLOSION    = new Audio('sounds/effect-explosion.wav');
}

And how does my call change? 我的电话又如何变化? Will it be something like: 会是这样吗?

audio.GAMEPLAY.play();

If you want to create an object with audios: 如果要创建带有音频的对象:

var audio = {
  STARTSCREEN : new Audio('sounds/soundtrack-idle-24s.wav'),
  GAMEPLAY    : new Audio('sounds/soundtrack-active-24s.wav'),
  FX_BREAK    : new Audio('sounds/effect-break.wav'),
  FX_BUBBLE   : new Audio('sounds/effect-bubble.wav'),
  FX_EXPLOSION: new Audio('sounds/effect-explosion.wav')
};

Now you can call play() method of each audio like this: 现在,您可以像这样调用每个音频的play()方法:

audio.GAMEPLAY.play();

To mute/unmute all audios iterate through this object: 要使所有音频静音/取消静音,请迭代此对象:

function toggleMute() {
  for (var i in audio) {
    audio[i].muted = !audio[i].muted;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM