Why is my JavaScript Code not playing Music? - javascript

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>

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>

How to play sound in javascript?

I create websocket server in python to handle notification event. Now, i can receive notification, the problem is i can't play sound because new autoplay policy changed, if i play sound using javascript it give me domexception. Any suggestion please ?
As i know, playing sound is simple in html-javascript. like this example: https://stackoverflow.com/a/18628124/7514010
but it depend to your browsers and how you load and play, so issues is:
Some of browsers wait till user click something, then let you play it (Find a way for it)
In some case browsers never let you play till the address use SSL (means the HTTPS behind your url)
The loading be late so the playing be late / or even not start.
So i usually do this:
HTML
<audio id="notifysound" src="notify.mp3" autobuffer preload="auto" style="visibility:hidden;width:0px;height:0px;z-index:-1;"></audio>
JAVASCRIPT (Generally)
var theSound = document.getElementById("notifysound");
theSound.play();
And the most safe if i want sure it be played when i notify is :
JAVASCRIPT (In your case)
function notifyme(theTitle,theBody) {
theTitle=theTitle || 'Title';
theBody=theBody || "Hi. \nIt is notification!";
var theSound = document.getElementById("notifysound");
if ("Notification" in window && Notification) {
if (window.Notification.permission !== "granted") {
window.Notification.requestPermission().then((result) => {
if (result != 'denied') {
return notifyme(theTitle,theBody);
} else {
theSound.play();
}
});
} else {
theSound.play();
try {
var notification = new Notification(theTitle, {
icon: 'icon.png',
body: theBody
});
notification.onclick = function () {
window.focus();
};
}
catch(err) {
return;
}
}
} else {
theSound.play();
}
}
(and just hope it be played. because even possible to volume or some customization make it failed.)
to bypass new autoplay policy :
create a button that can play the sound, hide it and trigger the sound with :
var event = new Event('click');
playBtn.dispatchEvent(event);
EDIT
assuming you have :
let audioData = 'data:audio/wav;base64,..ᴅᴀᴛᴀ...'; // or the src path
you can use this function to trigger whenever you want without appending or create element to the DOM:
function playSound() {
let audioEl = document.createElement('audio');
audioEl.src = audioData;
let audioBtn = document.createElement('button');
audioBtn.addEventListener('click', () => audioEl.play(), false);
let event = new Event('click');
audioBtn.dispatchEvent(event);
}
usage :
just playSound()
EDIT 2
I re test my code and it does'nt work hum ... weird

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

audio.play() html tag doesn't play in chrome

I am facing an issue while playing audio in chrome when audio.src is not called preceeding to play call. However, firefox plays it alright. Can someone pls suggest? Below is the fiddle link -
http://jsfiddle.net/vn215r2d/1/
One can also find the code over here -
<html>
<head>
<script language="javascript">
var audioo = document.createElement("audio");
function newCall() {
audioo.src = "";
audioo.src = "http://xx.xx.xx.xx:8181/api/captcha/sound";
audioo.play();
}
function playAgain() {
audioo.play(); // doesn't work in chrome :(
}
</script>
</head>
<body>
<button type="button" onClick="newCall()">New Captcha Call</button>
<br>
<button type="button" onClick="playAgain()">Replay Captcha</button>
</body>
</html>
Update
Oh waw, apparently is comes down to the audio.currentTime not being writeable until you rewrite the src. Heres what you can do and it does work:
function newCall() {
audioo.src = "http://xx.xx.xx.xx:8181/api/captcha/sound";
// make all audio attributes writeable again by resetting the src
audioo.src = audio.src;
}
The answer took a bit of googling, but I got it from here: https://stackoverflow.com/a/14850353
Original
I tested on Chrome with resetting the audio position and it worked. Its safest to pause first, but it works either way.
var audioo = document.createElement("audio");
// Lets add an event listener to play when we are ready to start playing
audioo.addEventListener("canplaythrough", function(){
audioo.play();
}, false);
function newCall() {
audioo.src = "";
audioo.src = "http://xx.xx.xx.xx:8181/api/captcha/sound";
}
function playAgain() {
// Let's check if we are ready enough to play
if(audioo.readyState === 4){
audioo.pause(); // first pause
audioo.currentTime = 0; // then reset
audioo.play(); // then play
} else {
// else inform us that we are not ready to play yet.
alert("Audio not ready yet.");
}
}
Here are two fun resources that can help:
MDN:
MediaElement (usefull properties and functions)
MDN:
Media Events (for event listeners)

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