Javascript pause sound when image is clicked - javascript

I'm using code that plays sound whn image is loaded (i'm using this as a play button on music player). But I have a problem, you can't stop sound when image is clicked (play button). So, do you know how can I make on this code, so sound pause when image is clicked.
My code:
<script type="text/javascript">
//Create new function that will update the image source on click.
function updateImage(el, soundfile) {
//Determine if music is playing or paused then adjust image
source accordingly.
if(soundfile.mp3.paused) {
el.src =
"imageurl.com";
} else {
el.src = "secondimageurl.com";
}
};
function playSound(el,soundfile) {
if (el.mp3) {
if(el.mp3.paused) el.mp3.play();
else el.mp3.pause();
} else {
el.mp3 = new Audio(soundfile);
el.mp3.play();
}
//Call new function made whenever the sound is toggled.
updateImage(document.getElementById("Bottom-1"), el);
};
</script>
<body onload="playSound(this, 'soundsource.mp3');">
<img src="buttonimage.html" name="Bottom-1" width="50" height="45"
border="0" id="Bottom-1"/>
</span>
</body>

Use SoundPlayer.js.
// Initialize
const player = new SoundPlayer();
// Load the sound
const sound = player.load('Sound.mp3');
// Play the sound
sound.play();
// load & play in one line
const sound = player.load('Sound.mp3').play();
And bind the image onclick event
image.onclick = function () {
sound[ sound.isPlaying ? 'pause' : 'play' ]();
image.src = sound.isPlaying ? 'isPlaying.jpg' : 'isPaused.jpg';
}
Full fiddle: https://jsfiddle.net/GustavGenberg/dxgph924/

Related

Audio does not play when first clicked, only after second click (Javascript)

Add added audio to my simple website and when i first click the button the audio does not play. After the second click it will play. If I wait a while then the problem will return.
There are no errors in the console and I even see chromes speaker icon on the tab but hear nothing.
Play
<script src="index.js"></script>
<script type="text/javascript">
// play audio on button click
document.getElementById('play').addEventListener('click', function () {
var audio = new Audio()
audio.src = '1.ogg'
// listen for can play event
audio.addEventListener('canplay', function () {
audio.play()
})
});
</script>
I also tried howler.js but the same problem happened.
<script type="text/javascript">
// play audio on button click
document.getElementById('play').addEventListener('click', function () {
var audio = new Audio();
audio.src = '1.ogg';
// added a volume value
audio.volume = 1;
// listen for can play event
audio.addEventListener('canplay', function () {
// try a console log to see if the function is called correctly
console.log("hello");
audio.play();
})
});
</script>
i added a console log to see if your function is really called
and put an volume so you are sure that the volume is not 0
Works fine
document.getElementById('play').addEventListener('click', function() {
var audio = new Audio()
audio.src = 'https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3'
audio.addEventListener('canplay', function() {
audio.play()
})
});
<button id="play">play</button>

AudioContext does not have a pause property?

I have used javascript Audio() before, but now I need to add some reverb effect in the audio and I am using reverb.js which uses the AudioContext api. I have the start property available, but no pause property? How do I pause or stop the audio??
Here is my code:
<script src="http://reverbjs.org/reverb.js"></script>
<script>
// 1) Setup your audio context (once) and extend with Reverb.js.
var audioContext = new (window.AudioContext || window.webkitAudioContext)();
reverbjs.extend(audioContext);
// 2) Load the impulse response; upon load, connect it to the audio output.
var reverbUrl = "http://reverbjs.org/Library/SaintLawrenceChurchMolenbeekWersbeekBelgium.m4a";
var reverbNode = audioContext.createReverbFromUrl(reverbUrl, function() {
reverbNode.connect(audioContext.destination);
});
// 3) Load a test sound; upon load, connect it to the reverb node.
var sourceUrl = "./sample.mp3";
var sourceNode = audioContext.createSourceFromUrl(sourceUrl, function() {
sourceNode.connect(reverbNode);
});
</script>
Play
Stop
Also, I tried using stop(), and it works, but when I fire start() after clicking on stop, the start() doesn't work. Can you you help me out with a solution??
You can use the suspend() and resume() methods of AudioContext to pause and resume your audio: https://developer.mozilla.org/en-US/docs/Web/API/AudioContext/suspend
One way to implement this with a single button for play/pause/resume, would be to add a function that controls the player state. For example:
let started = false;
function pauseOrResume() {
if (!started) {
sourceNode.start();
started = true;
document.getElementById("pauseButton").innerHTML = 'Pause';
} else if (audioContext.state === 'running') {
audioContext.suspend().then(function () {
document.getElementById("pauseButton").innerHTML = 'Resume';
});
} else if (audioContext.state === 'suspended') {
audioContext.resume().then(function () {
document.getElementById("pauseButton").innerHTML = 'Pause';
});
}
}
And replace your existing "Play" button with:
<a id="pauseButton" href="javascript:pauseOrResume()">Play</a>
This does the following:
If the audio hasn't yet been started, the link will say "Play".
If the user clicks "Play", the audio will start playing and the text of the link will change to "Pause".
If the user clicks "Pause" while the audio is playing, it will be paused, and the text of the link will change to "Resume".

My audio does not play when I click on the play button

This is how my script looks like:
<script>
var obj = document.createElement("audio");
document.body.appendChild(obj);
obj.src = "http://example.com/audios/Kalimba.mp3";
obj.load();
obj.volume = 0.3;
obj.preLoad = true;
obj.controls = true;
$(".testspeech").click(function() {
obj.paused?obj.play():obj.pause()
});
</script>
Then in the HTML I have a button that is meant to play and/or pause the video.
However, when I load the page nothing happens when I click on the play button.
Anything I could have possibly done wrong here?
Here is the HTML:
<button class="testspeech">
play/pause
</button>
As far as I can tell the reason your sound isn't playing is that the src for the actual sound is not valid. I've created a JSFiddle (here) to test it out, and after replacing the sound clip link it works as expected.
$(document).ready(function() {
var obj = document.createElement("audio");
document.body.appendChild(obj);
obj.src = "https://www.kozco.com/tech/piano2.wav";
obj.load();
obj.volume = 0.3;
obj.preLoad = true;
obj.controls = true;
$(".testspeech").on('click', function() {
obj.paused ? obj.play() : obj.pause()
});
});

How to create html button that runs two functions?

Hello I'm trying to create a play and pause button for a little web application I'm creating. I've already made a button that plays and another button that pauses but but now I need a button that'll run the play function when clicked and go back to the pause button when clicked.
var audio = new Audio("audio.mp3");
$(".play").click(function () {
audio.play();
})
$(".pause").click(function () {
audio.pause();
$(this).toggleClass(".play");
});
And here's the buttons
<div class="play"><img src="../images/play.gif"></img></div>
<div class="pause"><img src="../images/pause.gif"></img></div>
I know there could be and easy way to make a div change classes every time its clicked.
I would set up the <html> like this:
<div id="play"><img src="../images/play.gif"></img></div>
<!-- initially a play button -->
Then I would just use a boolean to switch back and forth in the script.
var toggleIt = false;
$("#play").click(function(){
if (!toggleIt){
audio.play();
toggleIt = true;
$("#play").find("img").attr("src", "file url here");
}
else{
audio.pause();
toggleIt = false;
$("#play").find("img").attr("src", "file url here");
}
})
edit: and here is a fiddle using wonderful place holder kittens. Yes, you should be grateful for my exquisite taste in placeholder pictures.
var audio = new Audio("audio.mp3");
$(".play").click(function () {
$(this).hide();
$(".pause").show();
audio.play();
})
$(".pause").click(function () {
audio.pause();
$(this).hide();
$(".play").show();
$(this).toggleClass(".play");
});
this is the simplest way. it would probably be better to do it with css psuedo classes, but i leave this pleasure to you if you care enough
You can create 2 diferents button and change de visibility
var audio = new Audio("audio.mp3");
$("#play").click(function () {
audio.play();
$("#play").hide();
$("#pause").show();
})
$("#pause").click(function () {
$("#pause").hide();
$("#play").show();
});
Set a variable then use a conditional to see if you should either play or pause the audio:
<div class="button"><img src="../images/play.gif"></img></div>
var play = true;
$(".button").click(function(){
if (play){
// Play
audio.play();
$(".button img").attr("src", "../images/pause.gif");
play = false;
} else {
// Pause
audio.pause();
$(".button img").attr("src", "../images/play.gif");
play = true;
}
});
Example
var audio = new Audio("audio.mp3");
$(".play").click(function () {
$(this).hide();
$(".pause").show();
audio.play();
})
$(".pause").click(function () {
audio.pause();
$(this).hide();
$(".play").show();
$(this).toggleClass(".play");
});

music play on load page in javascript

I have the following code in javascript that plays a sound
function muzplay() {
var muz = document.getElementById("song");
var button = document.getElementById("play");
if (muz.paused) {
muz.play();
button.textContent = "||";
} else {
muz.pause();
button.textContent = ">";
}
}
but it doesn't starts when the page is loading for the first time.
How can I make the song start when the page is loading?
If I would like to add an image as a button, instead of "button.textContent = "||";" what command can I use. for example I want to use a customize play and pause button instead of the || and > text.
window.onload = function(){ muzplay();}
// or
window.document.onload = function(){ muzplay();}
// or
muzplay();

Categories