Microsoft Translate Voice limit 200-400 words when request - javascript

I have a URL of Microsoft Translate Voice to get voice look like:
<audio controls autoplay>
<source src="https://www.bing.com/tspeak?&format=audio%2Fmp3&language=en&IG=D2CBB80AA6824D9A91B0A5D1074FC4A1&IID=translator.5034.2&text=I’m Often at the End of My Rope as a Mom of Two" type="audio/mpeg">
</audio>
The problem is: text="any text here". Any text here is limit about 200-400 word. I don't know the reason at here. In Bing Translate I can insert full 5000 words and click button audio to hear.
Have any method to pass this problem? Microsoft is limit in this URL?
Have any method to insert 5000 words like Microsoft Translate homepage?

If you open your developer console on Bing's website and start playing the sound, you'll see it sends a first mp3 request with only a couple of words, and when it's done reading it, it sends another one, and so on.
You could do the same:
// When the DOM (basically the HTML) is loaded
document.addEventListener('DOMContentLoaded', function(){
// Define your DOM elements
var getAudioBtn = document.getElementById('getAudioBtn'),
langSelect = document.getElementById("langSelect"),
langSource = document.getElementById("langSource"),
audioEl = document.getElementById('audioEl');
// Setup an event listener on the button
getAudioBtn.addEventListener('click', getContentTranslate);
// Setup an listener on the audio onended event
audioEl.addEventListener('ended', readChunkQueue);
var chunkQueue = [], // Queue of chunks of text to read
wordsPerChunk = 80, // Words per chunk
language = 'en'; // Default language
function getContentTranslate() {
// Store the language
language = langSelect.value;
// Empty the chunks array
chunkQueue = [];
// Split the text into words
var words = langSource.value.split(/ /g),
tmp = []; // Temporary array for creating a chunk
while(words.length) {
// If out temporary chunk is full, add it to the list
if (tmp.length === wordsPerChunk) {
chunkQueue.push(tmp.join(' '));
tmp = [];
}
tmp.push(words.shift());
}
if (tmp.length) {
chunkQueue.push(tmp.join(' '));
}
// Start reading these chunks
readChunkQueue();
}
function readChunkQueue() {
// If the list is empty, stop
if (!chunkQueue.length) {
return;
}
// Get the first chunk in the list
var chunk = chunkQueue.shift(),
url = 'https://www.bing.com/tspeak?&format=audio%2Fmp3'
+ '&language=' + encodeURIComponent(language)
+ '&IG=D2CBB80AA6824D9A91B0A5D1074FC4A1&IID=translator.5034.2'
+ '&text=' + encodeURIComponent(chunk);
// Set the URL as source for the audio element
audioEl.setAttribute('src', url);
}
});
<select id="langSelect">
<option value="en">English</option>
<option value="vi">Vietnamese</option>
</select>
<br>
<textarea id="langSource" placeholder="Enter text or webpage URL here">Obama Inaugural Address. 20th January 2009. My fellow citizens: I stand here today humbled by the task before us, grateful for the trust you have bestowed, mindful of the sacrifices borne by our ancestors. I thank President Bush for his service to our nation, as well as the generosity and cooperation he has shown throughout this transition. Forty-four Americans have now taken the presidential oath. The words have been spoken during rising tides of prosperity and the still waters of peace. Yet, every so often the oath is taken amidst gathering clouds and raging storms. At these moments, America has carried on not simply because of the skill or vision of those in high office, but because We the People have remained faithful to the ideals of our forbearers, and true to our founding documents. So it has been. So it must be with this generation of Americans. That we are in the midst of crisis is now well understood. Our nation is at war, against a far-reaching network of violence and hatred. Our economy is badly weakened, a consequence of greed and irresponsibility on the part of some, but also our collective failure to make hard choices and prepare the nation for a new age. Homes have been lost; jobs shed; businesses shuttered. Our health care is too costly; our schools fail too many; and each day brings further evidence that the ways we use energy strengthen our adversaries and threaten our planet. These are the indicators of crisis, subject to data and statistics. Less measurable but no less profound is a sapping of confidence across our land - a nagging fear that America's decline is inevitable, and that the next generation must lower its sights. Today I say to you that the challenges we face are real. They are serious and they are many. They will not be met easily or in a short span of time. But know this, America - they will be met. On this day, we gather because we have chosen hope over fear, unity of purpose over conflict and discord. On this day, we come to proclaim an end to the petty grievances and false promises, the recriminations and worn out dogmas, that for far too long have strangled our politics. We remain a young nation, but in the words of Scripture, the time has come to set aside childish things. The time has come to reaffirm our enduring spirit; to choose our better history; to carry forward that precious gift, that noble idea, passed on from generation to generation: the God-given promise that all are equal, all are free, and all deserve a chance to pursue their full measure of happiness. In reaffirming the greatness of our nation, we understand that greatness is never a given. It must be earned. Our journey has never been one of short-cuts or settling for less. It has not been the path for the faint-hearted - for those who prefer leisure over work, or seek only the pleasures of riches and fame. Rather, it has been the risk-takers, the doers, the makers of things - some celebrated but more often men and women obscure in their labor, who have carried us up the long, rugged path towards prosperity and freedom.</textarea>
<br>
<button id="getAudioBtn">GET AUDIO</button>
<br>
<audio id="audioEl" autoplay controls></audio>

Related

How do you change the intonation or tone of a word in JavaScript for web browser speech?

Short question is, can you tell the browser to read a word in a rising tone or dropping tone?
And this may apply to some other languages or platforms too, besides JavaScript on a web browser.
I read about speech using JavaScript on a browser on this webpage.
For example, if you want the browser to pronounce "one" as in "is this the only one?" with a rising tone or intonation, how would that be done? On the other hand, if you want the browser to pronounce "one" as in "this really is the only one" with a dropping tone or intonation, how would that be done?
The following code can pronounce "one" in Google Chrome version 78.0's console:
(I have 66 voices on my computer, but maybe because it is a Mac with additional voices installed on the OS)
((() => {
var msg = new SpeechSynthesisUtterance();
var voices = window.speechSynthesis.getVoices();
console.log("How many voices", voices.length, voices);
voices.forEach(voice => {
if (voice.name === "Google US English") {
console.log(voice);
msg.voice = voice;
}
});
msg.text = "one";
speechSynthesis.speak(msg);
})());
The same applies to proper names: such as "Tainan", if you want the browser to say it with a rising tone or dropping tone, how would that be done?
Another usage is, for some proper names, you may need a hash to "special case" the pronunciation because the default pronunciation is way off or could be better (for example, special case the word "Taipei" so that if the word is in the hash's keys, then read "Tai Bei" instead, which is what native speakers would pronounce). In this case, it is even more important to create rising or dropping tone, and actually, in some languages, such as in Mandarin, I think there are 4 tones, and in Cantonese, there are 9 tones. What is a way to specify it in code?

Write the text with typing effect using javascript/Jquery

I will receive some content from server side.What I trying is to make the typing effect at the time of display this content.
$("#dislay").click(function() {
//this is the dummy content i will recieve from server
var contentFromServer = "Smile spoke total few great had never their too. Amongst moments do in arrived at my replied. Fat weddings servants but man believed prospect. Companions understood is as especially pianoforte connection introduced. Nay newspaper can sportsman are admitting gentleman belonging his. Is oppose no he summer lovers twenty in. Not his difficulty boisterous surrounded bed. Seems folly if in given scale. Sex contented dependent conveying advantage can use. Do play they miss give so up. Words to up style of since world. We leaf to snug on no need. Way own uncommonly travelling now acceptance bed compliment solicitude. Dissimilar admiration so terminated no in contrasted it. Advantages entreaties mr he apartments do. Limits far yet turned highly repair parish talked six. Draw fond rank form nor the day eat. In post mean shot ye. There out her child sir his lived. Design at uneasy me season of branch on praise esteem. Abilities discourse believing consisted remaining to no. Mistaken no me denoting dashwood as screened. Whence or esteem easily he on. Dissuade husbands at of no if disposal.";
var typerText = "";
var contentLength = contentFromServer.length;
var count = 0;
var typingSpeed = 100000 / contentLength;
var typer = setInterval(function() {
if (count > contentFromServer.length) { clearInterval(typer); }
typerText += contentFromServer.charAt(count);
document.getElementById("dislayArea").innerHTML = "" + typerText + "";
count++;
}, typingSpeed);
//reset the interval on click of button
$("#dislay").click(function() { clearInterval(typer); });
});
div {
border: 1px solid gray;
padding: 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="dislay" type="button">Display Content</button>
<div id="dislayArea"></div>
The question is I do not know if I'm using the correct way or not. That is, not sure if it would be better to use the for loop, or use setInterval(what I am using). Or there is any better approach to do this.
Using setInterval() is definitely better than loop statement, as using loop will block your JS execution and you would not be able to do something during the same time. To avoid this you may use variable speed based on string length (as you have done) but IMO this will not give good visual experience.
I will also suggest to take a look at typed.js library. (There can be other libraries that achieve the same task, but I have experience with this library and it works great!)
Using the library provides more flexible control over the task with various options and again why to reinvent the wheel ?
Here is an example snippet of typed.js:
var typed = null;
$("#dislay").click(function() {
if(typed != null)
typed.destroy();
var contentFromServer = "Smile spoke total few great had never their too. Amongst moments do in arrived at my replied. Fat weddings servants but man believed prospect. Companions understood is as especially pianoforte connection introduced. Nay newspaper can sportsman are admitting gentleman belonging his. Is oppose no he summer lovers twenty in. Not his difficulty boisterous surrounded bed. Seems folly if in given scale. Sex contented dependent conveying advantage can use. Do play they miss give so up. Words to up style of since world. We leaf to snug on no need. Way own uncommonly travelling now acceptance bed compliment solicitude. Dissimilar admiration so terminated no in contrasted it. Advantages entreaties mr he apartments do. Limits far yet turned highly repair parish talked six. Draw fond rank form nor the day eat. In post mean shot ye. There out her child sir his lived. Design at uneasy me season of branch on praise esteem. Abilities discourse believing consisted remaining to no. Mistaken no me denoting dashwood as screened. Whence or esteem easily he on. Dissuade husbands at of no if disposal.";
var typedOptions = {
strings: [contentFromServer],
typeSpeed: 60,
showCursor: false
};
typed = new Typed("#displayArea", typedOptions);
});
div {
border: 1px solid gray;
padding: 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/typed.js/2.0.8/typed.js"></script>
<button id="dislay" type="button">Display Content</button>
<div id="displayArea"></div>

Find and repalce text in javascript except in <b></b> in a string [duplicate]

This question already has answers here:
Regex replace text outside html tags
(2 answers)
Closed 7 years ago.
currently to do search and replace string in JavaScript, I am using below code:
var regEX = new RegExp(toFind,"gi");
var newString = oldString.replace(regEx,toReplace);
where OldString contains tons of HTML tags.
What I need to do is during the execution of replace function I don't want the search and replace to be done on text between <b></b> tags.
How can I do this in Js? Is there any other way of doing the replacement?
As a example please consider below string:
<div id="testDiv">
<h2>In on announcing if of comparison pianoforte projection</h2>
<p>Compliment interested discretion estimating on stimulated apartments oh. Dear so sing when in find read of call. As distrusts behaviour abilities defective is. Never at water me might. On formed merits hunted unable merely by mr whence or. Possession the unpleasing simplicity her uncommonly.</p>
<b>Kept in sent gave feel will oh it we. Has pleasure procured men laughing shutters nay. Old insipidity motionless continuing law shy partiality. Depending acuteness dependent eat use dejection. Unpleasing astonished discovered not nor shy. Morning hearted now met yet beloved evening. Has and upon his last here must.</b>
<p>New the her nor case that lady paid read. Invitation friendship travelling eat everything the out two. Shy you who scarcely expenses debating hastened resolved. Always polite moment on is warmth spirit it to hearts. Downs those still witty an balls so chief so. Moment an little remain no up lively no. Way brought may off our regular country towards adapted cheered.</p>
<p><b>Not To be Replaced</b>Am no an listening depending up believing. Enough around remove to barton agreed regret in or it. Advantage mr estimable be commanded provision. Year well shot deny shew come now had. Shall downs stand marry taken his for out. Do related mr account brandon an up. Wrong for never ready ham these witty him. Our compass see age uncivil matters weather forbade her minutes. Ready how but truth son new under.</p>
</div>
I think, this is what you are looking for:
var re = /[^<b>]*[^<\/b>]/gi;
var str = '<b>Heloo..!,</b>Mr.Its<b>too hot</b>.oops!'
var rstr = str.replace(re,'nooo');
console.log(rstr);// prints <b>nooo</b>nooo<b>nooo</b>nooo

Javascript random quote generator NO REPEAT

Please refer to www.thisyeariwantto.com This is the js code I am using to display "random" quotes... but the problem I keep having is that the quotes on the array repeat themselves. I want the user to come in click and click without ever seeing the same quote twice. How can I achieve this? Thank you in advance.
function jargonator(){
$('#head').text("This year I want to...");
$('#tag').text("");
var fragments = shuffle(
["gym","Fall in love(cliche), be happy and work abroad","stop fighting with my boyfriend","to finish things, no matter how long they take or how silly they are", "I'LL FINISH EVERY THING I START !","adopt a Koala","write a book","make a million","grow a pair","get married","drink less live more","figure out where i buried her","Give my girlfriend a real orgasm","Read more books","Save more money","Lose weight","Redecorate","Take better photos so that I can gain more instagram followers","Stop it with the #selfies","Travel","Stop cheating on my husband","Sell old unwanted stuff on eBay","Do something for charity","Get new boobs","Spend more time with kids","Spend Less time on Facebook","Totally revamp my wardrobe","Try a new hairstyle... down there ;)","Have a threesome","Get a six-pack... of premium artisanal beer","Eat less chocolate","Socialise more in real life rather than Facebook","Drink less alcohol","Eat an entire bowl of Ben & Jerrys without feeling guilty", "Start my own business","Recommend this site to all my friends","Tell Susan I have feelings for her","Stop hitting my girlfriend","Do less cocaine","Quit smoking","Get a promotion","stop saying, 'Ooh, that feels nice' whenever the security guys frisk me at airports.","work with neglected children. (my own)","balance my checkbook. (on my nose).","Learn how to use Twitter","Stop sleeping with my brother’s fiancée","Have a better relationship with my parents","do less laundry and use more deodorant","assure my lawyer that I will never again show up drunk at a custody hearing.","start shaving my legs again","Run a half or full marathon","Call people more than text","Stop texting 'LOL'","Stop sexting my cousin", "Watch less reality TV","Stop treating my cat like a real person","Stop buying every iphone that comes out","Stop sleeping with my ex","Stop faking my orgasms","go to the beach more often","get penis reduction surgery so my girl lets me fuck her in the ass","start pretending i'm gay so I can get free drinks at the rainbow room","stop lying on my resume","Exclude McDonald's from my daily diet","Stop considering ketchup a vegetable","stop pretending I have friends","Make at least one REAL friend","Learn how to spell 'thru'... 'thrugh'... 'trhouh'.... fuck it.","Get into a fight so I can finally use my mma skills","stop watching mma so my girlfriend stops thinking I'm gay","Paint my balls blue so I always have an excuse for my gf to jerk me off","Tell Rebecca to fuck off, she is such a bitch","tell my son he is adopted, and his real name is not Kyle... it is Rodrigo.","Stop being a hipster because everyone is doing it","Stop being a hipster, thats so 2013","stop taking naked pictures in snapchat","Reduce, reuse, recycle :)","Graduate!","Be happy!","Take more pictures","Learn how to twerk","stick my tongue out and not feel dirty...like Miley","ride naked on a wrecking ball...with a hammer","make my first legal pornographic movie...with a hidden camera...","learn japanese curse words","star on a rap video as one of the hoes in the back","get my freak on...it's been off way too long...and people are talking","stop showing my boobs so I get more likes","make my momma proud","stop sleeping with my boss's daughter","wear condoms more often","tell him he is not the real dad...","Have intense lesbian sex in public places.","stop making new year's resolutions.","finally dunk.","stop doing Molly","Eat the still beating Heart of Jeff Gordan","get rich doing what i like","Do the splits!","speak up","finally open my own practice","meet a girl","be more positive","Stop being an intern and get a job.","travel to where the soul meets body.","get a tattoo","be fearless","stop curating, start creating", "continue to make my boyfriend happy to the best of my ability.","leave The City and start really living","become a mermaid","Quit 'Call me maybe'","Do my Irish penpal", "Have more bacon, have more sex","study quantum physics so I can RULE THE WORLD","stop biting my nails","drink quality instead of quantity","sleep completely naked in a middle of a peaceful forest","Take a shower with Ryan Gosling","break the circle of no-life", "BOOMSHAKALAKA!!!","Break the Internet", "go back to the future","play hide & seek with strangers on the internet","file a complaint to the Karma Police","NOT fall in love","Stop making a Morgan Freeman voice when talking about Nelson Mandela's death","Make my husband allergic to viagra... i am tired!! :)","cast a worldwide campaign to protest against animal abuse","drink over 20 Mezcal shots in a row","star in the next Star Wars movie","get inspired","stop thinking 'It'll be our year... I'm the only one being the Zombie","Try and see if I can live on wine and sushi... and nothing else","Prove Einstein was wrong","Buy a hammock and work from there","forget about Teen Spirit","find the second star to the right, and go straight on till morning","Leave Narcissus alone","write a novel","make the team","go to all my AA meetings","spit in the face of convention","Somewhere I've never been yet","learn a new recipe", "Paint!", "learn to meditate and at least take one weekend for myself to travel.",]
)
$('#c').click(function () {
change(1000);
});
function change(time){
$('#tag').animate({
opacity: 0
}, time, function () {
$('#tag').html(fragments.pop()).animate({
opacity: 1
}, time)
});
}
function shuffle(o) { //v1.0
for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
change(0);
}
I really need help. If you need to see any other code of any of the other files please let me know. thank you very much.
you can just poping it from array
for( var i=0;i<fragments.length;i++){
str += fragments[i].pop();
if(i <fragments.length-1){str+=stub;}
}
if you do so, then it remove quote and you never have dublicates.
and before doing this, you can sort array random, then you will have different quotes every time
something like this.
We cannot control the value returned by Math.random() as you expecting. However try this workaround, every time a value is generated add it to another array, say mylist
var fragments =[
["quote1", "quote2", "quote3","etc", ... ]
var selected;
var temp;
var str = "";
var stub = "";
for( var i=0;i<fragments.length;i++){
temp = fragments[i][Math.floor(Math.random()*fragments[i].length)];
while(selected.contains(temp)){
temp = fragments[i][Math.floor(Math.random()*fragments[i].length)];
}
selected.push(temp);
str += temp;
if(i <fragments.length-1){str+=stub;}
}
$('#tag').animate({opacity:0.9},1000).append(str);
}
Eventually at some time all randoms get generated after that clear mylist and continue. At least random wont repeat until all elements in your fragments get selected once.

My switch statement or the document.write(); isn't working and i can't fix it

Hello I want to display a specific text each day and I don't know where is the problem in the following code, I am using jQuery mobile and I thought that javascript is the one that can do this on a web page.
<div data-role="content">
<div>
<script>
var n = new Date().getDay();
var ch = new String();
switch(n)
{
case 0:
{
ch = String("\“It is not so easy to leave your comfort zone, it is a very difficult thing to do,
but it most certainly will change your future and make you a better person than you ever could imagine\”<br><br>Today\'s challenge:<br><br>
Do you live in the future?<br><br>
Become aware of moments when you are lost in thinking about the future, whether it is 10 minutes or 2 years from now.
Notice how it pulls your attention from the present moment. See the reasons why you are running from your current experience.<br>");
}
break;
case 1:
ch = String("A dream is your creative vision for your life in the future. You must break out of your current comfort zone and become comfortable with the unfamiliar and the unknown.-Denis Waitley<br><br>
Today\'s challenge(Do one of them, or more if you like so...):<br><br>
Do everyday things differently.
Take a different route to work.
Try a new restaurant without checking Yelp first. Go vegetarian for a week, or a month.
Try a new operating system. Recalibrate your reality.
Whether the change you make is large or small, make a change in the way you do things on a day-to-day basis.
Look for the perspective that comes from any change, even if it\'s negative.
Don\'t be put off if things don\'t work out the way you planned.");
break;
case 2:
ch = String("Life begins at the end of your comfort zone. -Neale Donald Walsch<br<br>
Today\'s challenge:<br><br>
");
break;
case 3:
ch = String("The comfort zone is the great enemy to creativity; moving beyond it necessitates intuition,
which in turn configures new perspectives and conquers fears.- Dan Stevens<br><br>
Today\'s challenge:<br><br>
Trust yourself and make snap decisions. We\'re contradicting ourselves, but there\'s a good reason.
Just as there are people who thrive on snap decisions, others are more comfortable weighing all of
the possible options several times, over and over again. Sometimes making a snap call is in order,
just to get things moving. Doing so can help you kickstart your personal projects and teach you to trust your judgement.
It\'ll also show you there\'s fallout to quick decisions as well as slow ones.");
break;
case 4:
ch = String("Comedians tend to find a comfort zone and stay there and do lamer versions of themselves for the rest of their career.- Chris Rock<br><br>
Today\'s challenge:<br><br>
Take your time making decisions.
Sometimes slowing down is all it takes to make you uncomfortable—especially if speed and
quick thinking are prized in your work or personal life. Slow down,
observe what\'s going on, take your time to interpret what you see, and then intervene.
Sometimes just defending your right to make an educated decision can push you out of your comfort zone.
Think, don\'t just react.");
break;
case 5:
ch = String("I think when you get people who are really talented and you take them out of their comfort zone, you get a lot more out of them.- Gore Verbinski<br><br>
Today\'s challenge:<br><br>
Do it in small steps. It takes a lot of courage to break out of your comfort zone.
You get the same benefits whether you go in with both feet as you do if you start slow, so don\'t be afraid to start slow.
If you\'re socially anxious, don\'t assume you have to muster the courage to ask your crush on a date right away,
just say hello to them and see where you can go from there. Identify your fears, and then face them step by step.");
break;
case 6:
ch = String("When you go out of your comfort zone and it works there's nothing more satisfying.- Kristen Wiig<br><br>
Today\'s challenge:<br><br>
Be aware of attachment to objects<br><br>
Notice your attachments to objects such as a cool sweater, a new gadget or any other thing that would make you feel bad if you lost it.
What is the deep reason for being attached to them? Can you find the strength to let go of the attachment and give the object away?");
break;
}
document.write("<p>" + ch.big() + "</p>");
</script>
</div>
<form>
<label for="textarea-1">Post on Facebook:</label>
<textarea cols="40" rows="8" name="textarea-1" id="textarea-1" >
</textarea>
</form>
<input type="submit" value="Post to Facebook">
</div><!-- /content -->
Javascript treats every new line as separate statement and You are using multiline string
so use \ at each end of the line in string(..) to make it one string
I have edited and added \ in this demo fiddle
There's a couple of things. Like shadow said, you need to ensure the multiline strings are dealt with properly. Also in case 0: you don't need the curly brackets around the main clause. You have them right for the other cases.
I'm going to make a suggestion that might make it a bit easier. Hold the information you want in an array in an object:
obj = {
0: [
'day one',
'this is what\'s happened',
'we\'re separating up the text so that we keep the line lengths manageable'
],
1: [
'blah blah',
'blah blah'
]
};
Then all you have to do is:
var n = new Date().getDay();
var info = obj[n].join('');
document.write("<p>" + info.big() + "</p>");

Categories