Implement site with text reader - javascript

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>

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.

Play a beep sound on button click

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
}
}

javascript replace code within source tag

Looking for a way to integrate two plugins so that I can have a HTML5 video player with a clickable html playlist. In order to do this, I need to alter one of the plugins so that instead of declaring:
var html = '';
html += '<video width...>'
html += '<source... /source>'
html += '<.video>'
return html
and then refilling on each click, it leaves the current contents alone, only replacing the content of the source tags. I'm trying something like:
html.replace(/'<source>'.*'</source>'/ , '<source> + myNewContent + '</source>');
return html;
I worry that my syntax for .replace() is wrong, or that replace can't handle strings like that.
As a side note, I know I'll need to re-run the function in order for it to reload with the new source, it's just that one plugin is deleting the content of the other, so I don't even have a chance.
Just select it with jquery and overwrite the source. (You could do it without jQ, but nevertheless)
var s = "newSourceString";
$(".videoClass source").html(s);
Now put the classname in your video attributes and fire away.
Just copy paste from the player documentation:
<script>
// JavaScript object for later use
var player = new MediaElementPlayer('#player',/* Options */);
// ... more code ...
player.pause();
player.setSrc('mynewfile.mp4'); /*********** this is what you want ***********/
player.play();
</script>
mediaelementjs.com
EDIT
Answer to the question:
var source = '<source>1 1bla bla bla xx uu dfhf</source>'
var startStr = source.indexOf('<source>') + 8;
var endStr = source.indexOf('</source>');
var oldSrc = source.substring(startStr, endStr);
console.log(oldSrc);
source = source.replace(oldSrc, 'new source');
console.log(source);
I believe this answers your original question.
Many thanks to Rudy for his answer, it put me on the right track, though I changed it to handle a dynamic source (his probably could too).
When you replace youtube videos in mediaelement.js you have to redeploy the plugin, so I ended up emptying the plugin container, storing all the hrefs as a data attribute in the list and then refilling the container with the appropriate html, and recalling the function at the end.
Here's the code:
HTML:
<div class="youtube-slide">
<div id="ytvideo">
<!--here's the initial video source-->
<video width="100%" height="100%" id="player1" preload="none" type="video/youtube" src="http://www.youtube.com/watch?feature=player_embedded&v=JUQXileHPQs" />
</div>
<!--the list of videos, each with a 'data-href' attribute storing a link, and the first one already activated as 'currentvideo'-->
<ul class="vidlist">
<li id="vid1" class="currentvideo" data-href="http://www.youtube.com/watch?feature=player_embedded&v=JUQXileHPQs"> <h3> "Cereus Bright"</h3> unplugged, anthemic ballad<br />recorded live in concert</li>
<li id="vid2" class data-href="http://www.youtube.com/watch?v=0RMtebCrJhY"> <h3> "Winds of Change" </h3>upbeat, funky, with upright bass<br />recorded live in studio </li>
<li id="vid3" class data-href="http://www.youtube.com/watch?v=7Ndm2o6p0A8"> <h3>"Some Strange Hold" </h3> melodic song of heartbreak <br /> recorded live (takeaway style)
</li>
</ul>
</div>
JAVASCRIPT:
<script>
//call function the first time
var player = new MediaElementPlayer('#player1');
$('ul.vidlist li').click(function() {
//clear the div of the player
$('div#ytvideo').empty();
//switch the currentvideo classes, to allow styling
$('.currentvideo').removeClass('currentvideo');
$(this).addClass('currentvideo');
//refill the player div, and call the plugin again
$('div#ytvideo').html('<video width="100%" height="100%" id="player1" preload="none" type="video/youtube" src="' + $(this).attr('data-href') +'"/>');
var player = new MediaElementPlayer('#player1');
});
</script>

Music playing continuously with name

I was actually able to make music play continuously throughout the pages without reloading, using frames (I know music playing continuously is not a good idea but the client really requested it, so I had no choice). Here is what I used for the frame with the music playing:
<body>
<div id="player">
<audio id="audio" controls="controls" autoplay="autoplay" loop="loop" style="width:150px;">
<source src="martnalia05namoracomigo.ogg" type="audio/ogg" />
<source src="martnalia05namoracomigo.mp3" type="audio/mp3" />
<embed src="martnalia05namoracomigo.mp3" hidden="true" loop="TRUE" autostart="TRUE"></embed>
</audio>
</div>
</body>
I inserted this music just to test, and I would like to know if it is possible to make a play list and if it is possible to inform the music which is currently playing with a link in it and a button to skip a music, for example:
[player]
| button previous | button to play/pause | button next
| name of the music (link to the page of the Album) |
[end of player]
Any suggestions?
You are wanting to make a small media player perhaps, if thats the case there are plenty of ready made script available to help you accomplish this. (Google is your friend).
If you do decide to go about it on your own here are my thoughts, they may help you in the right direction.
var data = [{audiourl: "filename1.mp3", artisturl:"http://example.com",name:"Song name"},
{audiourl: "filename1.mp3", artisturl:"http://example.com",name:"Song name"}];
Some sort of data structure to store the details of your tracks.
var audio = document.getElementById("audio");
audio.addEventListener('ended', playNext);
Finally some sort of function to handle the switching of tracks
var currentTrack = 0;
function playNext(options){
currentTrack++;
if (currentTrack > data.length){
currentTrack = 0;
}
var audiosrc = document.getElementById('embed_element_id') // or some other selector method
audiosrc.src = data[currentTrack].audiourl;
audiosrc.play();
}
Im not totally sure on the HTML5 audio specification but i would assume its along these lines.
Hope this helps
You're probably going to have to use a media player plugin. Try LeanBack Player:
http://leanbackplayer.com/ + http://leanbackplayer.com/player_extensions.html (XSPF Audio Playlist extension)
It's HTML5/CSS/JS with a Flash fallback option so you should be able to style it to suit your needs easily enough.

How do I fire a javascript playsound event onclick without sending the user to the top of the page?

I have the following code on a page on my site — when the user clicks on the image a sound plays:
<script language="javascript" type="text/javascript">
function playSound(soundfile) {
document.getElementById("dummy").innerHTML=
"<embed src=\""+soundfile+"\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";
}
</script>
<span id="dummy"></span>
<div id="soundimage">
<img src="image.png" />
</div>
It all works great, but the image is at the bottom of the page, and when the user clicks the image they are redirected back to the top of the page. Is there any way to get this working so that there is only an audio change, and not a visual one (if that makes sense!)?
When using a mouseover function instead, such as
<a onmouseover="playSound('sound.mp3');"><img src="image.png" /></a>
the user remains where they were on the page, but I would like them to have the option of playing the sound on click and not on rollover.
The problem is your href attribute. # as an anchor sends it to the top of the page. Use
...
Also, always include an href attribute to links.
You can (and I think is more correct in cases where Javascript support is limited), to use a link like:
...
instead of Grexis one, because if the browser you're using doesn't support Js, then the "onclick" event will never be fired and thus Js won't be read. It won't be a problem, probably, but still you should consider using better coding techniques.
instead of having the onclick event in an a tag, get rid of it and put it on the img tag. if you like the cursor for links, you can change the style too.
Example code has been indented so it actually shows in the post.
<img src="image.png" style="cursor:pointer;" onclick="playSound ('sound.mp3')" />

Categories

Resources