Audio does not play when first clicked, only after second click (Javascript) - 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>

Related

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".

Why is my JavaScript Code not playing Music?

I want that my buttons ( Home, About, Blog ) on my website plays some sound or music when someone is clicking on them. Now I tried and tried, but cant find out the error in the javascript code.
<body onload="htmlIsReady()">
<script type="text/javascript">
var audio;
var audioLink;
window.onmessage = function(event) {
if (event.data.data) {
//Passes the audio url to the new variable
audioLink = event.data.data;
//Created a new audio object with the received audio url
audio = new Audio('URL of AUDIO-FILE');
}
};
function htmlIsReady() {
window.parent.postMessage("html_is_ready", "*");
}
//Funcion that plays the audio
function playAudio() {
audio.play.play();
}
</script>
// Button that executes the function that plays the audio everytime it's
clicked
<button class="button" onclick="playAudio()">Play</button>
</body>
You're using audio.play.play(), which should be: audio.play(). However, you also haven't provided any actual proper URL/relative filepath as the audio source and at the moment your audio variable is never actually assigned as a new Audio.
It's not too clear why you're using window.onmessage to obtain the url of the audio file but it won't work no matter what because event.data.data is simply wrong. To obtain the data of a posted message you have to use event.data.
Furthermore here you're assigning the data to a variable called audioLink
audioLink = event.data.data;
but don't actually use it for the instantiation of your HtmlAudioElement audio.
Lastly, audio.play.play(); is wrong. To start playback you simply use the play() method on the audio object - audio.play().
Here's a working example:
var audio;
var audioLink;
function playAudio() {
audio.play();
}
window.onmessage = function(event) {
if (event.data) {
audioLink = event.data;
audio = new Audio(audioLink);
}
};
window.postMessage("https://www.w3schools.com/tags/horse.ogg", "*");
<button class="button" onclick="playAudio()">Play</button>

Javascript pause sound when image is clicked

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/

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");
});

Minimalistic play() and pause() audio solution

I found a little code snippet within another question, playing an mp3 just with jquery play() and pause():
<a href="#" rel="http://www.uscis.gov/files/nativedocuments/Track%2093.mp3"
class="play">Play</a>
<div class="pause">Stop</div>
<script>
$(document).ready(function() {
var audioElement = document.createElement('audio');
var source = $('.play').attr('rel');
audioElement.setAttribute('src', source);
//audioElement.setAttribute('autoplay', 'autoplay');
audioElement.load()
$.get();
audioElement.addEventListener("load", function() {
audioElement.play();
}, true);
$('.play').click(function() {
audioElement.play();
});
$('.pause').click(function() {
audioElement.pause();
});
});
I get the audio source from the rel attribute of the "play"-link. Now I would like to add more audio links and make the source relative to their rel attributes.
I tried
var source = $(this).attr('rel');
and also .find() and .each(), but nothing worked so far. I've set up a jsfiddle with two audio links, where only the first audio file will be played. (The fiddle links to an external script, which the client uses on his site, where only jquery 1.4.3 is loaded, but I guess it's possible anyway. I just don't want to use an audio player plugin, I aim for a minimalistic solution.)
Any help would be highly appreciated!
You can update your script to create one audio tag per container:
$(document).ready(function () {
// For each container div
$(".container").each(function() {
// Create the HTML5 <audio> tag
var audioElement = document.createElement('audio');
// Find the play/pause buttons
var $play = $(this).find(".play");
var $pause = $(this).find(".pause");
// Load the source from the play button
var source = $play.attr('rel');
audioElement.setAttribute('src', source);
$.get();
// Play the sound when loaded
audioElement.addEventListener("load", function () {
audioElement.play();
}, true);
// When the user clicks on the play button, play the audio
$play.click(function () {
audioElement.play();
});
// When the user clicks on the pause button, pause it
$pause.click(function () {
audioElement.pause();
});
});
});
And updated Fiddle: http://jsfiddle.net/sY7UT/

Categories