JavaScript / HTML5中的音效

本文翻译自:Sound effects in JavaScript / HTML5

I'm using HTML5 to program games; 我正在使用HTML5来编写游戏; the obstacle I've run into now is how to play sound effects. 我现在遇到的障碍是如何播放声音效果。

The specific requirements are few in number: 具体要求很少:

  • Play and mix multiple sounds, 播放和混合多种声音,
  • Play the same sample multiple times, possibly overlapping playbacks, 多次播放相同的样本,可能重叠播放,
  • Interrupt playback of a sample at any point, 在任何点中断播放样本,
  • Preferably play WAV files containing (low quality) raw PCM, but I can convert these, of course. 最好播放包含(低质量)原始PCM的WAV文件,但我当然可以转换它们。

My first approach was to use the HTML5 <audio> element and define all sound effects in my page. 我的第一种方法是使用HTML5 <audio>元素并在我的页面中定义所有声音效果。 Firefox plays the WAV files just peachy, but calling #play multiple times doesn't really play the sample multiple times. Firefox只播放WAV文件,但多次调用#play并不能真正多次播放样本。 From my understanding of the HTML5 spec, the <audio> element also tracks playback state, so that explains why. 根据我对HTML5规范的理解, <audio>元素还可以跟踪播放状态,因此可以解释原因。

My immediate thought was to clone the audio elements, so I created the following tiny JavaScript library to do that for me (depends on jQuery): 我的直接想法是克隆音频元素,所以我创建了以下微小的JavaScript库来为我做(取决于jQuery):

var Snd = {
  init: function() {
    $("audio").each(function() {
      var src = this.getAttribute('src');
      if (src.substring(0, 4) !== "snd/") { return; }
      // Cut out the basename (strip directory and extension)
      var name = src.substring(4, src.length - 4);
      // Create the helper function, which clones the audio object and plays it
      var Constructor = function() {};
      Constructor.prototype = this;
      Snd[name] = function() {
        var clone = new Constructor();
        clone.play();
        // Return the cloned element, so the caller can interrupt the sound effect
        return clone;
      };
    });
  }
};

So now I can do Snd.boom(); 所以现在我可以做Snd.boom(); from the Firebug console and play snd/boom.wav , but I still can't play the same sample multiple times. 从Firebug控制台播放snd/boom.wav ,但我仍然无法多次播放相同的样本。 It seems that the <audio> element is really more of a streaming feature rather than something to play sound effects with. 似乎<audio>元素实际上更像是流媒体功能,而不是播放音效的东西。

Is there a clever way to make this happen that I'm missing, preferably using only HTML5 and JavaScript? 是否有一种聪明的方法可以实现这一点,我很想忘记,最好只使用HTML5和JavaScript?

I should also mention that, my test environment is Firefox 3.5 on Ubuntu 9.10. 我还要提一下,我的测试环境是Ubuntu 9.10上的Firefox 3.5。 The other browsers I've tried - Opera, Midori, Chromium, Epiphany - produced varying results. 我尝试过的其他浏览器--Opera,Midori,Chromium,Epiphany--产生了不同的结果。 Some don't play anything, and some throw exceptions. 有些人不玩任何东西,有些人抛出异常。


#1楼

参考:https://stackoom.com/question/8773/JavaScript-HTML-中的音效


#2楼

WebAudio API by W3C W3C的WebAudio API

As of July 2012, the WebAudio API is now supported in Chrome, and at least partly supported in Firefox, and is slated to be added to IOS as of version 6. 截至2012年7月,Chrome现在支持WebAudio API ,并且至少部分支持Firefox,并且将从版本6开始添加到IOS。

Although it is robust enough to be used programatically for basic tasks, the Audio element was never meant to provide full audio support for games, etc. It was designed to allow a single piece of media to be embedded in a page, similar to an img tag. 虽然它足够强大,可以编程方式用于基本任务,但Audio元素从未打算为游戏等提供完整的音频支持。它旨在允许将单个媒体嵌入到页面中,类似于img标签。 There are a lot of issues with trying to use the Audio tag for games: 尝试将音频标记用于游戏时存在很多问题:

  • Timing slips are common with Audio elements 定时单对于Audio元素很常见
  • You need an Audio element for each instance of a sound 每个声音实例都需要一个Audio元素
  • Load events aren't totally reliable, yet 负载事件尚不完全可靠
  • No common volume controls, no fading, no filters/effects 没有常见的音量控制,没有褪色,没有滤镜/效果

I used this Getting Started With WebAudio article to get started with the WebAudio API. 我使用WebAudio入门文章开始使用WebAudio API。 The FieldRunners WebAudio Case Study is also a good read. FieldRunners WebAudio案例研究也是一本很好的读物。


#3楼

Here's one method for making it possible to play even same sound simultaneously. 这是一种可以同时播放相同声音的方法。 Combine with preloader, and you're all set. 结合预加载器,你就完成了。 This works with Firefox 17.0.1 at least, haven't tested it with anything else yet. 这至少适用于Firefox 17.0.1,尚未测试其他任何东西。

// collection of sounds that are playing
var playing={};
// collection of sounds
var sounds={step:"knock.ogg",throw:"swing.ogg"};

// function that is used to play sounds
function player(x)
{
    var a,b;
    b=new Date();
    a=x+b.getTime();
    playing[a]=new Audio(sounds[x]);
    // with this we prevent playing-object from becoming a memory-monster:
    playing[a].onended=function(){delete playing[a]};
    playing[a].play();
}

Bind this to a keyboard key, and enjoy: 将其绑定到键盘键,然后享受:

player("step");

#4楼

I know this is a total hack but thought I should add this sample open source audio library I put on github awhile ago... 我知道这是一个彻头彻尾的黑客,但我想我应该添加这个样本开源音频库我前一段时间放在github上...

https://github.com/run-time/jThump https://github.com/run-time/jThump

After clicking the link below, type on the home row keys to play a blues riff (also type multiple keys at the same time etc.) 单击下面的链接后,键入主页行键以播放蓝调riff(同时键入多个键等)

Sample using jThump library >> http://davealger.com/apps/jthump/ 使用jThump库的示例>> http://davealger.com/apps/jthump/

It basically works by making invisible <iframe> elements that load a page that plays a sound onReady(). 它基本上是通过制作不可见的<iframe>元素来加载播放声音onReady()的页面。

This is certainly not ideal but you could +1 this solution based on creativity alone (and the fact that it is open source and works in any browser that I've tried it on) I hope this gives someone else searching some ideas at least. 这肯定不是理想的,但你可以单独根据创造力+1这个解决方案(事实上它是开源的,并且可以在我尝试过的任何浏览器中运行)我希望这至少让其他人搜索一些想法。

:) :)


#5楼

I would recommend using SoundJS , a library I've help develop. 我建议使用SoundJS ,一个我帮助开发的库。 It allows you to write a single code base that works everywhere, with SoundJS picking web audio, html audio, or flash audio as appropriate. 它允许您编写一个可在任何地方使用的单个代码库,SoundJS会根据需要选择Web音频,html音频或flash音频。

It will allow you to do all of the thing you want: 它可以让你做你想做的所有事情:

  • Play and mix multiple sounds, 播放和混合多种声音,
  • Play the same sample multiple times, possibly overlapping playbacks 多次播放相同的样本,可能重叠播放
  • Interrupt playback of a sample at any point 在任何时候中断播放样本
  • play WAV files containing (depending on browser support) 播放包含的WAV文件(取决于浏览器支持)

Hope that helps. 希望有所帮助。


#6楼

To play the same sample multiple times, wouldn't it be possible to do something like this: 要多次播放相同的样本,是不是可以这样做:

e.pause(); // Perhaps optional
e.currentTime = 0;
e.play();

( e is the audio element) e是音频元素)

Perhaps I completely misunderstood your problem, do you want the sound effect to play multiple times at the same time? 也许我完全误解了你的问题,你想让声音效果同时播放多次吗? Then this is completely wrong. 那是完全错误的。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个HTML圣诞树动态音效的例子: ```html <!DOCTYPE html> <html> <head> <title>Christmas Tree with Music</title> <style> body { background-color: #000; } .tree { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 200px; height: 200px; background-color: #006400; border-radius: 0 0 50% 50%; overflow: hidden; } .tree:before { content: ""; position: absolute; top: -50%; left: 0; width: 200px; height: 200px; background-color: #006400; border-radius: 50%; } .tree:after { content: ""; position: absolute; top: 50%; left: -50%; width: 200px; height: 200px; background-color: #006400; border-radius: 50%; } .tree .star { position: absolute; top: -25%; left: 50%; transform: translate(-50%, -50%); width: 50px; height: 50px; background-color: #ffd700; border-radius: 50%; } .tree .trunk { position: absolute; top: 50%; left: 50%; transform: translate(-50%, 0); width: 50px; height: 100px; background-color: #8b4513; border-radius: 0 0 10px 10px; } .tree .trunk:before { content: ""; position: absolute; top: 0; left: -25%; width: 50%; height: 50%; background-color: #8b4513; border-radius: 50%; } .tree .trunk:after { content: ""; position: absolute; bottom: 0; left: -25%; width: 50%; height: 50%; background-color: #8b4513; border-radius: 50%; } .tree .lights { position: absolute; top: 25%; left: 50%; transform: translate(-50%, 0); width: 100%; height: 50%; display: flex; flex-wrap: wrap; align-items: center; justify-content: center; } .tree .lights .light { width: 10%; height: 10%; background-color: #fff; border-radius: 50%; animation: blink 1s infinite; } @keyframes blink { 0% { opacity: 1; } 50% { opacity: 0.5; } 100% { opacity: 1; } } </style> </head> <body> <audio id="music" src="music.mp3" autoplay loop></audio> <div class="tree"> <div class="star"></div> <div class="trunk"></div> <div class="lights"> <div class="light"></div> <div class="light"></div> <div class="light"></div> <div class="light"></div> <div class="light"></div> <div class="light"></div> <div class="light"></div> <div class="light"></div> <div class="light"></div> <div class="light"></div> </div> </div> </body> </html> ``` 这个例子,我们使用HTML和CSS创建了一个圣诞树,并使用JavaScript播放了背景音乐。在HTML,我们使用`<audio>`标签来嵌入音频文件,并使用`autoplay`和`loop`属性来自动播放和循环播放音乐。在CSS,我们使用伪元素和`border-radius`属性来创建圣诞树的形状,并使用`overflow`属性来隐藏超出容器的部分。我们还使用`animation`属性来创建闪烁的灯光效果。在JavaScript,我们使用`play()`方法来播放音乐。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值