Javascript HTML play sound only once, but more strange thing happened - javascript

I tried this simple snippet in codepen. and function once1 can play as many times as you want while once2 can play sound only once.
Anyone know what's the difference?
var simple = new
Audio("http://s3.amazonaws.com/freecodecamp/simonSound1.mp3" );
var birdSound = new
Audio('http://www.noiseaddicts.com/samples_1w72b820/4929.mp3');
birdSound.loop = false;
simple.loop = false;
function once1(){
birdSound.play();
};
function once2(){
simple.play();
};

Here you go, I saw the other answer still wasn't working on jsfiddle or codepen so try this!
var simple = new
Audio("http://s3.amazonaws.com/freecodecamp/simonSound1.mp3" );
var birdSound = new
Audio('http://www.noiseaddicts.com/samples_1w72b820/4929.mp3');
birdSound.loop = false;
simple.loop = false;
function once1(){
birdSound.load();
birdSound.play();
};
function once2(){
simple.load();
simple.play();
};
Just use .load :D

Update: Using the load() method, as suggested by the other poster, I can get the code below to repeatedly play the second sound in Chrome, but it still sounds different than it does in Firefox. In Firefox the sound plays smoothly, but in Chrome the sound ends more abruptly, with a little bit of a crackle or click. I suspect that there's just something about this particular sound file that isn't fully compatible with Chrome.
I'm able to get both sounds to play as many times as I want in Firefox with this Plunker here, but not in Chrome: http://plnkr.co/edit/gM8lobVoQoAtVSlwVZNC?p=preview
function init() {
var simple = new Audio("http://s3.amazonaws.com/freecodecamp/simonSound1.mp3" );
var birdSound = new Audio('http://www.noiseaddicts.com/samples_1w72b820/4929.mp3');
birdSound.loop = false;
simple.loop = false;
function once1() {
birdSound.play();
}
function once2() {
simple.load();
simple.play();
}
var btn1 = document.getElementById("one");
btn1.addEventListener('click', once1);
var btn2 = document.getElementById("two");
btn2.addEventListener('click', once2);
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body onload="init()">
<button id="one">Sound 1</button><br>
<button id="two">Sound 2</button>
</body>
</html>
Which web browser were you using?

Related

One Script for multiple buttons

I've got a soundboard I use at work to annoy coworkers. It has multiple buttons, that play or stop a sound. Right now each button has its own script to play the sound. So I'm up to 47 sounds on the page and have to write this script for each one. I'd like to clean that up and have a one smarter script that works for all of them.
my buttons look like:
<button onclick="javascript:toggleSound1();">I don't know what we're yelling about.</button>
Then I have the definition of the audio element:
<audio id="sound1" src="sounds/dontknowwhatwereyellingabout.wav"></audio>
and the script:
<script type="text/javascript">
function toggleSound1() {
var audioElem = document.getElementById('sound1');
if (audioElem.paused)
audioElem.play();
else
audioElem.pause(); audioElem.currentTime = 0;
}
</script>
So it seems to me that if i could define the 'sound1' on the press in each button the same script should work for each button. as I have it now I have to define 'sound1' 'sound2' 'sound3' and so on, and point a new 'togglesound' at each of them.
You could rewrite toggleSound1 to take an argument:
function toggleSound(num) {
var audioElem = document.getElementById('sound' + num); // append the number to "sound" (sound1, sound2, etc.)
if (audioElem.paused) {
audioElem.play();
} else {
audioElem.pause();
}
audioElem.currentTime = 0;
}
Then to use it, you could just pass the number to the function:
<button onclick="javascript:toggleSound(1);">I don't know what we're yelling about.</button>
I'm not sure how I feel about encouraging this, but...
<button onclick="toggleSound('sound1');">I don't know what we're yelling about.</button>
<button onclick="toggleSound('sound2');">Some other sound</button>
<script type="text/javascript">
function toggleSound1(soundId) {
var audioElem = document.getElementById(soundId);
if (audioElem.paused)
audioElem.play();
else
audioElem.pause(); audioElem.currentTime = 0;
}
</script>
a better way is to use event delegation, and put the event handler higher up
<div onclick="handleAudio(e)">
<button data-audio="1">I don't know what we're yelling about.</button>
<button data-audio="2">Some other sound</button>
</div>
function handleAudio(e) {
var audio = document.getElementById('sound' + e.target.dataset.audio);
audio.play();
}

HTML5 Voice API - Resetting Result Array

I'm using the HTML5 voice API for a project. I'm having trouble trying to set the result array: event.results.
I'm listening for '[A-H][0-9] "INTO" [A-H][0-9] "GO"'. When I hear "GO", I want to reset the events.result array. I have to listen for the same input again, but the first input cannot be removed from the event.results array.
I've tried:
event.results = [];
event.results.length = 0;
None of these work. I've also looked up the API and I can't find the solution to what I'm trying to do.
A similar example to what I want to do, would be if it was listening for any sequence of words. But when it heard the word "Cancel", it would forget everything it had just heard.
I hope this makes sense and any help is greatly appreciated.
It seems that the results are held in a SpeechRecognitionList, but I couldn't find any api for manipulating the list itself.
What does work is stopping and restarting the recognition, but that's problematic if you're not using a https-site (on a plain http site the browser always asks for permission when restarting recognition).
Here's an example:
<html>
<head>
<title>voice api test</title>
</head>
<body>
<h1>voice api test</h1>
<main></main>
<script>
(function startRecognizing() {
var main = document.querySelector('main');
var recognition = new webkitSpeechRecognition();
recognition.continuous = true;
recognition.addEventListener('result', function (event) {
var lastResult = event.results[event.results.length - 1];
if (lastResult[0].transcript.indexOf('cancel') > -1) {
recognition.stop();
while (main.children.length) main.removeChild(main.children[0]);
startRecognizing();
} else {
var p = document.createElement('p');
p.appendChild(document.createTextNode(lastResult[0].transcript));
main.appendChild(p);
}
});
recognition.start();
}());
</script>
</body>
</html>

Why does calling a function onclick not work all the time in Chrome and FF, but works in IE?

I have the below code:
<HTML>
<HEAD>
<SCRIPT>
function myFunction(atlasTrackingURL)
{
var atlasURL = atlasTrackingURL;
if (!atlasURL) return;
//Build a cache busting mechanism
var timestamp = new Date();
var queryString = "?random=" + Math.ceil(Math.random() * 999999999999) +
timestamp.getUTCHours() + timestamp.getUTCMinutes() +
timestamp.getUTCSeconds();
//Build the final URL
atlasURL = atlasURL + queryString;
if (!document.getElementsByTagName || !document.createElement
|| !document.appendChild)
{return false;}
else
{ //Activate the JACTION call
var script = document.createElement("script");
script.type = "text/javascript";
script.src = atlasURL;
document.getElementsByTagName("head")[0].appendChild(script);
return true;
}
}
</SCRIPT>
</HEAD>
<BODY>
Test - Click Me
</BODY>
</HTML>
It works in Internet Explorer every time, but rarely works in Chrome and Firefox. Why would this be?
Can these browsers not handle a function onClick very well? Are there any other options I can take?
I am trying to help a client figure out why one of their tracking tags are not firing off all the time on click in these browsers.
Thanks,
You've got some kind of browser-dependent race condition going on, as Musa pointed out.
Try hiding the link initially, waiting for the document to load, and then adding the onclick attribute and revealing the link with javascript.
So, for example, change the link HTML to something like:
<a id="microsoft-link" href="http://www.microsoft.com" style="display: none;">Test - Click Me</a>
And add in your javascript, below the myFunction(), something like:
document.addEventListener('DOMContentLoaded', function(){
var link_elem = document.getElementById("microsoft-link");
link_elem.onclick = function() {
myFunction('http://view.atdmt.com/jaction/adoakb_PiggybackJSTest_1');
};
link_elem.style.display = 'inherit';
});
jsfiddle -- http://jsfiddle.net/m8VTy/3/
edit: I realized I may be misinterpreting what you're trying to do. What exactly is myFunction() supposed to accomplish ?

Javascript, Variable is not accesible by function

I made an phonegap application that plays an sound when the user clicks on the button:
<button onclick="playAudio('test.mp3')">Play Some Audio</button>
But i want that the sound stops when the user makes an doubleclick, somehow my code dont works! Im an beginner in javascript, and think the i didnt put the variable = media in the right position. Here is my full code:
<body>
<h1>Playing Audio</h1>
<button onclick="playAudio('test.mp3')">Play Some Audio</button>
<script type="text/javascript" src="cordova-2.4.0.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
var playing = false;
var media = null;
function playAudio(src) {
if (!playing) {
if (device.platform == 'Android') {
src = '/android_asset/' + src;
}
var media = new Media(src);
media.play();
playing = true;
} else {
media.stop();
playing = false;
}
}
</script>
</body>
Change the following line
var media = new Media(src);
to
media = new Media(src);
Now i found the problem, you cannot use
media = new Media (src)
instead i had tu use
my_Media = new Media (src)
There is an interreference with the word media!
But what #Alexandre said was absolutley correct, and that brougt me to the final result!
Thanks

Javascript Sound Start/Stop and Image Change

I am new to JS and I have a pretty simple-seeming problem.
I want to have a small image that when clicked changes to a different image and at the same time begins playing a looped sound file. When the image is clicked a second time it changes back to the original image and also stops the sound file.
You can think of it as a button that says "start". when "start" is clicked it loops the sound and changes to "stop" and when "stop" is clicked it goes back to start and the sound ceases playing.
I've gotten as far as creating none-displayed checkbox inside of a label which is a square that when checked plays sound and when unchecked stops sound. Problem is I can't get the checkbox to change into different images with "check", "uncheck".
I've also got some code that has a link change images, but I cannot figure out how to make it play the sound.
SO basically i need to combine these two things. BUT I CAN'T figure out how. And I've been googling for the past two days nonstop but cannot find a clearcut and simple answer.
It may help to know that I plan on having many of these small clickable images on the same page, so the Javascript needs to be able to be light but effect all of the links or divs or whatever they are in the end.
Sorry for such a long question. Anybody?
Thanks in advance!
<html>
<head>
<script type="text/javascript">
var pos = 0
var sId = 'sound';
function change() {
if(pos == 0) {
pos = 1;
document.getElementById('btn').src="http://www.buzzingup.com/wp-content/uploads/2011/07/stop.png";
var e = document.createElement('embed');
e.setAttribute('src','beep.mp3');
e.setAttribute('id',sId);
e.setAttribute('hidden','true');
e.setAttribute('autostart','true');
e.setAttribute('loop','true');
document.body.appendChild(e);
} else {
pos = 0;
document.getElementById('btn').src="http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png";
document.body.removeChild(document.getElementById(sId));
}
}
</script>
</head>
<body>
<img src="http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png" onClick="change()" id="btn" />
</body>
</html>
How about that, I think it should work.
Edit:
Here is an OO version that should do what you need:
<html>
<head>
<script type="text/javascript">
function imageSwitch(_imgID,_imgStart,_imgStop,_soundFile) {
this.imgID = _imgID;
this.imgStart = _imgStart;
this.imgStop = _imgStop;
this.soundFile = _soundFile;
this.pos = 0;
this.e;
this.change = function() {
if(this.pos == 0) {
this.pos = 1;
document.getElementById(this.imgID).src = this.imgStop;
this.e = document.createElement('embed');
this.e.setAttribute('src',this.soundFile);
this.e.setAttribute('id','sound'+this.imgID);
this.e.setAttribute('hidden','true');
this.e.setAttribute('autostart','true');
this.e.setAttribute('loop','true');
document.body.appendChild(this.e);
} else {
this.pos = 0;
document.getElementById(this.imgID).src = this.imgStart;
this.e.parentNode.removeChild(this.e);
}
}
}
</script>
<script type="text/javascript">
var abc = new imageSwitch('btn1','http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png','http://www.buzzingup.com/wp-content/uploads/2011/07/stop.png','beep.mp3');
var def = new imageSwitch('btn2','http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png','http://www.buzzingup.com/wp-content/uploads/2011/07/stop.png','beep.mp3');
</script>
</head>
<body>
<img src="http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png" onClick="abc.change()" id="btn1" />
<img src="http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png" onClick="def.change()" id="btn2" />
</body>
</html>

Categories

Resources