如何让JavaScript发出哔哔声?

我想让我的网页在用户超过<textarea>的最大字符限制时发出哔哔声。

306358 次浏览

没有跨浏览器的方法来实现这纯javascript。相反,您可以使用一个小的.wav文件,使用嵌入或对象标记播放。

这在JavaScript中是不可能直接实现的。您需要在HTML中嵌入一个简短的WAV文件,然后通过代码播放该文件。

一个例子:

<script>
function PlaySound(soundObj) {
var sound = document.getElementById(soundObj);
sound.Play();
}
</script>


<embed src="success.wav" autostart="false" width="0" height="0" id="sound1"
enablejavascript="true">

然后从JavaScript代码中调用它,如下所示:

PlaySound("sound1");

这应该完全是你想要的-你只需要自己找到/创建哔哔声,这应该是微不足道的。

您需要从某个地方提供声音文件。下面是来自Scriptaculous的声音库的代码:

//Default:
<embed style="height:0" id="sound_#{track}_#{id}" src="#{url}" loop="false" autostart="true" hidden="true"/>


//For Gecko:
if(Prototype.Browser.Gecko && navigator.userAgent.indexOf("Win") > 0){
if(navigator.plugins && $A(navigator.plugins).detect(function(p){ return p.name.indexOf('QuickTime') != -1 }))
Sound.template = new Template('<object id="sound_#{track}_#{id}" width="0" height="0" type="audio/mpeg" data="#{url}"/>');
else if(navigator.plugins && $A(navigator.plugins).detect(function(p){ return p.name.indexOf('Windows Media') != -1 }))
Sound.template = new Template('<object id="sound_#{track}_#{id}" type="application/x-mplayer2" data="#{url}"></object>');
else if(navigator.plugins && $A(navigator.plugins).detect(function(p){ return p.name.indexOf('RealPlayer') != -1 }))
Sound.template = new Template('<embed type="audio/x-pn-realaudio-plugin" style="height:0" id="sound_#{track}_#{id}" src="#{url}" loop="false" autostart="true" hidden="true"/>');
else
Sound.play = function(){};
}

使用CSS,如果你给标签添加以下样式,你就可以做到这一点,但你需要一个wav文件:

<style type="text/css">
.beep {cue: url("beep.wav") }
</style>


var body=document.getElementByTagName("body");
body.className=body.className + " " + "beep";

正如我们在这个答案中读到的,如果你对那条路由开放,HTML5将为你解决这个问题。HTML5音频在所有现代浏览器中支持。

下面是示例的副本:

var snd = new Audio("file.wav"); // buffers automatically when created
snd.play();

我用新的音频API写了一个函数来发出哔哔声。

var beep = (function () {
var ctxClass = window.audioContext ||window.AudioContext || window.AudioContext || window.webkitAudioContext
var ctx = new ctxClass();
return function (duration, type, finishedCallback) {


duration = +duration;


// Only 0-4 are valid types.
type = (type % 5) || 0;


if (typeof finishedCallback != "function") {
finishedCallback = function () {};
}


var osc = ctx.createOscillator();


osc.type = type;
//osc.type = "sine";


osc.connect(ctx.destination);
if (osc.noteOn) osc.noteOn(0); // old browsers
if (osc.start) osc.start(); // new browsers


setTimeout(function () {
if (osc.noteOff) osc.noteOff(0); // old browsers
if (osc.stop) osc.stop(); // new browsers
finishedCallback();
}, duration);


};
})();

jsFiddle

function beep(wavFile){
wavFile = wavFile || "beep.wav"
if (navigator.appName == 'Microsoft Internet Explorer'){
var e = document.createElement('BGSOUND');
e.src = wavFile;
e.loop =1;
document.body.appendChild(e);
document.body.removeChild(e);
}else{
var e = document.createElement('AUDIO');
var src1 = document.createElement('SOURCE');
src1.type= 'audio/wav';
src1.src= wavFile;
e.appendChild(src1);
e.play();
}
}

适用于Chrome,IE,Mozilla使用Win7操作系统。 需要服务器上的beep.wav文件

以下是我如何使用HTML5让它发出哔哔声: 首先我复制并将windows wav文件转换为mp3,然后我使用这段代码:

var _beep = window.Audio("Content/Custom/Beep.mp3")


function playBeep() { _beep.play()};

全局声明声音文件并在需要时引用它会更快。

解决方案

你现在可以使用base64文件在导入为数据URI时产生声音。解决方案几乎与前面的相同,除了您不需要导入外部音频文件。

function beep() {
var snd = new Audio("data:audio/wav;base64,//uQRAAAAWMSLwUIYAAsYkXgoQwAEaYLWfkWgAI0wWs/ItAAAGDgYtAgAyN+QWaAAihwMWm4G8QQRDiMcCBcH3Cc+CDv/7xA4Tvh9Rz/y8QADBwMWgQAZG/ILNAARQ4GLTcDeIIIhxGOBAuD7hOfBB3/94gcJ3w+o5/5eIAIAAAVwWgQAVQ2ORaIQwEMAJiDg95G4nQL7mQVWI6GwRcfsZAcsKkJvxgxE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////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////VEFHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAU291bmRib3kuZGUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMjAwNGh0dHA6Ly93d3cuc291bmRib3ku
ZGUAAAAAAAAAACU=");
snd.play();
}
beep();

兼容性

现在几乎所有浏览器都支持数据URI。关于http://caniuse.com/datauri的更多信息

演示

http://jsfiddle.net/7EAgz/

转换工具

这里是你可以将mp3或wav文件转换为数据URI格式的地方:

https://dopiaza.org/tools/datauri/index.php

function Sound(url, vol, autoplay, loop)
{
var that = this;


that.url = (url === undefined) ? "" : url;
that.vol = (vol === undefined) ? 1.0 : vol;
that.autoplay = (autoplay === undefined) ? true : autoplay;
that.loop = (loop === undefined) ? false : loop;
that.sample = null;


if(that.url !== "")
{
that.sync = function(){
that.sample.volume = that.vol;
that.sample.loop = that.loop;
that.sample.autoplay = that.autoplay;
setTimeout(function(){ that.sync(); }, 60);
};


that.sample = document.createElement("audio");
that.sample.src = that.url;
that.sync();


that.play = function(){
if(that.sample)
{
that.sample.play();
}
};


that.pause = function(){
if(that.sample)
{
that.sample.pause();
}
};
}
}


var test = new Sound("http://mad-hatter.fr/Assets/projects/FreedomWings/Assets/musiques/freedomwings.mp3");
test.play();

http://jsfiddle.net/sv9j638j/

注意:把这段代码放在你的javascript中,在你想要哔哔声发生的地方。 并且记住指定存储哔哔声的目录或文件夹(源)
<script>
//Appending HTML5 Audio Tag in HTML Body
$('<audio id="chatAudio"><source src="sound/notify.ogg" type="audio/ogg"><source src="sound/notify.mp3" type="audio/mpeg"><source src="sound/notify.wav" type="audio/wav"></audio>').appendTo('body');


$('#chatAudio')[0].play();
</script>

参考:http://www.9lessons.info/2013/04/play-notification-sound-using-jquery.html

我在我正在开发的社交媒体中实现了这一点,它的工作发现,聊天时像facebook一样的通知,通知你有一个新的聊天消息

/*if you want to beep without using a wave file*/
var context = new AudioContext();
var oscillator = context.createOscillator();
oscillator.type = "sine";
oscillator.frequency.value = 800;
oscillator.connect(context.destination);
oscillator.start();
// Beep for 500 milliseconds
setTimeout(function () {
oscillator.stop();
}, 100);
            

上面的答案在当时是正确的,但现在是错误的;你可以用纯javascript实现。但是使用javascript的一个答案不再有效,而其他答案非常有限或不使用纯javascript。

我做了我自己的解决方案,工作得很好,让你控制音量,频率和波型。

//if you have another AudioContext class use that one, as some browsers have a limit
var audioCtx = new (window.AudioContext || window.webkitAudioContext || window.audioContext);


//All arguments are optional:


//duration of the tone in milliseconds. Default is 500
//frequency of the tone in hertz. default is 440
//volume of the tone. Default is 1, off is 0.
//type of tone. Possible values are sine, square, sawtooth, triangle, and custom. Default is sine.
//callback to use on end of tone
function beep(duration, frequency, volume, type, callback) {
var oscillator = audioCtx.createOscillator();
var gainNode = audioCtx.createGain();
    

oscillator.connect(gainNode);
gainNode.connect(audioCtx.destination);
    

if (volume){gainNode.gain.value = volume;}
if (frequency){oscillator.frequency.value = frequency;}
if (type){oscillator.type = type;}
if (callback){oscillator.onended = callback;}
    

oscillator.start(audioCtx.currentTime);
oscillator.stop(audioCtx.currentTime + ((duration || 500) / 1000));
};

有人建议我编辑一下,说明它只适用于某些浏览器。然而,据我所知,在所有现代浏览器上Audiocontext似乎是支持的。它在IE上不受支持,但微软已经停产了。如果您在特定的浏览器上有任何问题,请报告。

这将使你能够播放声音多次,与投票最多的答案形成对比:

var playSound = (function beep() {
var snd = new Audio("data:audio/wav;base64,//uQRAAAAWMSLwUIYAAsYkXgoQwAEaYLWfkWgAI0wWs/ItAAAGDgYtAgAyN+QWaAAihwMWm4G8QQRDiMcCBcH3Cc+CDv/7xA4Tvh9Rz/y8QADBwMWgQAZG/ILNAARQ4GLTcDeIIIhxGOBAuD7hOfBB3/94gcJ3w+o5/5eI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JSFRYWaLC4qZBYWFRGZdwqKiwkNBVmoWFSJkWFxX4FFRQWR+LsS4W/rFRb/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////VEFHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAU291bmRib3kuZGUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMjAwNGh0dHA6Ly93d3cuc291bmRib3ku
ZGUAAAAAAAAAACU=");
return function() {
snd.play();
}
})();


playSound(); // Play first time
playSound(); // Play second time

使用Houshalter的建议,我做了这个简单的音调合成器演示。

截图

这是一个截图。在下面的答案中尝试现场演示(单击运行代码段)。

在这个答案中进一步提供的现场演示的截图

演示代码

audioCtx = new(window.AudioContext || window.webkitAudioContext)();


show();


function show() {
frequency = document.getElementById("fIn").value;
document.getElementById("fOut").innerHTML = frequency + ' Hz';


switch (document.getElementById("tIn").value * 1) {
case 0: type = 'sine'; break;
case 1: type = 'square'; break;
case 2: type = 'sawtooth'; break;
case 3: type = 'triangle'; break;
}
document.getElementById("tOut").innerHTML = type;


volume = document.getElementById("vIn").value / 100;
document.getElementById("vOut").innerHTML = volume;


duration = document.getElementById("dIn").value;
document.getElementById("dOut").innerHTML = duration + ' ms';
}


function beep() {
var oscillator = audioCtx.createOscillator();
var gainNode = audioCtx.createGain();


oscillator.connect(gainNode);
gainNode.connect(audioCtx.destination);


gainNode.gain.value = volume;
oscillator.frequency.value = frequency;
oscillator.type = type;


oscillator.start();


setTimeout(
function() {
oscillator.stop();
},
duration
);
};
frequency
<input type="range" id="fIn" min="40" max="6000" oninput="show()" />
<span id="fOut"></span><br>
type
<input type="range" id="tIn" min="0" max="3" oninput="show()" />
<span id="tOut"></span><br>
volume
<input type="range" id="vIn" min="0" max="100" oninput="show()" />
<span id="vOut"></span><br>
duration
<input type="range" id="dIn" min="1" max="5000" oninput="show()" />
<span id="dOut"></span>
<br>
<button onclick='beep();'>Play</button>

你可以在这里克隆和调整代码: 音调合成器的演示JS Bin < / p >

玩得开心!

兼容的浏览器:

  • Chrome手机&桌面
  • Firefox移动&桌面
  • Opera手机,mini &桌面
  • Android浏览器
  • 微软Edge浏览器
  • iPhone或iPad上的Safari浏览器

不兼容的

  • Internet Explorer 11版(但在Edge浏览器上可以运行)

现在用JavaScript AudioContext API就很简单了。它完全支持由主要的桌面和移动网络浏览器…

let context = null;


const beep = (freq = 520, duration = 200, vol = 100) => {
const oscillator = context.createOscillator();
const gain = context.createGain();
oscillator.connect(gain);
oscillator.frequency.value = freq;
oscillator.type = "square";
gain.connect(context.destination);
gain.gain.value = vol * 0.01;
oscillator.start(context.currentTime);
oscillator.stop(context.currentTime + duration * 0.001);
}


document.querySelector('button').addEventListener('click', function () {
context = new AudioContext();
beep();
});

我写了一个小应用程序,可以播放马里奥游戏中的音乐,不需要任何音频文件,只有运行时。在我看来,这很有趣,你可以看到源代码并听它。

enter image description here

<html>
<head>
<script src='https://surikov.github.io/webaudiofont/npm/dist/WebAudioFontPlayer.js'></script>
<script src='https://surikov.github.io/webaudiofontdata/sound/0000_JCLive_sf2_file.js'></script>
<script>
var selectedPreset=_tone_0000_JCLive_sf2_file;
var AudioContextFunc = window.AudioContext || window.webkitAudioContext;
var audioContext = new AudioContextFunc();
var player=new WebAudioFontPlayer();
player.loader.decodeAfterLoading(audioContext, '_tone_0000_JCLive_sf2_file');
</script>
</head>
<body>
<p><a href="#" onmousedown="player.queueWaveTable(audioContext, audioContext.destination, selectedPreset, 0, 55, 3.5);">Play a note</a></p>
<hr/>
<p><a href="https://github.com/surikov/webaudiofont">source</a></p>
</body>

< p >听 https://jsbin.com/lamidog/1/edit?html,output < / p >

该代码支持多个哔哔声的排序,以及频率的逐渐变化('ramp'标志)。下面给出了两个例子。

<script>
var audioContext = null;
var oscillatorNode = null;
var stopTime = 0;


function beep (frequency, durationSec, ramp=false)
{
if (oscillatorNode == null) {
audioContext = new (window.AudioContext || window.webkitAudioContext) ();
stopTime = audioContext.currentTime;


oscillatorNode = audioContext.createOscillator();
oscillatorNode.type = "sine";
oscillatorNode.connect (audioContext.destination);
if (ramp) {
oscillatorNode.frequency.setValueAtTime (frequency, stopTime);
}
oscillatorNode.start ();
oscillatorNode.onended = function() {
oscillatorNode = null;
audioContext = null;
}
}


if (ramp) {
oscillatorNode.frequency.linearRampToValueAtTime (frequency, stopTime); // value in hertz
} else {
oscillatorNode.frequency.setValueAtTime (frequency, stopTime);  // value in hertz
}


stopTime += durationSec;
oscillatorNode.stop (stopTime);
}
function test1()
{
beep (250, 0.5);
beep (1000, 0.2);
beep (550, 0.5);
}
    

function test2()
{
beep (50, 2, true);
beep (5000, 2, true);
beep (50, 0, true);
}
</script>
    

<button onclick='test1()'>Beep!</button>
<button onclick='test2()'>Beep(ramped)!</button>