Google TTS API for Arabic, Chinese and Greek - android

I am trying to download an mp3 file from google TTS API, here is the code
try {
String path ="http://translate.google.com/translate_tts?tl=en&q=hello";
//this is the name of the local file you will create
String targetFileName = "test.mp3";
boolean eof = false;
URL u = new URL(path);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.addRequestProperty("User-Agent", "Mozilla/5.0");
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File(Environment.getExternalStorageDirectory()
+ "/download/"+targetFileName));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ( (len1 = in.read(buffer)) > 0 ) {
f.write(buffer,0, len1);
}
f.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This works fine, but when I try to make the request for languages like chinese or greek which use special characters
String path ="http://translate.google.com/translate_tts?tl=zh-TW&q=你好";
The mp3 file I get back has no sound but from the size of the file I can tell it has data in it. When I try the same with Arabic
String path ="http://translate.google.com/translate_tts?tl=ar&q=%D8%A7%D9%84%D9%84%D9%87";
I get back an empty mp3 file with 0 bytes.
I have tried using different user agents and nothing seems to work.
Please help.
Thank You

Use the path as a URI rather than a string then change it to an ascii string.
URI uri = new URI("http://translate.google.com/translate_tts?tl=zh-TW&q=你好");
URL u = new URL(uri.toASCIIString());

I have your same problem. But I have solve it yesterday.
I wanna the API say Chinese and save to mp3 file .
The url now is:
path ="http://translate.google.com/translate_tts?tl=zh-TW&q=你好"
you do as follow:
path ="http://translate.google.com/translate_tts?ie=UTF-8&tl=zh-TW&q=".urlencode("你好");
Add a param ie=utf-8 AND encode the Chinese words.
You'll got what you want .

and if the app crashes try this
txtToTranslate = txtToTranslate.replace(" ", "%20");
it replaces the spaces between the words.

Related

Downloaded image shows in computer but not in mobiles folder

I am working on an image wallpaper application in android when i download the image from url sometime it shows images on mobile but most of time it does't show but when i connect my mobile to computer its right in the specified folder.
Thanks advance looking forward for answer.
Here is my code to download image.
protected Void doInBackground(Void... arg0) {
FileOutputStream fileOutput = null;
try {
// set the path where we want to save the file
// in this case, going to save it on the root directory of the
// sd card.
File dir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
String filename = _imagePaths[FullScreenImage.position]
.substring(_imagePaths[FullScreenImage.position]
.lastIndexOf("/"));
if (!dir.exists())
dir.mkdirs();
File file = new File(dir, filename);
Log.i("Local filename:", "" + filename);
// this will be used to write the downloaded data into the file
// we created
fileOutput = new FileOutputStream(file);
Bitmap mybitmap = imageLoader.getBitmap(
_imagePaths[FullScreenImage.position], 800, 480);
mybitmap.compress(CompressFormat.JPEG, 100, fileOutput);
// close the output stream when done
// catch some possible errors...
} catch (IOException e) {
Log.e("Download Image catch > ", e.getMessage());
} finally {
if (fileOutput != null) {
try {
fileOutput.flush();
fileOutput.close();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("Download Image catch > ", e.getMessage());
}
}
}
return null;
}
Use MediaScannerConnection.scanFile() to notify the system about new media files.

Setting Google Glass Card image with file URI fails

I'm having issues using the Cards from the recently released GDK. Basically, Card.addImage() can only take two arguments, a resource id or a URI.
For my use case, I need to open an image that exists as a file not directly as a resource. So for testing purposes I'm including the images in the assets folder. Trying to access them directly from the asset folder fails, so I'm copying them from there to internal storage. Once they're copied, I generate a URI from the file and assign it to the card. The resulting card shows a grey block where the image should be.
String fileName = step.attachment; //of the form, "folder1/images/image1.jpg"
File outFile = new File(getFilesDir()+File.separator+fileName);
FileChannel inputChannel = null;
FileChannel outputChannel = null;
try {
//check to see if the file has already been cached in internal storage before copying
if(!outFile.exists()) {
FileInputStream inputStream = new FileInputStream(getAssets().openFd(fileName).getFileDescriptor());
FileOutputStream outputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
inputChannel = inputStream.getChannel();
outputChannel = outputStream.getChannel();
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
if(inputChannel!=null)
inputChannel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(outputChannel!=null)
outputChannel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
card.addImage(Uri.fromFile(outFile));
It's hard to diagnose because I have no clue what the Card is doing internally.
Instead of writing
new FileInputStream(getAssets().openFd(fileName).getFileDescriptor());
can you try
getAssets().openFd(fileName).createInputStream();
and see if it works?
To answer your original question, the addImage method supports resource: and file: URIs.
This is very strange, but I managed to solve my problem. I replaced the file copy code with the following and it appears to have solved my issues
InputStream in = null;
OutputStream out = null;
try {
in = getAssets().open(step.attachment);
out = new FileOutputStream(outFile);
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + step.attachment, e);
}
It's not clear to me why/how I was copying my entire apk, but I'm guessing it's the call to
getAssets().openFd(fileName).getFileDescriptor()
Perhaps it was returning the file descriptor of the apk. It's odd because I've seen some claim that the previous method works.

Saving a file to the external temp dir from R.raw.some_file.m4a

I need to be able to save a file to the external storgage temp dir. The file I am saving though is the R.raw directory of my app.
I have used this example here.
Move Raw file to SD card in Android
The issue is
1. The app seems to read the .m4a file I want (possible reads the bytes wrong here).
2. When the file is saved to the /tmp dir the file size is totally wrong.
eg one file goes from 30kb to 300kb, another goes from 25kb, to .25kb.
Any suggestions
public String saveAs(int ressound, String whipName){
byte[] buffer=null;
InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
int size=0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.i("saveas", "did not save1");
//return false;
}
String path= Environment.getExternalStorageDirectory().getAbsolutePath()+"/tmp/.pw2";
String filename="/"+whipName+".m4a";
Log.i("path", "file path is " + path);
boolean exists = (new File(path)).exists();
if (!exists){new File(path).mkdirs();}
FileOutputStream save;
try {
save = new FileOutputStream(path+filename);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Log.i("saveas", "did not save2");
//return false;
} catch (IOException e) {
// TODO Auto-generated catch block
Log.i("saveas", "did not save3");
//return false;
}
File k = new File(path, filename);
return k.getAbsolutePath();
}
You CAN read a file in one full buffer like you're doing, but this is generally bad practice, unless you know the files are small, and the InputStream will know the full size in advance and be able to load all data at once.
If you aren't absolutely sure of max file size, especially on mobile, don't try to load the full thing in memory.
See IOUtils code for the classic example:
http://grepcode.com/file/repo1.maven.org/maven2/commons-io/commons-io/1.4/org/apache/commons/io/IOUtils.java#IOUtils.copyLarge%28java.io.InputStream%2Cjava.io.OutputStream%29
public static long copyLarge(InputStream input, OutputStream output)
throws IOException {
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
long count = 0;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
Also, make sure to close your buffers explicitly.

Download a PDF file in via Web Browser, in Android ICS

I need to display a PDF document inside the mobile browsers, without asking if the user wants to download it. Using Safari (iOs) I can do it perfectly, but when I try to do the same thing using the Android's (version ICS) native browser (called "Internet") the file is downloaded, and even the download doesn't seem to work.. After the download is done, the file is shown as Download unsuccessful, and I can't open it using a PDF file reader.
The same link download works fine is all others browsers whos not mobile.
I believe the problem is in some of the headers that I need to add to the response.
I'm setting the Content-Type as application/pdf and the Content-Disposition as inline;filename="report.PDF"
Is there anyone who had the same problem?
Anyone who knows a solution? :)
Thanks!
Lucas
The android browser does not have a default built in PDF support so this cannot be easily done with that.
However here are two things you could do.
1) Download and install adobe reader from the play store and then try the following code
First you create a file on the device memory and then you read the pdf data into it.
"theurl" is the url of where the pdf is located
InputStream in = null;
File dst = new File(Environment.getExternalStorageDirectory()+"/myPDF.pdf");
try {
in = theurl.openStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OutputStream out = null;
try {
out = new FileOutputStream(dst);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
}
// Transfer bytes from in to out
try {
byte[] buf = new byte[100000];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent intent = new Intent();
Uri path = Uri.fromFile(dst);
intent.setDataAndType(path, "application/pdf");
startActivity(intent);
This will download the pdf, create it in your device memory and then the intent will open it on through your application using adove reader on your device.
Another option is
2) Go to http://jaspreetchahal.org/android-how-to-open-pdf-file-within-the-browser/ and see how that guy did it

Downloading an audio file from raw folder to SD card

I need to download a file from an application. I have 5 audio files in a raw folder. On the onclick event of a button I need to select one audio file from 5 files and download it to an SD card.
How can I acheive this?
this is so simple but mistakefull ... try this code :
File directoryTest = new File(
Environment.getExternalStorageDirectory(), "raw2sd");
try {
//coping sound file to sd
//defining specific directory
File soundDir = new File(directoryTest, "ORG");
//making directories
soundDir.mkdirs();
FileOutputStream sound = new FileOutputStream(
soundDir.getPath() + "/soundName.mp3");
InputStream is = getResources().openRawResource(R.raw.soundFile);
int a = is.available();
byte[] buf = new byte[a];
is.read(buf, 0, a);
sound.write(buf);
sound.flush();
sound.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
this is 100% tested.

Categories

Resources