.play JavaScript not playing sound sometimes - javascript

I have made and alarm page using .play() method. But sometimes audio does not play and sometimes it plays. My code it gets executed but the MP3 audio does not get played.
What could be the problem?
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
if (alrm4 != alrm4a) {
alrm4 = alrm4a;
audio.play();
blinker = 4;
}
}, 1000);
});
</script>
</head>
<body>
<script>
var audio = new Audio('Sound.mp3');
</script>
</body>
</html>

Providing more context would be helpful. Your code refers to two variables (alrm4 and alrm4a) that are not defined in the sample code you provided.
Chances are there was a problem loading the mp3 file or your condition, alrm4 != alrm4a, is not evaluating to true. Please edit your question to include the code which defines and manipulates these variables.

Related

Why does this code work on a separate file but not inline

This question may seem silly, but I really can't find out what the problem is. Initially I have a .js file only with this function that adds an audio to the page:
function addAudio(id_name, audio_filepath) {
var audio = $('<audio />')
.prop('id', 'audio' + id_name)
.prop('src', audio_filepath)
.text("Your reader doesn't support audio.");
$('body').append(audio);
$('#' + id_name).click(function () {
audio.get(0).play();
});
}
And it's being called in the html like this:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<!-- some content here -->
<button id="test">Play</button>
<!-- reference to lib containing jquery -->
<script type="text/javascript" src="js/lib.min.js"></script>
<!-- script where the function addAudio resides -->
<script type="text/javascript" src="js/add-audio.js"></script>
<script type="text/javascript">
$().ready(function() {
addAudio('test', 'audio/01-test.wav');
});
</script>
</body>
</html>
And that works fine. The problem is when I try to move the function out of the file and put it inline in the script tag. In that case, when I click the button, the console prints Uncaught TypeError: Cannot read property 'play' of undefined.
This is the modified code:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<!-- some content here -->
<button id="test">Play</button>
<!-- reference to lib containing jquery -->
<script type="text/javascript" src="js/lib.min.js"></script>
<script type="text/javascript">
function addAudio(id_name, audio_filepath) {
var audio = $('<audio />')
.prop('id', 'audio' + id_name)
.prop('src', audio_filepath)
.text("Your reader doesn't support audio.");
$('body').append(audio);
$('#' + id_name).click(function () {
audio.get(0).play();
});
}
$().ready(function() {
addAudio('test', 'audio/01-test.wav');
});
</script>
</body>
</html>
Trying to isolate the error, I found out that when the function is in the .js file, the variable audio is a jquery object [audio#audiotest], but when the function is inline, that variable is the object n.fn.init {}.
Why does that happen?
EDIT
I've noticed that that happens because it's in a xhtml file (I'm making an ebook in epub3 format). If I change the file to html it works again. But that is odd, because audio tags are supported in xhtml (you can check the specification here: http://www.idpf.org/accessibility/guidelines/content/xhtml/audio.php), and like I said, it works if the function is in a separate file. So why inline does not?
I think the issue is with your file reference. When I put your code into jsfiddle it appears to work referencing a wav file on the internet.
https://jsfiddle.net/ur64L8uh/
function addAudio(id_name, audio_filepath) {
var audio = $('<audio />')
.prop('id', 'audio' + id_name)
.prop('src', audio_filepath)
.text("Your reader doesn't support audio.");
$('body').append(audio);
$('#' + id_name).click(function () {
audio.get(0).play();
});
}
$().ready(function() {
addAudio('test', 'http://download.wavetlan.com/SVV/Media/HTTP/WAV/Media-Convert/Media-Convert_test1_Alaw_Mono_VBR_8SS_16000Hz.wav');
});
}
I found the answer, people. Thank you all for your attention and help, and sorry for the inconvenience. I was thinking about deleting this question, but I'm going to answer it to help those who might pass through the same thing.
According to Mozilla Foundation, using inline javascript in XHTML is troublesome: (https://developer.mozilla.org/en-US/docs/Archive/Web/Properly_Using_CSS_and_JavaScript_in_XHTML_Documents_/Examples#Example_1)
JavaScript typically contains characters which can not exist in XHTML outside of CDATA Sections.
So I solved the problem changing the line $('<audio />') to $('&t;audio /gt;')

How to play song using SoundCloud API

I am trying to make a music player that works with SoundCloud. So I have buttons like play, next, prev. and I made functions like:
function playIt(){
SC.stream("/tracks/293", function(sound){
sound.play();
});
}
So it plays song when the button is player:
<button onclick="playIt()">Play</button>
But it does not work. Any idea?
Here is the demo
1º - Put the JS files in the head. Use the "External Resources" on JSfiddle.
2º - Put var sound = [...] before the SC.steam.
Is that.
Demo: http://jsfiddle.net/don/zcN7G/3/
According to #lago above, let me deliver a full short code, so you can do your own labs ;-)
<!DOCTYPE html>
<html>
<head>
<script src=http://connect.soundcloud.com/sdk.js></script>
<script>
SC.initialize({client_id:'your client_id goes here'});
function p()
{
SC.stream
(
'/tracks/293',
function(s)
{
s.play()
}
)
}
</script>
</head>
<body>
<button onclick=p()>play</button>
</body>
</html>
API guide here

Create live video of jpeg snapshots using Gstreamer and JavaScript setTimeout()

I am trying to create a live "video" stream using an tag on a web page.
A Gstreamer pipeline continually overwrites a file "snapshot.jpeg" with a new frame grabbed from a webcam using video4linux2 with a framerate of 15 fps.
A web page renders the image without caching every 100 ms.
The problem is that I get ERR_CONTENT_LENGTH_MISMATCH (in browser console) for the image source on many frames. This is shown as a broken link in the browser.
GStreamer 0.10 syntax
gst-launch v4l2src ! video/x-raw-yuv, width=640, height=480, framerate=15/1 ! jpegenc ! multifilesink location=/var/www/video/snapshot.jpeg
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8' />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<img id="snapshot" src="snapshot.jpeg"/>
</body>
</html>
JavaScript
$(function() {
function refreshImage(){
$("#snapshot").attr("src", 'snapshot.jpeg?' + Math.random());
setTimeout(refreshImage, 100);
}
refreshImage();
})
Try to hook setTimeout to Image.onload:
$(function() {
function refreshImage(){
$("#snapshot").attr("src", 'snapshot.jpeg?' + Math.random());
}
$("#snapshot").onload = function(){
setTimeout(refreshImage, 100);
}
refreshImage();
})

Attaching onclick event to element is not working

I just started learning Javascript, and I know next to nothing. I am trying to attached an onclick event to an element in my HTML.
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").onclick = joinList;
This is my code so far. Nothing happens when the element with the ID of header is clicked on. What am I doing wrong?
the following is my HTML code
<!DOCTYPE html>
<html>
<head>
<title>Testing Page</title>
<script src="testing.js"></script>
</head>
<body>
<h1 id="header">Andrew Dawson</h1>
</body>
</html>
The issue is, that you try to load a html element, which does not "exists" when the javascript function is executed, because the dom has not finished loading.
To make your code work, you can try following solutions:
Place your script tag below in the HTML:
<!DOCTYPE html>
<html>
<head>
<title>Testing Page</title>
</head>
<body>
<h1 id="header">Andrew Dawson</h1>
<script src="testing.js"></script>
</body>
</html>
Add an event handler to check if the window element is ready:
window.addEventListener("load", eventWindowLoaded, false);
function eventWindowLoaded(){
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").onclick = joinList;
}
Another solution would be to use jquery framework and the related document ready function
http://api.jquery.com/ready/
I think the solve you are looking for is
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").setAttribute("onclick", joinList);
Your code seems straight forward, maybe your script is running before the DOM fully loads. To keep it simple across all browsers we can place a self executing anonymous function at the end to initiate all your scripts after DOM loads.
<html>
<title></title>
<head></head>
<body>
html here!!
<script>
(function() {
//Any other scripts here
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").onclick = joinList;
})();
</script>
</body>
</html>
The above is purely javascript, not to be confused with the shorthand (see below) of the jquery "document onready" function (you would need to add jquery to your pages).
$(function() {
//your javascript code here
});
Why using self executing function?

Can't write to dynamic iframe using jQuery

My goal is to dynamically create an iframe and write ad JavaScript into it using jQuery (e.g. Google AdSense script). My code works on Chrome, but fails intermittently in Firefox i.e. sometimes the ad script runs and renders the ad, and other times it doesn't. When it doesn't work, the script code itself shows up in the iframe.
My guess is these intermittent failures occur because the iframe is not ready by the time I write to it. I have tried various iterations of iframe_html (my name for the function which is supposed to wait for the iframe to be ready), but no luck. Any help appreciated!
PS: I have read various threads (e.g. jQuery .ready in a dynamically inserted iframe). Just letting everyone know that I've done my research on this, but I'm stuck :)
Iteration 1:
function iframe_html(html){
$('<iframe name ="myiframe" id="myiframe"/>').appendTo('#maindiv');
$('#myiframe').load(
function(){
$('#myiframe').ready( function(){
var d = $("#myiframe")[0].contentWindow.document;
d.open();
d.close();
d.write(html);
});
}
);
};
Iteration 2:
function iframe_html(html){
$('<iframe id="myiframe"/>').appendTo('#maindiv').ready(
function(){
$("#myiframe").contents().get(0).write(html);
}
);
};
Honestly, the easiest and most reliable way I have found when dealing with the load events on iframes uses the "onload" attribute in the actual iframe tag. I have never had much of a problem with setting the content once the "onload" event fires. Here is an example:
<html>
<head>
<script type='text/javascript' src='jquery-1.3.2.js'></script>
<script type='text/javascript'>
$(function() {
var $iframe = $("<iframe id='myiframe' name='myiframe' src='iframe.html' onload='iframe_load()'></iframe>");
$("body").append($iframe);
});
function iframe_load() {
var doc = $("#myiframe").contents()[0];
$(doc.body).html("hi");
}
</script>
</head>
<body></body>
</html>
The problem with this is that you have to use attribute tags and global function declarations. If you absolutely CAN'T have one of these things, I haven't had problems with this (although it doesn't look much different than your attempts, so I'm not sure):
<html>
<head>
<script type='text/javascript' src='jquery-1.3.2.js'></script>
<script type='text/javascript'>
$(function() {
var $iframe = $("<iframe id='myiframe' name='myiframe' src='iframe.html'></iframe>");
$iframe.load(iframe_load);
$("body").append($iframe);
});
function iframe_load() {
var doc = $("#myiframe").contents()[0];
$(doc.body).html("hi");
}
</script>
</head>
<body></body>
</html>
This is one of the most frustrating parts of the DOM and JavaScript - my condolences are with you. If neither of these work, then open up Firebug and tell me what the error message is.
false.html:
<html>
<head><title></title></head>
<body></body>
</html>
JS:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript">
function iframe_html(html)
{
var id = "myiframe_" + ((new Date()).getTime());
$('<iframe src="false.html" name ="'+id+'" id="'+id+'" />').appendTo('#maindiv');
var loadIFrame = function()
{
var elIF = window.document.frames[id];
if (elIF.window.document.readyState!="complete")
{
setTimeout(loadIFrame, 100);
return false;
}
$(elIF.window.document).find("body").html(html);
}
loadIFrame();
};
$(function(){
iframe_html("<div>hola</div>");
});
</script>
</head>
<body>
<div id="maindiv"></div>
</body>
</html>
then please see this link

Categories