How can I do that, so whenever a user clicks a link we play a sound? Using javascript and jquery here.
Use this plugin: https://github.com/admsev/jquery-play-sound
$.playSound('http://example.org/sound.mp3');
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/
Found something like that:
//javascript:
function playSound( url ){
document.getElementById("sound").innerHTML="<embed src='"+url+"' hidden=true autostart=true loop=false>";
}
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.
JavaScript Sound Manager:
http://www.schillmania.com/projects/soundmanager2/
$('a').click(function(){
$('embed').remove();
$('body').append('<embed src="/path/to/your/sound.wav" autostart="true" hidden="true" loop="false">');
});
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);
};
New emerger... seems to be compatible with IE, Gecko browsers and iPhone so far...
http://www.jplayer.org/
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')">
[Play]
<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>
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?
Related
Let's say I have an Html file that look like this:
<div name="piano">
<div name="a.wav"></div>
<div name="b.wav"></div>
<div name="c.wav"></div>
</div>
How would I play all the .wav files mentioned in the piano div simultaneously (when a button is pressed)?
Edit: For clarification, eventually the user will be able to select what notes are played and at what time. This is just a simplified example.
The normal audio element (<audio> or new Audio()) is not appropriate for this use case, as it leaves no method for precise timing. You need to use the Web Audio API.
Use a BufferSourceNode for each note you want to play:
const buffer = await audioContext.decodeAudioData(... audio data ...);
const bufferSourceNode = audioContext.createBufferSource();
bufferSourceNode.buffer = buffer;
bufferSourceNode.connect(audioContext.destination);
bufferSourceNode.start(/* you can use a start time here */);
See also:
JSFiddle I made for a mini sampler: https://jsfiddle.net/bradisbell/sc9jpxvn/1/
AudioBufferSourceNode documentation: https://developer.mozilla.org/en-US/docs/Web/API/AudioBufferSourceNode
If you would like to play it randomly use:
<audio src="..." id="song1"></audio>
<audio src="..." id="song2"></audio>
<audio src="..." id="song2"></audio>
for(var i = 1; i <= 3; i++){
document.querySelector("#song" + i)[0].play();
}
With html5, you should use the <audio> tag. It have javascript hooks for 'play', 'pause', etc.
You can add the following html;
<button onclick="playA();playB();playC()">Play Audio</button>
with corresponding javascript
var audioA = new Audio('a.wav');
var audioB = new Audio('b.wav');
var audioC = new Audio('c.wav');
function playA() {
audioA.play();
}
function playB() {
audioB.play();
}
function playC() {
audioC.play();
}
Is there any way to play a video in html5, stop and execute javascript at known points within the video?
Yes, try this. You have to use the currentTime property. Start with that and start your javascript functions from there. Is that what you're looking for?
var vid = document.getElementById("video");
//Add a timeupdate listener
video.addEventListener("timeupdate", function(){
//Check for video properties from within the function
if (this.currentTime == 5)
this.pause();
//cal javascript
}
}
Looking at the accepted answer over here it looks like it is possible.
To pause the video you just do this:
var mediaElement = document.getElementById("video"); // create a reference to your HTML5 video
mediaElement.pause(); // pauses the video
If you want to play the video, do this:
mediaElement.play(); // plays the video
To get the current time in the video, do this:
mediaElement.currentTime; // gets the current time
Here's an example linking them all up:
var mediaElement = document.getElementById("video");
if(mediaElement.currentTime == 35){
mediaElement.pause();
// do whatever else you would like
mediaElement.play();
}
The MDL documentation is here, there are plenty of other properties you might find helpful.
Hope this helps!
Yes, by doing like this you can.
Note that you have to look for a time using bigger than > bigger than (as the chance to match an exact millisecond is almost zero), and have a variable in one way or the other to know which ones is done.
window.addEventListener('load', function() {
var cur = document.querySelector('#cur'),
vid = document.querySelector('#vid')
})
var appDone = {"done7":false,"done4":false}
vid.addEventListener('timeupdate', function(e) {
if (e.target.currentTime > 7 && !appDone.done7) {
appDone.done7 = true;
e.target.pause();
//do something
cur.textContent += ", " + "done7 once";
e.target.play();
}
if (e.target.currentTime > 4 && !appDone.done4) {
appDone.done4 = true;
e.target.pause();
//do something
cur.textContent += ", " + "done4 once";
e.target.play();
}
})
<video id="vid" width="320" height="176" controls>
<source src="http://www.w3schools.com/tags/mov_bbb.mp4" type="video/mp4">
<source src="http://www.w3schools.com/tags/mov_bbb.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video>
<p id="cur"></p>
I'm using the following code to trigger fullscreen when a user clicks on the play button on a <video> element:
var video = $("#video");
video.on('play', function(e){
if (video.requestFullscreen) {
video.requestFullscreen();
} else if (video.mozRequestFullScreen) {
video.mozRequestFullScreen();
} else if (video.webkitRequestFullscreen) {
video.webkitRequestFullscreen();
}
});
But nothing happens when I click the play button.
Any idea's why?
EDIT: Here's my HTML code:
<video width="458" height="258" controls id='video' >
<source src='<?= bloginfo('template_directory'); ?>/inc/pilot.mp4' type="video/mp4">
<source src='<?= bloginfo('template_directory'); ?>/inc/pilot.ogv' type="video/ogg">
<source src='<?= bloginfo('template_directory'); ?>/inc/pilot.webm' type="video/webm">
</video>
There are a couple things going on here:
First, in your code, video is a jQuery object, not the actual video element. For a jQuery object, you can reference it like this:
var actualVideo = video[0]; // (assuming '#video' actually exists)
Second, for security and good user experience, browsers will only let you trigger full screen inside a user-triggered event, like a 'click'. You can't have every web page going to full screen as soon as you visit it, and you can cause a video to start playing automatically, which would violate that rule.
So an alternative solution would be to request fullscreen in a click event, like this:
var video = $("#video");
video.on('click', function(e){
var vid = video[0];
vid.play();
if (vid.requestFullscreen) {
vid.requestFullscreen();
} else if (vid.mozRequestFullScreen) {
vid.mozRequestFullScreen();
} else if (vid.webkitRequestFullscreen) {
vid.webkitRequestFullscreen();
}
});
Ideally, you'd probably want to build out a more complete player ui, but this should give you the general idea.
A less verbose way to toggle full screen combining answers from this and other questions.
This should handle all browser flavours: chromium- and webkit-based, firefox, opera, and MS-based browsers.
var p = document.querySelector('#videoplayer');
if (!window.isFs) {
window.isFs = true;
var fn_enter = p.requestFullscreen || p.webkitRequestFullscreen || p.mozRequestFullScreen || p.oRequestFullscreen || p.msRequestFullscreen;
fn_enter.call(p);
} else {
window.isFs = false;
var fn_exit = p.exitFullScreen || p.webkitExitFullScreen || p.mozExitFullScreen || p.oExitFullScreen || p.msExitFullScreen;
fn_exit.call(p);
}
p represents the DOM object of the video element, and window.isFs is just a random variable for storing the current fullscreen state.
If your player is a jQuery object then you can get the underlying DOM-element with var p = player.get(0).
I want to add a sound clip to a button on a game I am creating. Currently It doesn't do anything and I don't know why.
At the moment In the script I have...
var audio = $(".mysoundclip")[0];
$(".minibutton").onclick(function() {
audio.play();
});
In the HTML I have...
<audio id="mysoundclip" preload="auto">
<source src="http://www.wav-sounds.com/cartoon/bugsbunny1.wav"></source>
</audio>
Then I have CSS for .minibutton.
Any ideas why it won't work?
Your jQuery had some simple errors in it.
HTML
<audio id="mysoundclip" preload="auto">
<source src="http://www.wav-sounds.com/cartoon/bugsbunny1.wav"></source>
</audio>
<button type="button">play</button>
jQuery
var audio = $("#mysoundclip")[0];
$("button").click(function() {
audio.play();
});
Fiddle: http://jsfiddle.net/iambriansreed/VavyK/
Maybe I'm a too suspicous.. but
http://www.sound-effect.com/sounds1/animal/Saf/Tiger1.wav "The requested URL was not found on this server"
If that's just a typo, you should also try to figure out which audio types a browser is capable to play:
myApp.htmlAudio = (function _htmlAudioCheck() {
var elem = document.createElement('audio'),
bool = false;
try {
if( !!elem.canPlayType ) {
bool = new Boolean(bool);
bool.ogg = elem.canPlayType('audio/ogg; codecs="vorbis"');
bool.mp3 = elem.canPlayType('audio/mpeg;');
bool.wav = elem.canPlayType('audio/wav; codecs="1"');
bool.m4a = ( elem.canPlayType('audio/x-m4a;') || elem.canPlayType('audio/aac;'));
}
} catch(e) { }
return bool;
}());
Now we can check like
if( myApp.htmlAudio && myApp.htmlAudio.wav ) {
}
if the browser is able to playback .wav files for instance.
However, I never saw a nested source element for audio elements. That should be named track if anything. But you don't really need that here, you can just have a src attribute on the audio element itself. Example: http://jsfiddle.net/5GUPg/1/
I included a videos with html5, and I have a menu that change the video.
The menu runs well in Firefox, Opera and Chrome but not in Safari.
I have this html code:
<div id="tele">
<video id="v" width="254" height="204">
<source id="ogg" src="/media/joies.ogv" type="video/ogg" />
<source id="mp4" src="/media/joies.mp4" type="video/mp4" />
<source id="webm" src="/media/joies.webm" type="video/webm" />
<object id="flash" type="application/x-shockwave-flash"
data="player.swf?file=joies.mp4">
<param id="flash2" name="movie" value="player.swf?file=joies.mp4" />
</object> </video>
</div>
<li><a href="#" class="activo"
onClick="changeVideo('/media/joies.ogv','/media/joies.mp4','/media/joies.webm','player.swf?file=joies.mp4','player.swf?file=joies.mp4')">1</a>
And this Javascript:
function changeVideo(v,x,w,y,z) {
document.getElementById("ogg").src=v;
document.getElementById("mp4").src=x;
document.getElementById("flash").data=y;
document.getElementById("flash2").value=z;
document.getElementById("webm").src=w;
var video = document.getElementById('v');
video.load();
video.play();
}
To visit the web: http://81.35.152.41:8888/index.php/ca/static/zapping#
Why the menu to change video not runs in Safari?
Thanks
Regards
put the mp4-node on top of the others, then it might work.
if that does not work, remove the source-nodes completely and use the src attribute of the video-node. Then add a check for compatible codecs to changeVideo() --> video.canPlayType("video/mp4") (for each type, best in a loop)
in IE9 that fixed problems for me. tested Safari later so dunno if it has the same problem.
I use this function for source-testing:
var VIDEO = document.getElementById("myVideo");
function listSource(source,sources) {
var type,
ext = source.split('.').pop();
switch(ext) {
case "mp4":
case "m4v":
ext = "mp4";
type = "video/mp4";
break;
case "webm":
type = "video/webm";
break;
case "ogv":
type = "video/ogg";
break;
default:
console.log('invalid file extension: '+source);
return sources;
}
if( !VIDEO.canPlayType(type) ) {
return sources; // only add video to list if the current browser can actually play it
}
sources.push({ src: source, type: type });
return sources;
}
var sources_ok = [];
var sources = ["http://domain.com/test.mp4", "http://domain.com/test.webm", "http://domain.com/test.ogv"]; // example
for(var i=0,maxi=sources.length;i<maxi;i++) {
sources_ok = listSource(sources[i],sources_ok);
}
If you change a video's source after it has already loaded, safari will not load the video. You must Clone the video, delete the original and append the cloned container in its place.