function EvalSound(soundobj) {
var thissound=document.getElementById(soundobj);
thissound.currentTime = 0;
thissound.Play();
}
function StopSound(soundobj) {
var thissound=document.getElementById(soundobj);
thissound.Stop();
}
This is my code to play a audio file,
onmouseover="EvalSound('sound1')" onmouseout="StopSound('sound1')"
It is currently working on hover, however when i go back to the image that it plays under it doesnt go back to the beginning, it continues playing
The <embed> tag is the old way to embed multimedia. You really ought to be using the new HTML5 <audio> or <video> tags as they are the preferred and standardized way to embed multimedia objects. You can use the HTMLMediaElement interface to play, pause, and seek through the media (and lots more).
Here is a simple example that plays an audio file on mouseover and stops it on mouseout.
HTML:
<p onmouseover="PlaySound('mySound')"
onmouseout="StopSound('mySound')">Hover Over Me To Play</p>
<audio id='mySound' src='http://upload.wikimedia.org/wikipedia/commons/6/6f/Cello_Live_Performance_John_Michel_Tchaikovsky_Violin_Concerto_3rd_MVT_applaused_cut.ogg'/>
Javascript:
function PlaySound(soundobj) {
var thissound=document.getElementById(soundobj);
thissound.play();
}
function StopSound(soundobj) {
var thissound=document.getElementById(soundobj);
thissound.pause();
thissound.currentTime = 0;
}
For more information, check out the MDN guide for embedding audio and video
I had the same question, about starting and stopping audio. I use jQuery without any other plugins. My code is for mousedown and mouseup, but could be changed to other actions.
HTML
<div class="soundbutton">
cool wind sound
</div>
<audio id="wind-sound" src="wind-sound/wind.mp3">
Javascript
$('.soundbutton').on('mousedown', function () {
playWind(); //start wind sound
})
.on('mouseup', function () {
stopWind(); //stops the wind sound
});
// my full functions to start and stop
function playWind () { //start wind audio
$('#wind-sound')[0].volume = 0.7;
$('#wind-sound')[0].load();
$('#wind-sound')[0].play();
}
function stopWind () { //stop the wind audio
$('#wind-sound')[0].pause();
$('#wind-sound')[0].currentTime = 0; //resets wind to zero/beginning
}
<html>
<script>
function stopAudio() {
player.pause();
player.currentTime = 0;
}
</script>
<body>
<audio id="player" src="(place audio here)"></audio>
<div>
<button onclick=" stopAudio()">Stop</button>
</div>
</body>
</html>
//End Note: you must look at your audio id as mine is named "player"
this is the reason it is not working look at your css and your html
very closely in your lines. The other thing you must be careful about
is your call function as mine is stated as stopAudio() yours could be
named different. The function only works with css if you use your call
method properly.
Related
I am a total JavaScript amateur. I want to create a section where people can switch between 2 audios with a video running along with it. I want to show a before and after version of the audio.
Basically, the video should run with the "before" version of the audio initially. Then there should be a button to switch the audio to the "after" version, and go back and forth.
I tried the "audioTracks" method, but the browser compatibility is not good with it. What is the best possible way to achieve it?
Thanks in advance.
You just use two HTML Audio elements and then sync their times:
var audio1 = new Audio()
var audio2 = new Audio()
audio1.src = 'pathToSource',
audio2.src = 'pathToSource2',
var video = document.getElementByID('myvideo');
video.muted = true; //mute video cuz we have audio already
function switchAudio(one, two, vid) {
if(one.paused) {
two.pause();
one.currentTime = vid.currentTime;
one.play
} else {
one.pause();
two.currentTime = vid.currentTime;
two.play()
}
}
That did it :) I made some changes though. The audio seems to be working great. I could play and switch it. But the video was not starting up with the button. So I changed the code to this:
function switchAudio(one, two, vid) {
if (one.paused) {
two.pause();
vid.play();
one.play();
one.currentTime = vid.currentTime;
} else {
vid.pause();
one.pause();
vid.play();
two.play();
two.currentTime = vid.currentTime;
}
}
After this the video is playing along with the audio. But when I switch the audio, their timing does not match. The audio seems to be playing just a little bit late.
I'd like to know how could I achieve a video playlist without any buttons or control that would simply play an array of videos and would start again when the last is over.
I found this piece of code about a clickable playlist : http://jsfiddle.net/e8CbF/
but I really don't know how to make it automatic. Also, the array is coming from a PHP variable, how I can I use it inside this code ?
function loadVids(vidsArray){
for(var a=0,b,f=document.createDocumentFragment();b=vidsArray[a];++a){
var c=document.createElement('div');
c.textContent=b;
f.appendChild(c);
}
d.appendChild(f);
}
var video=document.createElement('video'),vids=['http://screen.alifts.com/screenfiles/video1.mp4','http://screen.alifts.com/screenfiles/video2.mp4'], /* Is it there that I should put the php array ? */
d=document.createElement('div');
d.onclick=function(e){if(e.target.parentNode==this){
video.src=e.target.textContent;
video.play();
}}
document.body.appendChild(video);
document.body.appendChild(d);
loadVids(vids);
Your code is a total mess. So i completely rewrite it.
<video src="" id="player"/>
<script>
var video=counter=0;
videos=['<?php echo join("';'",$array);?>'];
window.onload=()=>{
//get the video frame
video=document.getElementById("player");
//if the video ended, play next.
video.addEventListener("ended",play,false);
//start
play();
}
var play=()=>{
//add the video src
video.src=videos[counter];
//play next video next time
counter++;
if(counter==videos.length){
counter=0;
}
};
</script>
I am trying to use a intro sound for the mp3 files. After playing the intro the original track should start to play. i mean the original mp3 plays right after the intro ends. Here i have this:
<script type="text/javascript" src="js/jquery.min.js"></script>
<audio id='top' onended="playOrg();" preload='none' src='http://www.sounddogs.com/previews/59/mp3/607322_SOUNDDOGS__th.mp3' type='audio/mpeg'> </audio>
<a href='#' class='btn' id='audioControl'> START </a>
And here the javascript part:
<script type="text/javascript">
var yourAudio = document.getElementById('top');
var ctrl = document.getElementById('audioControl');
ctrl.onclick = function () {
var pause = ctrl.innerHTML === 'STOP';
$('.btn').html('START');
$('audio').trigger('pause');
ctrl.innerHTML = pause ? 'START' : 'STOP';
var method = pause ? 'pause' : 'play';
yourAudio [method]();
return false; };
function playOrg(){
yourAudio.setAttribute('onended','orgPlayed()');
yourAudio.src='http://www.sounddogs.com/sound-effects/59/mp3/606540_SOUNDDOGS__sf.mp3';
yourAudio.play();
console.log('playOrg()');
}
function orgPlayed(){
yourAudio.setAttribute('onended','playOrg()');
yourAudio.src='http://www.sounddogs.com/previews/59/mp3/607322_SOUNDDOGS__th.mp3';
yourAudio.pause();
yourAudio.currentTime = 0;
console.log('orgPlayed()');
}
</script>
When i press start the file plays and on the end it calls the playOrg() function witch should change some attributes and should play the original track. Then the second file should play and on its end this time the orgPlayed() function should be called and set back the attributes so that it is ready for the other play.
So i want to use intro track for all my track on the site. But i can't accomplish that. i appreciate any upcoming help.
PS: Actually there is a loop for all tracks in my original code but i summarised it here. Please don't ask why i couldn't find better mp3 test files :).
I found the my problem. Instead of reloading the new track with "currentTime=0" i tried to reload with "load()" , and now it works. I guess sometime we need to sleep over such problems :). Thanks to everyone ;).
<audio id='top' onended="playOrg();" preload='none' src='top10/intro/1.mp3' type='audio/mpeg'> </audio>
<a href='#' class='btn' id='audioControl'>START</a>
<script type="text/javascript">
var yourAudio = document.getElementById('top');
var ctrl = document.getElementById('audioControl');
ctrl.onclick = function () {
if (ctrl.innerHTML=='START') {
ctrl.innerHTML='STOP';
yourAudio.play();
}else if (ctrl.innerHTML=='STOP'){
ctrl.innerHTML='START';
yourAudio.pause();
}
}
function playOrg(){
var myPlayer= document.getElementById('top');
myPlayer.setAttribute('onended','orgPlayed()');
myPlayer.src='top10/tarkan.mp3';
myPlayer.pause();
myPlayer.load();
myPlayer.play();
}
function orgPlayed(){
var myPlayer= document.getElementById('top');
myPlayer.setAttribute('onended','playOrg()');
myPlayer.src='top10/intro/1.mp3';
myPlayer.pause();
myPlayer.load();
ctrl.innerHTML='START';
}
</script>
now i realised another way to solve this. i could use two audio tags with one intro source and the other the original source. and then after the first one ends i could play the second using either a function or directly onended="document.getElementById('top2').play();"
i mean something like this:
<audio id='top1' onended="play second(with a function or directly)" preload='none' src='intro' type='audio/mpeg'> </audio>
<audio id='top2' onended="make ready for another play (with a function or directly)" preload='none' src='original' type='audio/mpeg'> </audio>
<a href='#' class='btn' id='audioControl'>START</a>
I have a JavaScript code to play a sound on click.
It works on Chrome but on Firefox it starts on load.
Can anyone help?
<script>
var audio = new Audio("http://music.ogg");
audio.oncanplaythrough = function(){
audio.play();
}
audio.loop = true;
audio.onended = function(){
audio.play();
}
</script>
<input type="image" src="http://button.png" onclick="audio.play()">
Try the below code snippet
<!doctype html>
<html>
<head>
<title>Audio</title>
</head>
<body>
<script>
function play() {
var audio = document.getElementById("audio");
audio.play();
}
</script>
<input type="button" value="PLAY" onclick="play()">
<audio id="audio" src="https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3"></audio>
</body>
</html>
JavaScript
function playAudio(url) {
new Audio(url).play();
}
HTML
<img src="image.png" onclick="playAudio('mysound.mp3')">
Supported in most modern browsers and easy to embed into HTML elements.
That worked
<audio src="${ song.url }" id="audio"></audio>
<i class="glyphicon glyphicon-play-circle b-play" id="play" onclick="play()"></i>
<script>
function play() {
var audio = document.getElementById('audio');
if (audio.paused) {
audio.play();
$('#play').removeClass('glyphicon-play-circle')
$('#play').addClass('glyphicon-pause')
}else{
audio.pause();
audio.currentTime = 0
$('#play').addClass('glyphicon-play-circle')
$('#play').removeClass('glyphicon-pause')
}
}
</script>
Now that the Web Audio API is here and gaining browser support, that could be a more robust option.
Zounds is a primitive wrapper around that API for playing simple one-shot sounds with a minimum of boilerplate at the point of use.
You can do that in two line
let playSound = () => new Audio("src").play()
<button onclick="playSound()">Play</button>
While several answers are similar, I still had an issue - the user would click the button several times, playing the audio over itself (either it was clicked by accident or they were just 'playing'....)
An easy fix:
var music = new Audio();
function playMusic(file) {
music.pause();
music = new Audio(file);
music.play();
}
Setting up the audio on load allowed 'music' to be paused every time the function is called - effectively stopping the 'noise' even if they user clicks the button several times (and there is also no need to turn off the button, though for user experience it may be something you want to do).
HTML:
<button onclick="play()">Play File</button>
<audio id="audio" src="https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3"></audio>
JavaScript:
let play = function(){document.getElementById("audio").play()}
I have a little html5 application where you can play a sound by clicking a button.
I have a function that adds an <audio> tag to a <div> with an id "playing." The sound removes itself when it is done.
function sound(track){
$("#playing").append("<audio src=\"" + track + "\" autoplay onended=\"$(this).remove()\"></audio>");
}
For the button I have:
<button onclick="sound('sounds/tada.mp3')">Tada</button>
When I click the button, an <audio> briefly appears in the element inspector and disappears when it is finished, just the way I want it, but after triggering it two times, it just stops working in Chrome, at least. There are no errors in the console either.
What is going on?
Get rid of the onclick/onend in your HTML and reference the button in your js:
HTML
<button id='tada' sound_url='sounds/tada.mp3'>Tada</button>
And the JS
var sound = function(track){
$("#playing").append("<audio id='played_audio' src='\" + track + \"' autoplay='true'></audio>");
}
$('#tada').on('click', function () {
var sound_url = $(this).attr('sound_url');
sound(sound_url);
});
$('#playing').on('end', 'played_audio', function() {
$(this).remove();
});
Okay, lets see..
var audioURL = "http://soundbible.com/mp3/Canadian Geese-SoundBible.com-56609871.mp3";
var audioEl = null;
function removeAudio() {
if (audioEl && audioEl.parentNode)
audioEl.parentNode.removeChild(audioEl);
}
function sound() {
removeAudio();
audioEl = document.createElement("audio");
audioEl.src = audioURL;
audioEl.controls = true;
audioEl.addEventListener("ended", removeAudio); // <-- Note it's ended, not end!
document.getElementById("playing").appendChild(audioEl);
audioEl.play();
}
document.getElementById("tada").addEventListener("click", sound);
<div id="playing">
</div>
<button id="tada">Tada</button>
I'm not seeing any problems with this script.
Decide audioURL, set audioEl to null as it will be used later
When the element with ID "tada" is clicked, run our sound function.
Remove the audio.
Create the audio element.
When the audio is finished, remove the audio.
Append the audio to the element with ID "playing".
Play the audio.
One thing to note is that I use the ended event, not the end event.
(This answer is here because Andrew really wants us to answer it.)