create a crypted voip application - java

I realized a voip application encrypted with the algorithms AES and RC4 then when I execute the application and I encrypt the voice with the two algorithms it works normal but when I add the algorithm ECC it works for the first time and after it displays this error and then nothing of these algorithms works
here is some of my code that executes voice transfer and encrypted with ECC
public VOIPClientEC(String ip, int port) {
this.ip = ip;
this.port = port;
try {
client = new Socket(ip, port);
this.start();
} catch (Exception e) {
}
}
public VOIPClientEC(Socket s) {
client = s;
this.start();
}
public void run() {
try {
//long t = System.currentTimeMillis();
OutputStream o = client.getOutputStream();
DataOutputStream dos = new DataOutputStream(o);
//dos.writeLong(t);
InputStream inp = client.getInputStream();
DataInputStream dis = new DataInputStream(inp);
// long time = dis.readLong();
EllipticCurveAlgorithm algorithm = new EllipticCurveAlgorithm();
PointProccessor processor = new PointProccessor();
long pri = 1234567891;
Point pub = processor.multiply(pri, algorithm.base);
ObjectOutputStream os = new ObjectOutputStream(o);
os.writeObject(pub.getX());
os.writeObject(pub.getY());
ObjectInputStream ois = new ObjectInputStream(inp);
Object px = ois.readObject();
System.out.println(px);
Object py = ois.readObject();
System.out.println(py);
Point p = new Point((long)px, (long)py);
inp = null;
dos = null;
dis = null;
class VOIPEcouteur extends Thread {
private BufferedInputStream buffis = null;
private InputStream is = null;
private byte[] data;
private int count,
cE;
private AudioFormat audio = null;
private SourceDataLine ligneSource = null;
private AudioInputStream audiois = null;
public VOIPEcouteur() {
try {
buffis = new BufferedInputStream(client.getInputStream());
//configuration Audio
audio = confAudio();
} catch (IOException ex) {
}
}
public void run() {
data = new byte[VOIP_BUFFER];
try {
while ((count = buffis.read(data, 0, data.length)) !=
-1 && !boolStopTalking) {
is = new ByteArrayInputStream(data);
audiois = new AudioInputStream(is, audio,
data.length / audio.getFrameSize());
DataLine.Info dataLineInfo = new DataLine.Info(
SourceDataLine.class, audio);
ligneSource = (SourceDataLine) AudioSystem.getLine(
dataLineInfo);
ligneSource.open(audio);
ligneSource.start();
while ((count = audiois.read(data, 0, data.length)) !=
-1) {
if (count > 0) {
byte[] s = algorithm.decrypt(data, pri);
ligneSource.write(s, 0, s.length);
cE++;
/* if (cE == 1){
tc3 = System.currentTimeMillis()-time;
System.out.println("temp d'execution EC : "+tc3);
}*/
}
}
}
// ligneSource.flush();
ligneSource.drain();
ligneSource.stop();
ligneSource.close();
client.close();
} catch (IOException | LineUnavailableException ex) {
}
}
}
class VOIPParleur extends Thread {
private BufferedOutputStream buffos = null;
private TargetDataLine ligneCible = null;
private AudioFormat audio = null;
private byte[] data;
private int count;
public VOIPParleur() {
try {
buffos = new BufferedOutputStream(client.
getOutputStream());
audio = confAudio();
} catch (IOException ex) {
}
}
public void run() {
try {
DataLine.Info dataLineInfo = new DataLine.Info(
TargetDataLine.class, audio);
ligneCible = (TargetDataLine) AudioSystem.getLine(
dataLineInfo);
ligneCible.open(audio);
ligneCible.start();
data = new byte[VOIP_BUFFER];
boolStopTalking = false;
try {
while (!boolStopTalking) {
count = ligneCible.read(data, 0, data.length);
if (count > 0) {
byte [] s = algorithm.encrypt(data, p);
buffos.write(s, 0, data.length);
}
}
buffos.close();
ligneCible.stop();
ligneCible.close();
client.close();
} catch (Exception e) {
}
} catch (LineUnavailableException ex) {
Logger.getLogger(VOIPClientEC.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
new VOIPParleur().start();
new VOIPEcouteur().start();
} catch (IOException | ClassNotFoundException ex) {
Logger.getLogger(VOIPClientEC.class.getName()).log(Level.SEVERE, null, ex);
}
}
private AudioFormat confAudio() {
//configuration copi�e
//8000,11025,16000,22050,44100
float sampleRate = 8000.0F;
//8,16
int sampleSizeInBits = 16;
//1,2
int channels = 2;
boolean signed = true;
boolean bigEndian = false;
return new AudioFormat(sampleRate, sampleSizeInBits,
channels, signed,
bigEndian);
}
}
and that is the error
chat.VOIPClientEC$1VOIPParleur run GRAVE: null
javax.sound.sampled.LineUnavailableException: line with format
PCM_SIGNED 8000.0 Hz, 16 bit, stereo, 4 bytes/frame, little-endian not
supported. at
com.sun.media.sound.DirectAudioDevice$DirectDL.implOpen(DirectAudioDevice.java:513)
at
com.sun.media.sound.AbstractDataLine.open(AbstractDataLine.java:121)
at
com.sun.media.sound.AbstractDataLine.open(AbstractDataLine.java:153)
at chat.VOIPClientEC$1VOIPParleur.run(VOIPClient.java:759)
Exception in thread "Thread-15" java.lang.NullPointerException at
chat.VOIPClientEC$1VOIPEcouteur.run(VOIPClient.java:720)

Related

Sending a binary file over a Java Socket

I have written a multi-client TCP server that has the dual purpose of sending Json (text based) command strings and also sending an SQLite database file to multiple clients. Everything is working nicely except... the database file uses the special character hex81 (decimal 129) for some internal purpose. When I read the database file into a byte array, Java converts this character to decimal -127 because of Java's signed representation of bytes. However the socket is actually transmitting this character as hex3F. So when I receive the save the data in the client and save it to a file, the database is corrupt due to the presence of h3F chars instead of h81.
Why is this happening and how do I correct it?
Here is the complete code that I am using for the server (a new instance of this class is started by a separate TCPServer class whenever a client connects):
public class TCPServerThread extends Thread {
// Connect status constants
private final static int NULL = 0;
private final static int DISCONNECTED = 1;
private final static int DISCONNECTING = 2;
private final static int BEGIN_CONNECT = 3;
private final static int CONNECTED = 4;
private final static String END_SESSION = new Character((char)0).toString(); // Indicates the end of a session
// Connection state info
private int connectionStatus = DISCONNECTED;
private static StringBuffer txBuffer = new StringBuffer("");
private static ByteArrayOutputStream txBuffer2 = new ByteArrayOutputStream();
private static File file;
// TCP Components
private ServerSocket serverSocket = null;
private Socket clientSocket = null;
private BufferedReader in = null;
private PrintWriter out = null;
private DataOutputStream out2 = null;
private String s = "";
private DecodeJson dj = new DecodeJson();
private boolean doRun;
public TCPServerThread(Socket socket) throws IOException {
doRun = true;
clientSocket = socket;
changeStatusTS(BEGIN_CONNECT, true);
}
public void run() {
while (doRun) {
try { // run every ~10 ms
Thread.sleep(10);
}
catch (InterruptedException e) {}
if (Mainscreen.shutdown == true || TCPClient.close == true)
connectionStatus = DISCONNECTING;
switch (connectionStatus) {
case BEGIN_CONNECT:
try {
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream(), true);
out2 = new DataOutputStream(clientSocket.getOutputStream());
TCPServer.writers.add(out); // add this socket to the connected clients list
changeStatusTS(CONNECTED, true);
}
// If error, clean up and output an error message
catch (IOException e) {
cleanUp();
changeStatusTS(DISCONNECTED, false);
}
break;
case CONNECTED:
try {
// Send data
if (txBuffer.length() != 0) {
for (PrintWriter writer : TCPServer.writers) {
writer.print(txBuffer);
writer.flush();
if(writer.checkError()) {
closeSocket();
changeStatusTS(DISCONNECTING, true);
}else {
changeStatusTS(NULL, true);
}
}
txBuffer.setLength(0);
}
if (txBuffer2.size() != 0) {
byte[] result = txBuffer2.toByteArray();
System.out.println(result[745] + "," + result[746] + "," + result[747] + "," + result[748] + "," + result[749] + "," + result[750]);
out2.write(result);
out2.flush();
txBuffer2.reset();
}
// Receive data
if (in.ready()) {
s = in.readLine();
if ((s != null) && (s.length() != 0)) {
// Check if it is the end of a transmission
if (s.equals(END_SESSION)) {
changeStatusTS(DISCONNECTING, true);
}
// Otherwise, receive text
else {
dj.receiveString(s);
changeStatusTS(NULL, true);
}
}
}
}
catch (IOException e) {
System.out.println("Socket error " + e);
cleanUp();
changeStatusTS(DISCONNECTED, false);
}
break;
case DISCONNECTING:
// Tell clients to disconnect as well
if (out != null) {
out.print(END_SESSION);
out.flush();
}
// Clean up (close all streams/sockets)
cleanUp();
changeStatusTS(DISCONNECTED, true);
break;
default: break;
}
}
}
// Add command to text send-buffer
public static void sendString(String s) {
synchronized (txBuffer) {
txBuffer.append(s + "\n");
}
}
// Add file data to binary send buffer
public static void sendFile(String filename) {
synchronized (txBuffer2) {
file = new File(filename);
byte[] content = new byte[(int)file.length()];
FileInputStream fin;
try {
fin = new FileInputStream(file);
fin.read(content);
System.out.println(content[745] + "," + content[746] + "," +content[747] + "," +content[748] + "," + content[749] + "," + content[750]);
txBuffer2.write(content);
fin.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException f) {
f.printStackTrace();
}
}
}
private void changeStatusTS(int newConnectStatus, boolean noError) {
// Change state if valid state
if (newConnectStatus != NULL) {
connectionStatus = newConnectStatus;
}
}
private void closeSocket(){
try {
if (clientSocket != null) {
clientSocket.close();
clientSocket = null;
}
}
catch (IOException e) { clientSocket = null; }
}
// Cleanup for disconnect
private void cleanUp() {
try {
if (serverSocket != null) {
serverSocket.close();
serverSocket = null;
}
}
catch (IOException e) { serverSocket = null; }
try {
if (clientSocket != null) {
clientSocket.close();
clientSocket = null;
}
}
catch (IOException e) { clientSocket = null; }
try {
if (in != null) {
in.close();
in = null;
}
}
catch (IOException e) { in = null; }
if (out != null) {
TCPServer.writers.remove(out); // remove this socket for the connected sockets list
out.close();
out = null;
}
doRun = false;
}
}
So as EJP suggested, the problem is due to using readers and writers.
The following code now works as expected (thanks for the tip EJP). I will get around to addressing the issue raised by VGR about wrapping client.getOutputStream() in both a PrintWriter and a BufferedOutputStream, but for now the code works nicely (this is a work in progress).
public class TCPServerThread extends Thread {
// Connect status constants
private final static int NULL = 0;
private final static int DISCONNECTED = 1;
private final static int DISCONNECTING = 2;
private final static int BEGIN_CONNECT = 3;
private final static int CONNECTED = 4;
private final static String END_SESSION = new Character((char)0).toString(); // Indicates the end of a session
// Connection state info
private int connectionStatus = DISCONNECTED;
private static StringBuffer txBuffer = new StringBuffer("");
private static BufferedOutputStream out2 = null;
private static File file;
// TCP Components
private ServerSocket serverSocket = null;
private Socket clientSocket = null;
private BufferedReader in = null;
private PrintWriter out = null;
private static BufferedInputStream fileData = null;
private String s = "";
private DecodeJson dj = new DecodeJson();
private boolean doRun;
public TCPServerThread(Socket socket) throws IOException {
doRun = true;
clientSocket = socket;
changeStatusTS(BEGIN_CONNECT, true);
}
public void run() {
while (doRun) {
try { // run every ~10 ms
Thread.sleep(10);
}
catch (InterruptedException e) {}
if (Mainscreen.shutdown == true || TCPClient.close == true)
connectionStatus = DISCONNECTING;
switch (connectionStatus) {
case BEGIN_CONNECT:
try {
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream(), true);
out2 = new BufferedOutputStream(clientSocket.getOutputStream());
TCPServer.writers.add(out); // add this socket to the connected clients list
changeStatusTS(CONNECTED, true);
}
// If error, clean up and output an error message
catch (IOException e) {
cleanUp();
changeStatusTS(DISCONNECTED, false);
}
break;
case CONNECTED:
try {
// Send data
if (txBuffer.length() != 0) {
for (PrintWriter writer : TCPServer.writers) {
writer.print(txBuffer);
writer.flush();
if(writer.checkError()) {
closeSocket();
changeStatusTS(DISCONNECTING, true);
}else {
changeStatusTS(NULL, true);
}
}
txBuffer.setLength(0);
}
if (fileData != null) {
byte[] buffer = new byte[(int) file.length()];
for (int read = fileData.read(buffer); read >=0; read = fileData.read(buffer)) out2.write(buffer, 0, read);
out2.flush();
fileData = null;
}
// Receive data
if (in.ready()) {
s = in.readLine();
if ((s != null) && (s.length() != 0)) {
// Check if it is the end of a transmission
if (s.equals(END_SESSION)) {
changeStatusTS(DISCONNECTING, true);
}
// Otherwise, receive text
else {
dj.receiveString(s);
changeStatusTS(NULL, true);
}
}
}
}
catch (IOException e) {
System.out.println("Socket error " + e);
cleanUp();
changeStatusTS(DISCONNECTED, false);
}
break;
case DISCONNECTING:
// Tell clients to disconnect as well
if (out != null) {
out.print(END_SESSION);
out.flush();
}
// Clean up (close all streams/sockets)
cleanUp();
changeStatusTS(DISCONNECTED, true);
break;
default: break;
}
}
}
// Add command to text send-buffer
public static void sendString(String s) {
synchronized (txBuffer) {
txBuffer.append(s + "\n");
}
}
// Add file data to binary send buffer
public static void sendFile(String filename) {
file = new File(filename);
try {
fileData = new BufferedInputStream(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private void changeStatusTS(int newConnectStatus, boolean noError) {
// Change state if valid state
if (newConnectStatus != NULL) {
connectionStatus = newConnectStatus;
}
}
private void closeSocket(){
try {
if (clientSocket != null) {
clientSocket.close();
clientSocket = null;
}
}
catch (IOException e) { clientSocket = null; }
}
// Cleanup for disconnect
private void cleanUp() {
try {
if (serverSocket != null) {
serverSocket.close();
serverSocket = null;
}
}
catch (IOException e) { serverSocket = null; }
try {
if (clientSocket != null) {
clientSocket.close();
clientSocket = null;
}
}
catch (IOException e) { clientSocket = null; }
try {
if (in != null) {
in.close();
in = null;
}
}
catch (IOException e) { in = null; }
if (out != null) {
TCPServer.writers.remove(out); // remove this socket for the connected sockets list
out.close();
out = null;
}
doRun = false;
}
}

Java Voice Chat Error

I am making a voice chat program. I have two servers one for voice and one for messages. When I connect two people I get this error, Thank you in advance. I attached the client code, ClientAudio code and the Client receive code
java.io.StreamCorruptedException: invalid type code: 00
at java.io.ObjectInputStream$BlockDataInputStream.readBlockHeader(ObjectInputStream.java:2508)
at java.io.ObjectInputStream$BlockDataInputStream.refill(ObjectInputStream.java:2543)
at java.io.ObjectInputStream$BlockDataInputStream.read(ObjectInputStream.java:2702)
at java.io.ObjectInputStream.read(ObjectInputStream.java:865)
at client.chat$ClientAudioRec.run(chat.java:388)
at java.lang.Thread.run(Thread.java:745)
its calling the error on
try {
bytesRead = ((ObjectInput) i2).read(inSound, 0, inSound.length);
} catch (Exception e) {
e.printStackTrace();
}
Code
public class Client implements Runnable { // CLIENT
private String msg;
public void run() {
try {
s1 = new Socket(ipAddress, port);
s2 = new Socket(ipAddress, 1210);
o1 = new ObjectOutputStream(s1.getOutputStream());
o1.writeObject(name);
serverListModel.addElement(name);
i1 = new ObjectInputStream(s1.getInputStream());
Thread voice = new Thread(new ClientAudio());
voice.start();
while(true) {
msg = (String) i1.readObject();
String[] namePart = msg.split("-");
if(namePart[0].equals("AddName") && !namePart[1].equals(name) && !serverListModel.contains(namePart[1])) {
serverListModel.addElement(namePart[1]);
}
if(namePart[0].equals("RemoveName") && !namePart[1].equals(name)) {
serverListModel.removeElement(namePart[1]);
}
if(!msg.equals(null) && !namePart[0].equals("AddName") && !namePart[0].equals("RemoveName")) {
chatWindow.append(msg+"\n");
}
}
} catch (IOException | ClassNotFoundException e) {
chatWindow.append("Server Closed");
e.printStackTrace();
try {
s1.close();
} catch (IOException e1) {
e1.printStackTrace();
}
mainWindow(true);
}
}
}
public class ClientAudio implements Runnable { // CLIENT AUDIO
public void run() {
try {
o2 = new ObjectOutputStream(s2.getOutputStream());
System.out.println("AUDIO");
int bytesRead = 0;
byte[] soundData = new byte[1];
Thread car = new Thread(new ClientAudioRec());
car.start();
while(true) {
bytesRead = mic.read(soundData, 0, bytesRead);
if(bytesRead >= 0) {
o2.write(soundData, 0, bytesRead);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class ClientAudioRec implements Runnable { // CLIENT AUDIO REC
public void run() {
i2 = new ObjectInputStream(s2.getInputStream());
System.out.println("REC");
SourceDataLine inSpeaker = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, af);
try {
inSpeaker = (SourceDataLine)AudioSystem.getLine(info);
inSpeaker.open(af);
} catch (LineUnavailableException e1) {
System.out.println("ERROR 22");
e1.printStackTrace();
}
int bytesRead = 0;
byte[] inSound = new byte[100];
inSpeaker.start();
while(bytesRead != -1)
{
try{
bytesRead = ((ObjectInput) i2).read(inSound, 0, inSound.length);
} catch (Exception e){
e.printStackTrace();
}
if(bytesRead >= 0)
{
inSpeaker.write(inSound, 0, bytesRead);
}
}
}
}

Java Voice Server Not Working

I am trying to make a voice server and the server is throwing this error "javax.sound.sampled.LineUnavailableException: line with format PCM_SIGNED 8000.0 Hz, 8 bit, mono, 1 bytes/frame, not supported.". Here is my code, Thank you in advance
public class VoiceUser extends Thread { // CHAT USER
private ObjectOutputStream clientOutput;
public VoiceUser(Socket sv) {
try {
System.out.println("VSTART");
clientOutput = new ObjectOutputStream(sv.getOutputStream());
outputArray.add(clientOutput);
} catch (IOException e) {
System.out.println("Can't create stable connection between server and client");
}
}
public void run() {
try {
AudioFormat af = new AudioFormat(8000.0f,8,1,true,false);
DataLine.Info info = new DataLine.Info(TargetDataLine.class, af);
TargetDataLine microphone = (TargetDataLine)AudioSystem.getLine(info);
microphone.open(af);
microphone.start();
int bytesRead = 0;
byte[] soundData = new byte[1];
while(bytesRead != -1)
{
bytesRead = microphone.read(soundData, 0, soundData.length);
System.out.println(soundData.length);
if(bytesRead >= 0)
{
for(ObjectOutputStream o : outputArray) {
o.write(soundData, 0, bytesRead);
}
}
}
} catch (IOException | LineUnavailableException e) {
e.printStackTrace();
}
}
}

I am unable to record voice by using the following program with applet in java

I GOT THIS CODE FROM HERE
I am using the following program to record voice.But when i click on record voice is not recording.I am not getting any errors.What might be the problem.
//imports
//Main class
public class AudioApplet extends JApplet implements ActionListener, ChangeListener, ItemListener {
//declarations
public void init()
{
setLayout(null);
JLabel recorder = new JLabel("Recorder");
JLabel fileName = new JLabel("Please Enter File Name");
JLabel server = new JLabel("Listen From Server");
JLabel status = new JLabel("Status...");
fnametxt = new JTextField("FileName");
servercombo = new JComboBox();
statustxt = new JTextField("Check your status here...");
record = new JButton("Record");
play = new JButton("Play");
pause = new JButton("Pause");
stop = new JButton("Stop");
send = new JButton("Upload");
listen = new JButton("Listen");
save = new JButton("Save");
progress = new JSlider(0, audioLength, 0);
time = new JLabel("0:00");
mute = new JToggleButton("Mute");
vol1 = new JLabel("Volume -");
vol2 = new JLabel("+");
volslider = new JSlider(0,100);
volslider.setToolTipText("Volume");
volslider.setPaintTicks(true);
volslider.setMinorTickSpacing(10);
//properties related to size
add(recorder);
add(record);
add(play);
add(pause);
add(stop);
add(save);
add(fileName);
add(fnametxt);
add(send);
add(server);
add(servercombo);
add(listen);
add(status);
add(statustxt);
add(progress);
add(time);
add(vol1);
add(volslider);
add(vol2);
add(mute);
record.setEnabled(true);
pause.setEnabled(true);
play.setEnabled(true);
stop.setEnabled(true);
save.setEnabled(true);
send.setEnabled(true);
listen.setEnabled(true);
record.addActionListener(this);
play.addActionListener(this);
pause.addActionListener(this);
stop.addActionListener(this);
save.addActionListener(this);
send.addActionListener(this);
listen.addActionListener(this);
mute.addActionListener(this);
progress.addChangeListener(this);
volslider.addChangeListener(this);
servercombo.addItemListener(this);
}//End of init method
//***************************************************/
//******* StateChanged method for ChangeListener*****/
//***************************************************/
public void stateChanged(ChangeEvent e) {
if (e.getSource()==volslider) {
volumeControl();
}else {
int value = progress.getValue();
time.setText(value / 1000 + "." + (value % 1000) / 100);
}
}
public void itemStateChanged(ItemEvent ie) {
msg = " Listening from server [buffering]...";
statustxt.setText(msg);
listenAudio();
}
//***************************************************/
//***** ActionPerformed method for ActionListener****/
//***************************************************/
public void actionPerformed(ActionEvent e) {
if(e.getSource()==record){
msg = " Capturing audio from mic.....";
statustxt.setText(msg);
record.setEnabled(false);
pause.setEnabled(true);
stop.setEnabled(true);
play.setEnabled(false);
save.setEnabled(true);
if(paused)
{
resumeRecord();
}
else
{
recordAudio();
}
}
else if (e.getSource()==play) {
msg = " Playing recorded audio.....";
statustxt.setText(msg);
stop.setEnabled(true);
if(first)
{
playAudio();
}
else
{
resumePlay();
}
}
else if (e.getSource()==pause) {
msg = "Paused....";
statustxt.setText(msg);
record.setEnabled(true);
pause.setEnabled(true);
pauseAudio();
first=false;
}
else if (e.getSource()==stop) {
msg = " Action stopped by user.....";
statustxt.setText(msg);
progress.setValue(0);
record.setEnabled(true);
stop.setEnabled(false);
play.setEnabled(true);
running = false;
stopAudio();
}
else if (e.getSource()==save) {
msg = " Saving file to user's System....";
statustxt.setText(msg);
saveAudio();
}
else if (e.getSource()==send) {
msg = " Sending recorded file to server...";
statustxt.setText(msg);
uploadAudio();
}
else if(e.getSource()==listen){
msg = " Listening from server [buffering]...";
statustxt.setText(msg);
//code for listen audio
}
else {
muteControl();
}
}
//******************************************/
//************** Method Declarations ****/
//******************************************/
private void recordAudio() {
first=true;
try {
final AudioFileFormat.Type fileType = AudioFileFormat.Type.AU;
final AudioFormat format = getFormat();
DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
line = (TargetDataLine)AudioSystem.getLine(info);
line.open(format);
line.start();
Runnable runner = new Runnable() {
int bufferSize = (int) format.getSampleRate()* format.getFrameSize();
byte buffer[] = new byte[bufferSize];
public void run() {
out = new ByteArrayOutputStream();
running = true;
try {
while (running) {
int count = line.read(buffer, 0, buffer.length);
if (count > 0) {
out.write(buffer, 0, count);
InputStream input = new ByteArrayInputStream(buffer);
final AudioInputStream ais = new AudioInputStream(input, format, buffer.length /format.getFrameSize());
}
}
out.close();
}catch (IOException e) {
System.exit(-1);
}
}
};
Thread recordThread = new Thread(runner);
recordThread.start();
}catch(LineUnavailableException e) {
System.err.println("Line Unavailable:"+ e);
e.printStackTrace();
System.exit(-2);
}
catch (Exception e) {
System.out.println("Direct Upload Error");
e.printStackTrace();
}
}//End of RecordAudio method
private void playAudio() {
try{
byte audio[] = out.toByteArray();
InputStream input = new ByteArrayInputStream(audio);
final AudioFormat format = getFormat();
final AudioInputStream ais = new AudioInputStream(input, format, audio.length /format.getFrameSize());
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
sline = (SourceDataLine)AudioSystem.getLine(info);
sline.open(format);
sline.start();
Float audioLen = (audio.length / format.getFrameSize()) * format.getFrameRate();
Runnable runner = new Runnable() {
int bufferSize = (int) format.getSampleRate() * format.getFrameSize();
byte buffer[] = new byte[bufferSize];
public void run() {
try {
int count;
synchronized(lock){
while((count = ais.read( buffer, 0, buffer.length)) != -1) {
while(paused) {
if(sline.isRunning()) {
sline.stop();
}
try{
lock.wait();
}
catch(InterruptedException e) {
}
}
if(!sline.isRunning()) {
sline.start();
}
if(count > 0) {
sline.write(buffer, 0, count);
}
}
}
first=true;
sline.drain();
sline.close();
}catch(IOException e) {
System.err.println("I/O problems:" + e);
System.exit(-3);
}
}
};
Thread playThread = new Thread(runner);
playThread.start();
}catch(LineUnavailableException e) {
System.exit(-4);
}
}//End of PlayAudio method
private void resumeRecord(){
synchronized(lock) {
paused = false;
lock.notifyAll();
first = true;
}
}//End of ResumeRecord method
private void stopAudio() {
if (sline != null) {
sline.stop();
sline.close();
}else {
line.stop();
line.close();
}
}//End of StopAudio method
private void resumePlay(){
synchronized(lock) {
paused = false;
lock.notifyAll();
System.out.println("inside resumeplay method");
}
}//End of ResumePlay method
private void pauseAudio(){
paused = true;
}
private void saveAudio() {
Thread thread = new saveThread();
thread.start();
}
private void uploadAudio() {
Thread th= new uploadThread();
th.start();
}
private void listenAudio() {
Thread thread = new listenThread();
thread.start();
}
private AudioFormat getFormat() {
Encoding encoding = AudioFormat.Encoding.PCM_SIGNED;
float sampleRate = 44100.0F;
int sampleSizeInBits = 16;
int channels = 2;
int frameSize = 4;
float frameRate = 44100.0F;
boolean bigEndian = false;
return new AudioFormat(encoding, sampleRate, sampleSizeInBits, channels, frameSize, frameRate, bigEndian);
}//End of getAudioFormat method
class saveThread extends Thread {
public void run(){
AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE;
FileDialog fd = new FileDialog(new Frame(), "Save as WAVE", FileDialog.SAVE);
fd.setFile("*.wav");
fd.setVisible(true);
String name = fd.getDirectory() + fd.getFile();
File file = new File(name);
try{
byte audio[] = out.toByteArray();
InputStream input = new ByteArrayInputStream(audio);
final AudioFormat format = getFormat();
final AudioInputStream ais = new AudioInputStream(input, format, audio.length /format.getFrameSize());
AudioSystem.write(ais,fileType,file);
}catch (Exception e){
e.printStackTrace();
}
}
}//End of inner class saveThread
class uploadThread extends Thread{
public void run(){
AudioFileFormat.Type fileType = AudioFileFormat.Type.AU;
try{
line.flush();
line.close();
}
catch(Exception e){
e.printStackTrace();
System.err.println("Error during upload");
}
}
}//End of inner class uploadThread
class listenThread extends Thread{
public void run() {
try {
URL upload=new URL("http://localhost:8080/TapasApplet/upload");
HttpURLConnection conn = (HttpURLConnection) upload.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setDefaultUseCaches(false);
conn.setChunkedStreamingMode(1000);
conn.setRequestProperty("Content-Type", "application/octet-stream");
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String serfile = br.readLine();
while(line != null){
//un complete code here
serfile=br.readLine();
}
} catch (IOException e) {
System.err.println("Error in UserThread run() method");
e.printStackTrace();
}
}
}
public void volumeControl() {
try {
if(AudioSystem.isLineSupported(Port.Info.LINE_OUT))
{
lineIn = (Port)AudioSystem.getLine(Port.Info.LINE_OUT);
lineIn.open();
}
else if(AudioSystem.isLineSupported(Port.Info.HEADPHONE))
{
lineIn = (Port)AudioSystem.getLine(Port.Info.HEADPHONE);
lineIn.open();
}
else if(AudioSystem.isLineSupported(Port.Info.SPEAKER))
{
lineIn = (Port)AudioSystem.getLine(Port.Info.SPEAKER);
lineIn.open();
}
else
{
System.out.println("Unable to get Output Port");
return;
}
final FloatControl controlIn = (FloatControl)lineIn.getControl(FloatControl.Type.VOLUME);
final float volume = 100 * (controlIn.getValue() / controlIn.getMaximum());
System.out.println(volume);
int sliderValue=volslider.getValue();
controlIn.setValue((float)sliderValue / 100);
} catch (Exception e) {
System.out.println(" VOLUME control: exception = " + e);
}
}//End of volumeControl method
public void muteControl() {
BooleanControl mControl;
try {
mControl = (BooleanControl) sline.getControl(BooleanControl.Type.MUTE);
if (mControl.getValue() == true)
{
mControl.setValue(false);
}
else
{
mControl.setValue(true);
}
} catch (Exception e) {
System.out.println(" MUTE control: exception = " + e);
}
}
}//End of main class AudioBroadcast
Thanks in advance...

Start two threads in the same time but avoid using join after, this is for android program

i have two threads starting at the same time in my android program for downloading some packets.
ServerIP = WifiServer;
Thread thread22 = new Thread (new CallDownloader(fileToReceive, ServerIP, WifiServer, MobileServer));
thread22.start();
ServerIP = MobileServer;
Thread thread23 = new Thread (new CallDownloader(fileToReceive, ServerIP, WifiServer, MobileServer));
thread23.start();
i want to download some files from two servers at the same time.
if i use under every thread the thread.joim();
ServerIP = WifiServer;
Thread thread22 = new Thread (new CallDownloader(fileToReceive, ServerIP, WifiServer, MobileServer));
thread22.start();
thread22.join();
ServerIP = MobileServer;
Thread thread23 = new Thread (new CallDownloader(fileToReceive, ServerIP, WifiServer, MobileServer));
thread23.start();
thread23.join();
the code is not parallel but serialized. and i don't want this. I know that join is waiting to finish the first and after continue to the other.
when i take out the thread.join(); its downloading whatever it wants and not what i want to download. and is using only the first thread and it isn't going to the second.
how i can avoid the join?
because i need thread to call the connection.
if you need more details tell me to put.
here is the main code.
Queue<String> fileparts = new LinkedList<String>();
Time = SystemClock.currentThreadTimeMillis();
long Time2 = System.currentTimeMillis();
StartTime = Time2;
int intnumbOfChunks = Integer.parseInt(numbOfChunks);
intnumbOfChunks = 250;
for (int i = 0; i < intnumbOfChunks; i++) {
fileToClaim = "";
fileToClaim = "bigbang.mp4";
fileToClaim = String.format("%s.part%06d", fileToClaim, i);
fileparts.add(fileToClaim);
}
int i=0;
while (!fileparts.isEmpty()) {
fileToReceive = fileparts.peek();
ServerIP = WifiServer;
Thread thread22 = new Thread (new CallDownloader(fileToReceive, ServerIP, WifiServer, MobileServer));
thread22.start();
thread22.start();
try {
thread22.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ServerIP = MobileServer;
Thread thread23 = new Thread (new CallDownloader(fileToReceive, ServerIP, WifiServer, MobileServer));
thread23.start();
try {
thread22.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Thread thread3 = new Thread(new Join(fileToReceive));
thread3.start();
try {
thread3.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fileparts.remove();}
the downloader thread is
public class Downloader {
final String fileToReceive;
boolean fileDownloaded = false;
Socket clientSocket;
public Downloader(String fileToReceive) {
this.fileToReceive = fileToReceive;
}
public void download(String ServerIP) {
//Socket clientSocket = null;
try {
System.out.println("kanw connect me ti porta 3248");
clientSocket = new Socket(ServerIP, 3248);
System.out.println("egine i sundesi me ti porta 3248");
System.out.println("stelnw to " + fileToReceive);
BufferedWriter BuffWriter = new BufferedWriter(
new OutputStreamWriter(clientSocket.getOutputStream()));
BuffWriter.write(fileToReceive + "\n");
BuffWriter.flush();
System.out.println("esteila to " + fileToReceive);
InputStream is = clientSocket.getInputStream();
File root = Environment.getExternalStorageDirectory();
System.out.println("dimiourgo to fakelo vid ");
File dir = new File(root.getAbsolutePath() + "/vid/");
// File dir = new File (root.getAbsolutePath());
dir.mkdirs();
System.out.println("arxizw tin lipsei tou chunk");
byte[] longBytes = new byte[8];
readFully(clientSocket, longBytes);
ByteBuffer bb = ByteBuffer.wrap(longBytes);
long fileLength = bb.getLong();
System.out.println("apothikeusi arxeiou");
// save
#SuppressWarnings("resource")
FileOutputStream f = new FileOutputStream(new File(dir,
fileToReceive));
byte[] buffer = new byte[1024];
int len1 = 0;
int readBytes = 0;
while ((len1 = is.read(buffer)) > 0) {
f.write(buffer, 0, len1);
readBytes += len1;
}
if (readBytes == fileLength) {
this.fileDownloaded = true;
}
System.out.println("Receiving the file " + fileToReceive);
System.out.println("File Recieved");
} catch (IOException ex) {
System.out.println("Client stopped");
ex.printStackTrace();
} finally {
try {
if (clientSocket != null && !clientSocket.isClosed()) {
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void readFully(Socket clientSocket, byte[] buffer)
throws IOException {
System.out.println("readfully");
InputStream inputStream = clientSocket.getInputStream();
int remaining = buffer.length;
int read = 0;
while (remaining > 0) {
read = inputStream.read(buffer, buffer.length - remaining, remaining);
if (read < 0) {
throw new IOException();
}
remaining -= read;
}
System.out.println("exit");
}
public boolean IsDownloaded() {
return this.fileDownloaded;
}
}
CallDownloader class is the thread
public void run() {
System.out.println("connecting tou "+ServerIP);
Downloader d = new Downloader(fileToReceive);
//Downloader1 d1 = new Downloader1(fileToReceive);
d.download(ServerIP);
}

Categories