89

How can I do that, so whenever a user clicks a link we play a sound? Using javascript and jquery here.

Ali
  • 261,656
  • 265
  • 575
  • 769
  • 2
    I've wrote a jQ plugin for audio control http://soundplay.nikolavukovic.net63.net, it supports what you asking and more, docs are bundled with JavaScript code, check it out. – public override Nov 13 '13 at 11:55
  • You can ( for example ) populate playlist(s) with a bunch of page sound effects and `.load()`, `.play()` them in key moments using the api. – public override Nov 13 '13 at 12:04
  • 2
    For the love of all things holy, include a mute option. Links with sounds is one of the quickest ways to ensure a user never comes back to your site. – Wobbles Oct 16 '15 at 13:18

10 Answers10

48

Use this plugin: https://github.com/admsev/jquery-play-sound

$.playSound('http://example.org/sound.mp3');
Pang
  • 9,564
  • 146
  • 81
  • 122
  • Is there a way to make it so it pulls the url of the actual link? – hakarune Nov 12 '13 at 14:36
  • @hakarune: Yes, just remove the ".mp3" ending from the [source](https://raw.githubusercontent.com/admsev/jquery-play-sound/master/jquery.playSound.js). – Avatar Jun 05 '14 at 18:18
  • [This](http://stackoverflow.com/a/38571639/2218697) plays sounds if **browser is inactive or minimized** by the user. Hope helps someone. – Shaiju T Jul 25 '16 at 15:29
26

Put an <audio> element on your page.
Get your audio element and call the play() method:

document.getElementById('yourAudioTag').play();

Check out this example: http://www.storiesinflight.com/html5/audio.html

This site uncovers some of the other cool things you can do such as load(), pause(), and a few other properties of the audio element.

When exactly you want to play this audio element is up to you. Read the text of the button and compare it to "no" if you like.

Alternatively

http://www.schillmania.com/projects/soundmanager2/

SoundManager 2 provides a easy to use API that allows sound to be played in any modern browser, including IE 6+. If the browser doesn't support HTML5, then it gets help from flash. If you want stricly HTML5 and no flash, there's a setting for that, preferFlash=false

It supports 100% Flash-free audio on iPad, iPhone (iOS4) and other HTML5-enabled devices + browsers

Use is as simple as:

<script src="soundmanager2.js"></script>
<script>
// where to find flash SWFs, if needed...
soundManager.url = '/path/to/swf-files/';

soundManager.onready(function() {
    soundManager.createSound({
        id: 'mySound',
        url: '/path/to/an.mp3'
    });

    // ...and play it
    soundManager.play('mySound');
});

Here's a demo of it in action: http://www.schillmania.com/projects/soundmanager2/demo/christmas-lights/

Joris Van Regemortel
  • 935
  • 1
  • 10
  • 34
21

Found something like that:

//javascript:
function playSound( url ){   
  document.getElementById("sound").innerHTML="<embed src='"+url+"' hidden=true autostart=true loop=false>";
} 
Xn0vv3r
  • 17,766
  • 13
  • 58
  • 65
13

Using the html5 audio tag and jquery:

// appending HTML5 Audio Tag in HTML Body
$('<audio id="chatAudio">
    <source src="notify.ogg" type="audio/ogg">
    <source src="notify.mp3" type="audio/mpeg">
</audio>').appendTo('body');

// play sound
$('#chatAudio')[0].play();

Code from here.

In my implementation I added the audio embed directly into the HTML without jquery append.

Avatar
  • 14,622
  • 9
  • 119
  • 198
  • 2
    Just for reference, I am playing sound on success handler from ajax function (which runs on page load) , and get this error: `Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first`, Chrome `Version 70.0.3538.102 (Official Build) (64-bit)`...seems to be solution here: https://stackoverflow.com/a/52821721 – user1063287 Nov 22 '18 at 15:19
9

JavaScript Sound Manager:

http://www.schillmania.com/projects/soundmanager2/

epascarello
  • 204,599
  • 20
  • 195
  • 236
7
$('a').click(function(){
    $('embed').remove();
    $('body').append('<embed src="/path/to/your/sound.wav" autostart="true" hidden="true" loop="false">');
});
Andrew Philpott
  • 939
  • 1
  • 10
  • 11
3

I wrote a small function that can do it, with the Web Audio API...

var beep = function(duration, type, finishedCallback) {

    if (!(window.audioContext || window.webkitAudioContext)) {
        throw Error("Your browser does not support Audio Context.");
    }

    duration = +duration;

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

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

    var ctx = new (window.audioContext || window.webkitAudioContext);
    var osc = ctx.createOscillator();

    osc.type = type;

    osc.connect(ctx.destination);
    osc.noteOn(0);

    setTimeout(function() {
        osc.noteOff(0);
        finishedCallback();
    }, duration);

};
alex
  • 479,566
  • 201
  • 878
  • 984
2

New emerger... seems to be compatible with IE, Gecko browsers and iPhone so far...

http://www.jplayer.org/

degenerate
  • 1,224
  • 1
  • 14
  • 35
2

Following code might help you to play sound in a web page using javascript only. You can see further details at http://sourcecodemania.com/playing-sound-javascript-flash-player/

<script>
function getPlayer(pid) {
    var obj = document.getElementById(pid);
    if (obj.doPlay) return obj;
    for(i=0; i<obj.childNodes.length; i++) {
        var child = obj.childNodes[i];
        if (child.tagName == "EMBED") return child;
    }
}
function doPlay(fname) {
    var player=getPlayer("audio1");
    player.play(fname);
}
function doStop() {
    var player=getPlayer("audio1");
    player.doStop();
}
</script>

<form>
<input type="button" value="Play Sound" onClick="doPlay('texi.wav')">
<a href="#" onClick="doPlay('texi.wav')">[Play]</a>
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
    width="40"
    height="40"
    id="audio1"
    align="middle">
    <embed src="wavplayer.swf?h=20&w=20"
        bgcolor="#ffffff"
        width="40"
        height="40"
        allowScriptAccess="always"
        type="application/x-shockwave-flash"
        pluginspage="http://www.macromedia.com/go/getflashplayer"
    />
</object>

<input type="button" value="Stop Sound" onClick="doStop()">
</form>
falakniazi
  • 133
  • 1
  • 4
Falak
  • 451
  • 1
  • 4
  • 11
0

First things first, i'd not like that as a user.

The best way to do is probably using a small flash applet that plays your sound in the background.

Also answered here: Cross-platform, cross-browser way to play sound from Javascript?

Community
  • 1
  • 1
Javache
  • 3,398
  • 3
  • 21
  • 25
  • 3
    What's so bad about it if the user knows a sound would be played? – lc. Jan 16 '09 at 10:48
  • 3
    It is useful, what about if a user need an beep alert, when new orders arrive? perhaps users are not with eyes on screen the whole time, perhaps I need a pee and turn on the BEEP, then someone else can answer the order.. just few examples.. – devasia2112 Apr 28 '12 at 03:37