Actionscript Text To Speech

Ever wanted to add text to speech functionality to your Actionscript project?
Well now you can thanks to this cool little as3 class I wrote last night.

So how does it work?
Google hasn’t released an official API for their text to speech engine, however if you query: http://translate.google.com/translate_tts?tl=en&q=this%20is%20a%20test an mp3 will be produced which speaks whatever q equals. There is however a limit to how many characters will be accepted in one query. TextToSpeech.as gets around this limitation by splitting your request up into smaller more manageable parts and then requests them one at a time. TextToSpeech.as also fixes the delay between clips on playback by starting playback of the next segment just before the current one finishes.

Get Adobe Flash player

TextToSpeech.as simply bridges the gap between the Google text to speech engine and your as3 project. The example below imports TextToSpeech.as, loads a string (the first paragraph of this blog) and then plays it once the first segment has been converted and downloaded.

?View Code ACTIONSCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
import ps.GText2Speech.TextToSpeech;
import ps.GTranslate.Language;
 
textToSpeech = new TextToSpeech();
textToSpeech.Lang = Language.ENGLISH;
textToSpeech.addEventListener("FirstClipLoaded", beginPlaying);
textToSpeech.load('Ever wanted to add text to speech functionality to your Actionscript project? Well now you can thanks to Google and this awesome little as3 class I’ve written.');
 
function beginPlaying(event:Event):void
{
   textToSpeech.play();
}

Because TextToSpeech.as relies on the Google TextToSpeech engine it does mean that this could stop working in the future if Google decides to change or remove the URL. I guess the best way would be to actually do everything within actionscript, however this is easier said than done, so for the time being this is the best option we have.

You can download the source and example files here.

If anyone has additional feature requests please post them below.
Enjoy!

——————————————————
Update – Leading on from this post I’ve added a TextToSpeech accessibility class: Read More

——————————————————
Update – Seems to be a problem with the request within IE, not to sure what the problem is as I’m on a mac. I guess if you want to use this for a project it’d probably be a good idea to use a proxy on the same domain as your flash content.

50 Comments

  1. Nice ! Thx for your class.

  2. This is really nice… a feature I think would be cool is caching. Maybe something that runs the entire spectrum of the application and can be included in its assest or on the http domain of the application.

    Rock on

  3. There is no sound in Internet Explorer 8

  4. Hi,

    I’m getting error like this,

    Error #2044: Unhandled IOErrorEvent:. text=Error #2032: Stream Error.
    at net.peteshand::TextToSpeech/loadSpeech()
    at net.peteshand::TextToSpeech/load()
    at main()

    Thanks,
    -Sasi

  5. Hi,
    This don’t work in Opera and IE for me
    Error #2044: Unhandled IOErrorEvent:. text=Error #2032: Stream Error.
    at net.peteshand::TextToSpeech/loadSpeech()
    at net.peteshand::TextToSpeech/load()
    at main()

  6. yeah I been told about this… just don’t have time to look into it right now…
    If you or anyone for that matter fixes it let me know.

  7. Hi

    I was hoping to try out this code but when I try to run the downloaded file I get an error opening the .fla in Flash CS4 – “Unexpected file format”. Perhaps you wrote it in Flash CS5 ? If you did is it possible to save it as a CS4 file and include a download of the CS4 file. Thanks.

    Paul

  8. Hi Paul
    Yeah they were saved for CS5, I’ve saved them down to CS4 and re-uploaded.

  9. Hi Pete

    Thank you VERY much for taking time to save in CS4 on my behalf – although I am pretty sure there are others out there equally appreciative.

    I ran it but got a few errors which I will now try to resolve.

    I am looking for something which will turn text to speech and run on a mobile – hopefully without needing to access the internet and hopefully in AS 2 since only Flashlite 4 will run AS 3 and its not available on any mobiles yet.

    So thats a pretty tall order.

    I appreciate access to your work !

    Regards

    Paul

  10. This is very cool but I have a problem using it.

    I am trying to use it speak a Japanese sentence. I’ve got it all set up correctly and speaking but have an issue. What I get is if I give it romaji (ex. konnichiwa), it will just speak the letters. If I give it hiragana (ex. こんにちは) I don’t get any speech.

    I’m assuming the speech engine requires Japanese characters (katakana, hiragana and kanji) but I’m guessing the class has an issue with unicode. I cannot figure out any other reason.

    Any help would be greatly appreciated, I want this sorted asap so I can release.

    If I can find your email I will email you as well, just cause you will find this message otherwise.

    Thanks a lot for the class though. If I can get it working it will immensely help with this project I am working on.

  11. Just a lead on from my last comment.

    I have done some testing and still don’t know where the issue is but I have discovered a couple of things.

    I have been working with the following string “はがき hagaki” The first part of the string just is hagaki written in hiragana. What I hear from this is ” H A G A K I”, the spaces at the start just mean silence followed by each letter being spoken individually.

    Using trace I have discovered query which gets created is: http://translate.google.com/translate_tts?tl=ja&q=はがき hagaki

    Putting that into a browser will allow you to hear “hagaki H A G A K I”. This confirms my earlier assumption that it cannot support romaji (Japanese written with English letters), the other thing it shows is that it can read the first part of my string correctly.

    So I have no idea where the error is. Google is giving what it should and the URL your class creates is correctly, so that leaves the only place for error being the playing of the mp3 … which makes no sense to me.

    … I am now a bit confused. I will investigate further and post here if I can solve the issue.

  12. Hi there

    You may be right, it might have something to do with the encoding of the characters.
    Although looking into it, it may also simply be that google is yet to add support for this.

    it you type http://translate.google.com/translate_tts?tl=ja&q=こんにちは directly into your browser, it will speak in japanese, however if you change the tl to en, eg: http://translate.google.com/translate_tts?tl=en&q=こんにちは a blank audio file is returned.

    Hope this helps… well probably not, but it may save you a bit of time…

  13. Thanks for your quick reply. I have managed to make a partial fix, only partial because of Internet Explorer.

    The problem lies in the URL, I don’t understand the reason but it doesn’t work. The fix is simple, in the file TextToSpeech.as find the function loadspeech(). The first line should read:
    var url:String = ‘http://translate.google.com/translate_tts?tl=’ + Lang + ‘&q=’ + queries[index];

    Change that to:

    var url:String = ‘http://translate.google.com/translate_tts?tl=’ + Lang + ‘&q=’ + encodeURIComponent(queries[index]);

    What this does is simple changes special characters into escape characters.

    Example:
    Original: http://translate.google.com/translate_tts?tl=ja&q=はがき hagaki
    Fix: http://translate.google.com/translate_tts?tl=ja&q=%E3%81%AF%E3%81%8C%E3%81%8D%20hagaki

    This works in both Google Chrome and Firefox but not IE.

  14. Hi,

    When I open this app in IE or Chrome, it isn’t work, how can I fix it?

  15. Hi there

    yep there is a Security Error

    “SecurityError: Error #2000: No active security context.”

    You may be able to get around this by playing around with line 114 in gTTS.TextToSpeech and adding a context…

    Or another way around it would be to use a server side proxy which is located on the same domain as your application.
    If i had the time I’d look into myself, but sadly I’m pretty flat out these days.

    If you have any luck it’d be great to hear what you’ve done to get around the issue.

  16. just tried adding a SoundLoaderContext, however it doesn’t work because its on a different domain without a crossdomain xml… so looks like a proxy is the way to go

  17. Hi Pete!

    Can i change the voice to man?

  18. unfortunately doesn’t look like you can do this right now.
    Some languages have a male voice, other a female voice, however this may change in the future.

  19. to solve the browser issue i tried to use the suggested proxy fix:
    var url:String = ‘http://petzooba.com/proxy.php?url=’+encodeURIComponent(‘http://translate.google.com/translate_tts?tl=’ + Lang + ‘&q=’ + queries[index]);

    i even tried it with an audio mime type:
    var url:String = ‘http://petzooba.com/proxy.php?url=’+encodeURIComponent(‘http://translate.google.com/translate_tts?tl=’ + Lang + ‘&q=’ + queries[index]) + &mimeType=audio/basic

    now none of the browsers work whereas before (without proxy) only Firefox works. any other ideas? or am i doing this wrong?

  20. supplemental: IE8 only works after a long load time, that is, load the page without changing the text, go eat your dinner, come back and hit “speak”. weird.

  21. definitive browser fix:
    var url:String = ‘http://domain.com/proxy.php?url=http://translate.google.com/translate_tts%3Ftl=’ + Lang + ‘%26q=’ + encodeURIComponent(queries[index]);

    AND:
    find ‘val += ” “;’
    and change to ‘val += “+”;’

    there ya go! (took me a whole day of deductive fiddling)

  22. awesome, nice work!

  23. there seems to be a conflict between the browser fix and the correct pronunciation of special characters (accents …). both will not work at the same time.

  24. i’ve narrowed the problem to this: in the php proxy if i say $url = header(‘Location: ‘.$url);, then it works perfectly but only in Firefox. otherwise it works in all browsers but again, the gibberish on the special characters…
    perhaps the incorporation of the above line defeats the purpose of the proxy…
    in the file i also tried fiddling with the urldecode function and putting a header for content-type on top of the page but no luck so far. any thoughts on the matter?

  25. hmmm would you be able to post the proxy file so i can have a look?

  26. or better yet, just paste the code that is contained within the proxy

  27. also, in the TextToSpeech.as file, the query function should have the line ‘val += “%2B”;’ so when using the urldecode function in the proxy, it properly decodes that as a ‘+’

  28. i tried pasting the code. the post came up blank

  29. Could I have a copy of the proxy.php file as well please?
    I am losing my head around…
    thank you very much,

  30. No problem, I’ve updated the above zip file to include the proxy

  31. uhm… i tried
    var url:String = ‘http://test.domain.com/proxy/proxy.php?url=http://translate.google.com/translate_tts%3Ftl=’ + Lang + ‘%26q=’ + encodeURIComponent(queries[index]);

    but it doesn’t work, please any advice?

    thanx

  32. Does anyone knows what’s the file type? mp3 or wav?

  33. Thanks for a great set of code snippets.
    Is there any way to change the voice to male?

  34. Hello,

    I made small adobe air app for vocabulary learning and one of the functionality is voice pronunciation via google tts (translate.google.com/translate_tts) and also downloading mp3 and creating wav files containing word+pause+translation.

    Unfortunately, google made some restriction, that if it’s used too much, sound is not produced and screen with captcha is displayed instead to verify that it’s human, who want to use this service. This is not good for my application of course because voice pronunciation works on one button click with no browser involved.

    I’m using it via proxy file and it worked fine for one year. Now I would need to get mp3 files without proxy, directly as it would be via browser.

    Please, is there any way, how to do that?

    Thanks a lot

  35. not to sure dude, i guess because its not a public api there is no guaranty that its going to work.

  36. Doesn’t look like it. some languages are male, others are female.

  37. Thanks for this BRILLIANT piece of work but is there any way to get it to wok in AIR for Android on Flash CS5.5

    Thanks

    Paul

  38. Hey Paul

    There shouldn’t be any reason why it wouldn’t work… but yeah i haven’t tested on Android.. maybe there are security errors. probably the best thing to try is running your application on your android with the debug environment running (This can be found in flash cs5 through the following tool bars: “Debug” > “Begin Remote Debug Session” > “Actionscript 3.0″), this should give you feedback on why its not working, then post back here with the results.

  39. Hi Pete.

    Thanks for your promt reply. I will try the debug as you suggested and then post what I find. There appear to be many others asking the same question so hopefully I can help.

    Paul

  40. Pete

    I am new at this debug thing.

    I get the followng message;

    Error #2044: Unhandled IOErrorEvent:. text=Error #2032: Stream Error.
    at ps.GText2Speech::TextToSpeech/loadSpeech()[C:\Flash AS3\Text to Speech\March 2012\working\TextToSpeech\ps\GText2Speech\TextToSpeech.as:114]
    at ps.GText2Speech::TextToSpeech/load()[C:\Flash AS3\Text to Speech\March 2012\working\TextToSpeech\ps\GText2Speech\TextToSpeech.as:94]
    at main()[C:\Flash AS3\Text to Speech\March 2012\working\TextToSpeech\main.as:28]
    at runtime::ContentPlayer/loadInitialContent()
    at runtime::ContentPlayer/playRawContent()
    at runtime::ContentPlayer/playContent()
    at runtime::AppRunner/run()
    at ADLAppEntry/run()
    at global/runtime::ADLEntry()

    I will have to study this in relation to your code to see if it points me to where the problem is.

    Paul

  41. Hi Pete

    It runs in the emulator and even loads onto the device but the text is not read. If you have Flash CS5.5 just try running it using the AIR for Android publishing setting.

    Thanks

    Paul

  42. Hmmm, I’m a bit flat out with work right now, but I’ll try have a look at this on the weekend

  43. Hi Pete

    I can succesfully install it to my Samsung Galaxy S2 and it runs but the text is not voiced. I have confirmed that I have requested internet access in my permissions. So not sure what is going on. I will also try to figure it out.
    Thanks

    Paul

  44. Thanks Eugene. I am sure you have the answer but where do I place that line of code ?

    Thanks

    Paul

Trackbacks/Pingbacks

  1. TextToSpeech Accessibility made easy | Pete Shand - [...] recently posted a TextToSpeech as3 interface class which you can view here. Basically you pass it a string and …
  2. TextToSpeech Accessibility made easy 2 | Pete Shand - [...] recently posted a TextToSpeech as3 interface class which you can view here. Basically you pass it a string and …
  3. Text to Speech Fun « BobTheCoolGuy - [...] Also cool is the Google Translate text to speech webservice, which can be used to retrieve an mp3 file …
  4. Text to Speech com ActionScript 3 | 100loop.com - [...] minha pesquisa encontrei uma biblioteca em ActionScript 3.0 criada por Pete Shand (http://peteshand.net/blog/index.php/actionscript-text-to-speech/). Ficou muito simples de utilizar, por …

Submit a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Get Adobe Flash player