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/
Related
var song1 = $('#sound-1');
var song2 = $('#sound-2');
var audioArray = [song1, song2];
var i=0;
var lastPlayedFile = null;
$(".click").click(function(){
if(lastPlayedFile !== null) {
lastPlayedFile[0].currentTime = 0;
lastPlayedFile.trigger('pause');
}
if (i< audioArray.length){
lastPlayedFile = audioArray[i];
audioArray[i].trigger('play');
i++;
} else if (i>=audioArray.length){
i = 0;
lastPlayedFile = audioArray[0];
audioArray[i].trigger('play');
};
});
This code is not working for me and I am using firefox web browser. Is there any issue in this code?
Please make sure you are correctly using the <audio> tag like shown here. The browser will pick up the first recognized source:
<audio controls>
// browser tries to fetch horse.ogg first
<source src="horse.ogg" type="audio/ogg">
// browser tries to fetch horse.mp3 if the above couldn't be recognized
<source src="horse.mp3" type="audio/mpeg">
// if none files are valid the browser falls back with a message
Your browser does not support the audio element.
</audio>
Make sure also that your files you are trying to access do actually exist. I have tried finding them but I got a 404 response.
Also this line of code won't do anything:
lastPlayedFile[0].currentTime = 0;
make sure you have a currentTime property set on each of the audioArray elements (song1 and song2)
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).
Im using java script for a simple if else statement and was trying to add some audio to it. Play one song when its right, and another if its bad. Here is what I have minus the actual if statements. I commented out the audio portion because that broke my code and couldn't get it working.
if (x is true)
{
document.write("Good job!<br />");
/*<audio controls = "controls" autoplay = "autoplay" loop ="loop" >
<source src = "congrats.ogg" type = "audio/ogg" />
<source src = "congrats.mp3" type = "audio/mpeg" />
<source src = "congrats.wav" type = "audio/wav" />
Your browser does not support the audio element
</audio>*/
}
else
{
document.write("Boo!<br />");
}
Any help is appreciated!
Update for clarification: I was trying to say that if my "if statement" executes, play song1 and if my "else statement" executes, play song2.
Update, working!: Did some more research and was able to find the following snippet of code that works for me.
http://www.position-absolute.com/articles/introduction-to-the-html5-audio-tag-javascript-manipulation/
With JavaScript, you can do something like this:
var supports = function(mime) { return (new Audio()).canPlayType('audio/' + mime); };
var sound;
if (supports('ogg; codecs=vorbis')) {
sound = new Audio('congrats.ogg');
} else if (supports('mpeg')) {
sound = new Audio('congrats.mp3');
} else if (supports('wav')) {
sound = new Audio('congrats.wav');
} else {
alert('Your browser is horrible');
}
if (typeof sound !== 'undefined') {
sound.play();
}
Do you really have if (x is true)?
That should be just if (x)
I have the following code:
function playSound(source) {
document.getElementById("sound_span").innerHTML =
"<embed src='" + source + "' hidden=true autostart=true loop=false>";
}
<span id="sound_span"></span>
<button onclick="playSound('file.mp3');"></button>
Once you click play, the MP3 gets downloaded, than it starts to play. However, it can take a while if it has like 1 MB. What I need is a preloaded (just like you can do with the images). So when the page loads, the mp3 will be streamed and if, for instance, 10 seconds later, the user pressed the 'play' button, he won't have to wait until the mp3 gets downloaded first, as it is already streamed.
Any ideas? Thanks in advance for any tip!
You can preload using <audio /> for newer browsers. Set autoplay = false. For older browsers that don't support <audio />, you can use <bgsound />. To preload a sound, set the volume to -10000.
function preloadSound(src) {
var sound = document.createElement("audio");
if ("src" in sound) {
sound.autoPlay = false;
}
else {
sound = document.createElement("bgsound");
sound.volume = -10000;
}
sound.src = src;
document.body.appendChild(sound);
return sound;
}
That will get the sound in your browser's cache. Then to play it, you can keep doing what you are doing with <embed />. Or if you want to take advantage of HTML5 features, you can call .play() on the returned <audio /> element. You could even add a play method to the <bgsound />:
function loadSound (src) {
var sound = document.createElement("audio");
if ("src" in sound) {
sound.autoPlay = false;
}
else {
sound = document.createElement("bgsound");
sound.volume = -10000;
sound.play = function () {
this.src = src;
this.volume = 0;
}
}
sound.src = src;
document.body.appendChild(sound);
return sound;
}
Then use it like this:
var sound = loadSound("/mySound.ogg"); // preload
sound.play();
The only caveat is FireFox doesn't support mp3. You'll have to convert your files to ogg.
Working demo: http://jsfiddle.net/PMj89/1/
You can use the HTML5 <audio> element's preload attribute, and fall back on <embed>.