Play a beep sound on button click - javascript

OK I've read several answers here but they didn't help me at all (in fact, none of them is being accepted as answer)
Question is how to "Play a beep sound" on "button click"
I am trying to make a website that works on touchscreen device so I want every button click events will play a beep sound, that should be nicer for users who using the website. Beep sound file is here: http://www.soundjay.com/button/beep-07.wav . I only need this work on Google Chrome (supports HTML5)
I understand this need to work on client-side so I tried this:
Javascript:
<script>
function PlaySound(soundObj) {
var sound = document.getElementById(soundObj);
sound.Play();
}
</script>
HTML
<embed src="/beep.wav" autostart="false" type="audio/mpeg" loop="false" width="0" height="0" id="beep" enablejavascript="true" />
<asp:LinkButton ID="lbtnExit" runat="server" OnClick="lbtnExit_Click" OnClientClick="PlaySound('beep')" CssClass="btn btn-lg btn-danger" Text="Exit <i class='fa fa-sign-out' style='font-size: 40px'></i>"></asp:LinkButton>
But it doesn't work, nothing happens when I click the button.

You could use an audio tag like this:
<audio id="audio" src="http://www.soundjay.com/button/beep-07.wav" autoplay="false" ></audio>
<a onclick="playSound();"> Play</a>
<script>
function playSound() {
var sound = document.getElementById("audio");
sound.play();
}
</script>
Here is a Plunker

Admitting you already have something like <div id='btn'>Click to play!</div> in your html, you could do it as simple as:
$('#btn').click( () => new Audio('mp3/audio.mp3').play() );
This is the best solution IMO because it allow to click multiple times quickly on the button without problem (which is not possible in other answers at the time) and is a one liner.
const audioUrl = 'https://freewavesamples.com/files/Ensoniq-ESQ-1-Piano-C3.wav'
$('.btn').click( () => new Audio(audioUrl).play() ); // that will do the trick !!
body {padding: 16px;}
.btn {
background: tomato;
padding:15px;
border-radius:5px;
color:#fff;
cursor: pointer;
box-shadow: 0 -3px rgba(0,0,0,0.15) inset;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class='btn'>Click to play!</span>
Example on codepen

This works fine
function playSound () {
document.getElementById('play').play();
}
<audio id="play" src="http://www.soundjay.com/button/beep-07.wav"></audio>
<button onclick="playSound()">Play</button>

Technically, the following doesn't answer the question about "playing" a beep, but if asking how to "generate" a beep, then consider the following code that I found on this website:
a=new AudioContext()
function beep(vol, freq, duration){
v=a.createOscillator()
u=a.createGain()
v.connect(u)
v.frequency.value=freq
v.type="square"
u.connect(a.destination)
u.gain.value=vol*0.01
v.start(a.currentTime)
v.stop(a.currentTime+duration*0.001)
}
Sample values for the call: beep(20, 100, 30). The aforementioned website includes more details and sound samples.
The sound can be in response to a button click or programmatically generated at will. I have used it in Chrome but have not tried it in other browsers.

With raw JavaScript, you can simply call:
new Audio('sound.wav').play()

Been driving me crazy, but with JQuery I found a solution... not really the best way to do it, but it worked properly for me...
function ding() {
$("body").append('<embed src="/ding.mp3" autostart=false autoplay=false type="audio/mpeg" loop="false" width="0" height="0" id="beep" enablejavascript="true" />');
setTimeout(function(){ $("#beep").remove(); },2000);
}
not sure how much of the embed tag is really required, but once it started working, I stopped writing (embed copied from another solution).
Hope this helps someone else (or helps me the next time I forget)

expanding on Alan M.'s answer, this will prevent console errors if unable to run due to no user event yet
var actx = false;
function beep(vol, freq, duration){
try{
if(!actx) actx = new AudioContext();
v=actx.createOscillator();
u=actx.createGain();
v.connect(u);
v.frequency.value=freq;
u.connect(actx.destination);
u.gain.value=vol*0.01;
v.start(actx.currentTime);
v.stop(actx.currentTime+duration*0.001);
}catch{
// ignore
}
}

Related

How to prevent HTML code from running?

I seek to embed multiple iframes on a single page without slowing the page. When I embedded a single iframe, it was running smoothly; added a second and third, and all were slower - despite only one being displayed at a time (using JScript). I presume this is due to the iframe code still executing.
How can I execute code conditionally? In my case, whenever a button is clicked.
Help is appreciated. Fiddle for the exact code I use, with actual content replaced by IDs and iframes by p's: http://jsfiddle.net/aof89Ljt/55/
HTML for the iframes:
<p id="ifr1">
ifr1
</p>
<p id="ifr2" style="display:none;">
ifr2
</p>
<p id="ifr3" style="display:none;">
ifr3
</p>
UPDATE: New JFiddle link with JScript included. End-goal description: I click a button which displays a different embedded Desmos graph, then another graph, then the first graph - in a loop, one at a time (see code). Demonstration gif: https://puu.sh/Bjpil/da9a038e11.gif
UPDATE 2: Solution found; full code: https://jsfiddle.net/32uxrhmw/49/
UPDATE 3: Greatly optimized code: https://jsfiddle.net/32uxrhmw/92/
You need to add the onclick="<your function>" event trigger to the element(s) you want to "do something".
Simple example:
<button onclick="swap()">Button</button>
<iframe style="display: none;" data-url="https://www.example.com" id="iframe">
<p>Your browser does not support iframes.</p>
</iframe>
<script>
function swap() {
e = document.getElementById('iframe'); // get iframe
url = e.dataset.url; // get desired url attribute stored in data-url
e.setAttribute("src", url); // add the iframe src with desire url
e.removeAttribute("style"); // remove styling that hid it otherwise
}
</script>
UPDATED to better apply to question.
UPDATED again to also incorporate #Joe Fitzsimmons good suggestion re handling iframe sources (in his answer).
FINAL ADDITION SEEING YOUR CODE:
Looking at your last code, it seems what you want to do is:
load page with one iframe;
then change iframe displayed when the button is clicked.
If that is what you want, you might want to use this much simpler code:
(Note: I used your code sample as a base, but haven't inserted any src urls - yours may be private, but even if not they all showed the same result so it may confuse other readers)
<style>
.tdropbtn {
background-color: white;
font-size: 16px;
border: none;
cursor: pointer;
color: #0066CC;
}
</style>
<center>
<iframe id="frame" src="https://url1" width="500px" height="400px" frameborder=0></iframe>
</center>
<div style="display:inline;">
<center>
<button onclick="swap()" class="tdropbtn">[+]</button>
</center>
</div>
<script>
var counter = 1;
var firstFrame = "https://url1";
var secondFrame = "https://url2";
var thirdFrame = "https://url3";
var e = document.getElementById("frame");
function swap() {
if (counter == 0){
e.src = firstFrame;
counter++;
}
else if (counter == 1){
e.src = secondFrame;
counter++;
}
else if (counter == 2){
e.src = thirdFrame;
counter = 0;
}
}
</script>
One idea would be to load/remove the source of the iframe onClick.
This is a rough idea of what you could do:
function Swap(id, url) {
document.getElementById(id).src = url;
}
You'd have to show and hide the iFrames as well. Hopefully this could get you on your way. I'm not exactly sure what your end goal is.

Trigger function when clicking play button on <audio>

I have my audio element:
<audio class='mp3audio' src='file.mp3'></audio>
And I want to perform a function or an action when the play button is clicked in jQuery. I've found lots of things for creating your own custom controls, but nothing to fire when the play button is clicked. The closest I've found is this, but then I can't use useful things like $(this).
I really want something like this:
$('audio.mp3audio').click(function () {
alert("you clicked play");
});
But I can't find any documentation on it?
You can hook to the playing event, so you can run the code no matter how the audio element is controlled; either from the play control, or manually through code. Try this:
$('audio').on('playing', function() {
console.log('playback started!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio id="audio" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto" controls></audio>
pass the this object in your function as
<audio class='mp3audio' src='file.mp3' onplay="myFunction(this)"></audio>
and receive it as
function myFunction(element){
console.log(element);
}
Take a look to this example
function playBeep() {
var sound = document.getElementById("Sound")
sound.play();
}
<div class="animatedButton">
<audio id="Sound" src="https://www.soundjay.com/button/sounds/beep-07.mp3"></audio>
<button id="aButton" onclick="playBeep()">
beep
</button>
</div>
You can do this in 3 ways:
In HTML:
<audio onplay="myScript">
In JavaScript:
var audio = document.getElementById("myAudio");
audio.onplay=function(){myScript};
In JavaScript, using the addEventListener() method:
var audio = document.getElementById("myAudio");
audio.addEventListener("play", myScript);
HTML
<audio class='myaudio' ></audio>
JQUERY
$('.myaudio').on('playing', function(){
//your code
});

I have a site that changes themes, I'm trying to get the iframe to change themes with the site

I'm not sure how i'm able to do such a thing. I've been searching for an answer and have come up empty handed. I'm thinking javascript is the answer here but i'm just not sure how to implement it into the current script i'm using to change the theme of the site.
Thanks for any assistance!
If the iframe content is hosted externally, you can't modify it due cross-domain site scripting rules.
Not really sure what you would change but you could do.
<iframe id="theframe" src="something.pdf" style="background-color: #FFF;" />
this would do it. or if you were to do it using css.
<iframe id="theframe" src="somthing.pdf"/>
CSS:
#theframe{
background-color: blue;
}
i am a little confused on what you wanted. did you want this to change while the user is on it or like change when you get tired of it?
EDIT: the color would only show up if the src does not load. otherwise it would have something in it.
EDIT: ok to do this with a button it would be (i am using the example above for reference) i will add a button(just one) and the script. Hope this helps.
<script>
function change(){
if(document.getElementById("thebutton").innerHTML == "light"){
document.getElementById("thebutton").innerHTML = "dark";
document.getElementById("theframe").contentWindow.document.body.style.backgroundColor = "white";
}
else{
document.getElementById("thebutton").innerHTML = "light";
document.getElementById("theframe").contentWindow.document.body.style.backgroundColor = "black";
}
}
</script>
<button id="thebutton" type="button" onclick="change();">Dark</button>
<iframe id="theframe" src="" />
if you want to do this on two buttons just put code where it changes the frame into the button instead like.
<button id="thebutton" type="button" onclick="document.getElementById("theframe").contentWindow.document.body.style.backgroundColor = "black";">Dark</button>
<button id="thebutton" type="button" onclick="document.getElementById("theframe").contentWindow.document.body.style.backgroundColor = "white";">Light</button>
<iframe id="theframe" src="" />
hope this helps. if it answers the question put a check so other people can find it.

Mouseover and Mouseout javascript not working in Firefox

I've written some basic Javascript code to work with the videos on my website. Basically I have embedded video content, placed a transparent and clickable div over the video that when hovered over will play the video behind it, then pause when the mouse is moved away. It works flawlessly on Chrome and Safari (not tested IE, I work on a Mac) but not at all on Firefox, the videos do not play. I've searched here and other places for a reason why, but haven't been able to find anything. I've only started playing with Javascript the last couple of weeks so I wouldn't be surprised if I've missed something obvious!
<div class="sectionWrapper">
<a href="http://weathereddown.co.uk">
<div id="sales-section" class="video-block" onmouseover="playVideo1()" onmouseout="playVideo1()"></div>
</a>
<div class="videoWrapper">
<div id="wistia_92lscndvjx" class="wistia_embed" style="width:900px;height:506px;"> </div>
</div>
<script charset="ISO-8859-1" src="//fast.wistia.com/assets/external/E-v1.js"></script>
<script>
wistiaEmbed = Wistia.embed("92lscndvjx", {
videoFoam: true
});
</script>
<script type="text/javascript">
var open = false;
function playVideo1() {
open = !open
if (open == true) {
document.getElementById('wistia_8').play();
}
else {
document.getElementById('wistia_8').pause();
}
}
</script>
</div>
The Id references ('wistia_8') are correct, they refer to the code automatically generated on the page by the Wistia embed code.
Try using the same methods as the W3Schools site but instead of hooking up the buttons use your mouseover mouseout events instead!
Here
Hope this helps!

Implement site with text reader

I have decided to start a new project.
This project is a spell checker to help children and send the report on how well the child is performing to the teacher.
I have already set up where the teacher can place the word, and what I now need to do is that when the pupil clicks the button, the word gets read out loud.
Is there any plugin that I could use?
I'm not worried about how the pupil will access the word but how to make the word be read out.
Any language will be fine.
Thank you all for your time.
I guess the easiest thing would be to use html5 audio to play the according word from the webserver whenever it is clicked:
<html>
<body>
<script type="text/javascript">
window.onload = function main() {
var path = "/sndz"; //folder on the webserver for all your sound files
var Hello = document.getElementById("Hello");
Hello.onclick = readWrd(path + "Hello.mp3");
return false;
}
function readWrd(String audioSrc) {
var wrd = new Audio(audioSrc);
wrd.play();
}
</script>
<!--and later in make link or sth-->
<a id="Hello" href="#">Hello</a>
<!--leave the 'href' empty if you want the link to be destroyed after you click it-->
</body>
</html>
All you need to do is add the word at the end of the link below, and then you can style it as much as you want e.g. autoplay when you click a button.
<audio controls="controls">
<source src="http://translate.google.com/translate_tts?tl=en&q=wordgoeshere" type="audio/mpeg">
</audio>

Categories

Resources