chat sound not played in javascript - javascript

I am facing a problem for playing sound in javascript. The alert box is displayed but the chat sound doesn't play. Following is the code of chat.js.
for (x in newMessages) {
if (newMessages[x] == true) {
if (chatboxFocus[x] == false) {
//FIXME: add toggle all or none policy, otherwise it looks funny
$('#chatbox_'+x+' .chatboxhead').toggleClass('chatboxblink');
alert('before ');
var snd = new Audio("facebookchat.mp3");
snd.play();
alert('middle');
alert('after');
}
}
}

Try this:
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'facebookchat.mp3');
audioElement.load()
audioElement.addEventListener("load", function() {
audioElement.play();
}, true);
Reffered: How to use a javascript to autoplay a html5 audio tag
It might help, in your case.

Related

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

Toggle Play/Pause Youtube Video with external button

I have a template I'm building out using fullPage js to create sliding sections. The page supports video, but scroll and gestures are disabled when users scroll with the cursor on top of the video itself. Likewise, this behavior is observed on mobile.
To work around this, I'm using an empty div overlaying the youtube iframe. This solves the scrolling behavior, but I also lack the ability to directly control the youtube player. I've tried using the youtube API and jquery to fake being able to toggle play/pause with the empty div I have on top of the youtube player, but it's not working.
http://codepen.io/lumpeter/pen/XpayeB
The primary code for youtube is:
function onYouTubePlayerReady(playerId) {
ytplayer = document.getElementById("player");
ytplayer.addEventListener("onStateChange", "onPlayerStateChange");
}
function onPlayerReady(event) {
$('#video-button').click(function(event){
ytplayer.playVideo();
});
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
$('#video-button').click(function(event){
ytplayer.pauseVideo();
});
}
else {
$('#video-button').click(function(event){
ytplayer.playVideo();
});
}
}
Can anybody tell why this isn't working? I have event listeners looking for changes and using a boolean to detect the state of the video to toggle play/pause, but for some reason this doesn't work like I anticipated.
===============UPDATE=================
I've also tried the following:
$(document).on('click', '#pauseVideo', function(){
player = new YT.Player('myVideo')
if (event.data == player.PlayerState.PAUSED) {
$('#myVideo').get(0).contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}','*');
}
if (event.data == player.PlayerState.PLAYING) {
$('#myVideo').get(0).contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}','*');
}
});
However, I get the error "Uncaught ReferenceError: YT is not defined."
As fullpage.js already does part of the job by adding ?enablejsapi=1 and loading the JS script of the API for you, then you only have to do this:
var player;
window.onYouTubeIframeAPIReady = function() {
player = new YT.Player('myVideo');
}
$(document).on('click', '#pauseVideo', function(){
$('#myVideo').get(0).contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}','*');
});
Reproduction online
Thanks Alvaro! Yeah I was overthinking the solution a bit with the youtube api. I just needed to use a boolean with a binary true/false statement. Super easy, should have seen it before. Again thanks for your help!
var player;
window.onYouTubeIframeAPIReady = function() {
player = new YT.Player('myVideo',{
events: { 'onStateChange': onPlayerStateChange }
});
}
var isPlaying = true;
$(document).on('click', '#pauseVideo', function(){
if ( isPlaying == true){
$('#myVideo').get(0).contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}','*');
isPlaying = false;
} else {
$('#myVideo').get(0).contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}','*');
isPlaying = true;
}
});

Playing Audio Using Jquery

I have a small jQuery function to play audio when a user clicks the link. I don't need any controls, they are short samples. I just want to play anytime a user clicks. Here is the html for the section that should play;
</div class="classicalRecordings">
Open song
</div>
Then this is the jQuery to play the sound;
function playMusic(){
var audioElement = document.createElement('audio');
var audioElementSrc = $(this).attr('data-audio-src');
audioElement.setAttribute('src', audioElementSrc);
$.get();
audioElement.addEventListener("load", function(){
audioElement.play();
}, true);
}
$(function(){
$('.play').click(playMusic);
});
It doesn't seem to work. I think it has to do with the src variable, I am not sure I am passing it to the audioElement correctly. I have tested using an alert to be sure I am grabbing the data-audio-src correctly. Any help is appreciated.
I think that the event you're looking for is the loadeddata event.
function playMusic(){
var audioElement = document.createElement('audio');
var audioElementSrc = $(this).attr('data-audio-src');
audioElement.setAttribute('src', audioElementSrc);
$.get();
// changed "load" t0 "loadeddata"
audioElement.addEventListener("loadeddata", function(){
audioElement.play();
}, true);
}
$(function(){
$('.play').click(playMusic);
});
Although you could probably be better off having a static audio element and changing the src attribute on user clicks rather than creating a new audio element.
// example
var audio = document.getElementsByTagName('audio')[0];
audio.addEventListener('loadeddata', function() {
this.play();
}, true);
function playMusic() {
var audioElementSrc = $(this).attr('data-audio-src');
audio.setAttribute('src', audioElementSrc);
};
$('.play').click(playMusic);
There is a framework for this that is worth checking out. ListenJS. I wrote it :)
Try something like this:
<audio id="sound">
<source src="music/classical/open.mp3" type="audio/mpeg">
</audio>
And from code:
$(function(){
$('#sound').get(0).play();
});

Sound in Android

Why sound cannot be played in android version 4.1? When in browser sound can be played very well.
i am trying to play the sound when the card match and when the card mismatch.
I have currently developed my game using HTML5, CSS and javascript.
Javascript:
function playAudio(sAudio) {
var audioElement = document.getElementById('audioEngine');
if(audioElement !== null) {
audioElement.src = sAudio;
audioElement.play();
}
}
function playAudio(sAudio) {
var audioElement = document.getElementById('audioEngine');
if(audioElement !== null) {
audioElement.src = sAudio;
audioElement.play();
}
}
function checkPattern() {
if (isMatchPattern()) {
$(".card-flipped").removeClass("card-flipped").addClass("card-removed");
if(document.webkitTransitionEnd){
$(".card-removed").bind("webkitTransitionEnd", removeTookCards);
}else{
playAudio("mp3/WinLevel.mp3");
removeTookCards();
}
} else {
$(".card-flipped").removeClass("card-flipped");
playAudio("mp3/WrongLose.mp3");
}
}
HTML5:
<audio id="audioEngine">
our browser does not support the audio element.
</audio>
Can anyone help me?

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