This repository was archived by the owner on Dec 18, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTextToSpeech.pde
More file actions
83 lines (73 loc) · 2.36 KB
/
TextToSpeech.pde
File metadata and controls
83 lines (73 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/**
* Sources for this file:
*
* https://amnonp5.wordpress.com/2011/11/26/text-to-speech/
* http://code.compartmental.net/tools/minim/
* https://stackoverflow.com/questions/35002003/how-to-use-google-translate-tts-with-the-new-v2-api
*/
import ddf.minim.*;
import java.net.*;
import java.io.*;
public class TextToSpeech {
AudioPlayer player;
Minim minim;
String sketchPath = "C:/[FILE PATH]";
public TextToSpeech(Minim minim) {
this.minim = minim;
}
void visualize() {
if (player != null) {
translate(0, 250);
for(int i = 0; i < player.left.size()-1; i++) {
line(i, 50 + player.left.get(i)*50, i+1, 50 + player.left.get(i+1)*50);
line(i, 150 + player.right.get(i)*50, i+1, 150 + player.right.get(i+1)*50);
}
}
}
void playString(String s) {
googleTTS(s, "de");
if (player != null) { player.close(); } // comment this line to layer sounds
player = minim.loadFile(sketchPath + "/" + s + ".mp3", 2048);
player.play();
}
void stopPlaying() {
if (player != null) {
player.pause();
player = null;
}
}
void googleTTS(String txt, String language) {
String u = "https://translate.google.com/translate_tts?ie=UTF-8&client=tw-ob&tl=";
u = u + language + "&q=" + txt;
u = u.replace(" ", "%20");
try {
URL url = new URL(u);
try {
URLConnection connection = url.openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; .NET CLR 1.2.30703)");
connection.connect();
InputStream is = connection.getInputStream();
String filePath= sketchPath + "/" + txt + ".mp3";
System.out.println(filePath);
File f = new File(filePath);
OutputStream out = new FileOutputStream(f);
byte buf[] = new byte[1024];
int len;
while ((len = is.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
is.close();
println("File created: " + txt + ".mp3");
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
void stop() {
player.close();
minim.stop();
}
}