Getting noise while tryin to stream song to android over tcp - java

I've made some java code which connects and sends data to my android device over LAN, at the receiver side, the app uses AudioTrack to play the audio.
It seems to be streaming the audio, but the receiver plays back only noise!
Here is my sender code:
MainActivity has the following function -
public void startStream() {
//initiate the audioTrack and play it, then start listening
try {
int minBufferSize = AudioTrack.getMinBufferSize(44100,AudioFormat.CHANNEL_OUT_STEREO,AudioFormat.ENCODING_PCM_16BIT);
audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,44100, AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT, minBufferSize, AudioTrack.MODE_STREAM);
audioTrack.play();
Streamer streamer = new Streamer(MainActivity.this);
streamer.execute();
}catch(Exception e) {
say("mainSuperException");
}
}
This is the Streamer class:
public class Streamer extends AsyncTask<Void, Void, Void> {
MainActivity mainActivity = null;
int i = 0;
Streamer(MainActivity m)
{
mainActivity = m;
}
protected Void doInBackground(Void... p) {
try {
byte[] buffer = new byte[1024];
ServerSocket serverSocket = new ServerSocket(3210);
Socket socket = serverSocket.accept();
DataInputStream input = new DataInputStream(socket.getInputStream());
i = 0;
byte[] size = new byte[4];
input.read(size,0,4);
int s = ByteBuffer.wrap(size).getInt();
//Start streaming the file
while (i<s) {
try {
input.read(buffer,0,1024);
++i;
mainActivity.audioTrack.write(buffer, 0, buffer.length);
Log.d("packetTag", "got "+i);
} catch (IOException e) {
e.printStackTrace();
mainActivity.say("InnerioException");
} catch (IllegalStateException e) {
Log.e("packetTag", e.toString());
mainActivity.say("InnerIllegalStateException");
} catch (Exception e) {
Log.e("InnerSuperException", e.toString());
e.printStackTrace();
mainActivity.say("InnerSuperException");
}
}
} catch (IOException io) {
Log.e("ioexception", io.toString());
mainActivity.say("OuterioException");
} catch (Exception e) {
Log.e("SuperException", e.toString());
e.printStackTrace();
mainActivity.say("OuterSuperException");
}
return null;
}
}
And for the sender I used the following Java code:
public class mainClassSend {
public static void main(String[] s)
{
try {
InputStream songInputStream = new FileInputStream("D:\\song.mp3");
byte[] buffer = new byte[1024];
InetAddress group = InetAddress.getByName("192.168.2.8");
Socket socket = new Socket(group,3210);
int i=0;
byte[] size = ByteBuffer.allocate(4).putInt(3359).array();
socket.getOutputStream().write(size);
//Start streaming the file
while ((songInputStream.read(buffer, 0, buffer.length)) > -1) {
try {
socket.getOutputStream().write(buffer, 0, buffer.length);
++i;
System.out.println(i);
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
songInputStream.close();
socket.close();
System.out.println(i);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Right now I'm just desperately trying to get this to work, so I've filled in all the values explicitly, even figured out the exact number of frames it sends, and sent that as the size.
It receives the size correctly, and keeps looping till that value, but all I hear is static.
I've looked all over stackOverflow, and tried looking into a lot of java class documentations, can't seem to figure out whats wrong here.

Related

android.os.NetworkOnMainThreadException but my class extends Thread

I have a client class that extends Thread to start socket programming
my class code
class MyClientMessages extends Thread {
Socket socket;
int PORT = 5002;
DataInputStream din;
DataOutputStream dout;
public MyClientMessages(String IP) {
try {
System.out.println("IP = ======= " + IP + " TYPE = " + TYPE);
//*********** crash here ***************
socket = new Socket(IP,PORT); // *********** it crash here *************
din = new DataInputStream(socket.getInputStream());
dout = new DataOutputStream(socket.getOutputStream());
this.start();
}catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
while (true) {
byte[] data = new byte[1024];
int size = 0;
try {
while ((size = din.read(data)) > 0) {
final String str = new String(data,"UTF8");
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView textView = new TextView(ServerChat.this);
textView.setTextSize(15);
textView.setText(str);
linearLayout.addView(textView);
}
});
}
}catch (IOException e) {
e.printStackTrace();
try {
dout.close();
din.close();
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
public void WriteToSocket(byte[] arr,int size) {
try {
dout.write(arr,0,size);
dout.flush();
}catch (IOException e) {
e.printStackTrace();
try {
dout.close();
din.close();
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
I make this class inside my activity class. I have another class inside my activity class for server, which extends thread and it works fine. Why does this client class crash and give me this error ?
this how I use it on my onCreate() function:
if (TYPE == 1) {
serverMessages = new MyServerMessages(5002);
Toast.makeText(this,"Room Started Wait clients To Join",Toast.LENGTH_LONG).show();
}
else {
clientMessages = new MyClientMessages(deConvert(mycode)); // crash here
Toast.makeText(this,"Connect To Room",Toast.LENGTH_LONG).show();
}
why this client class crash and give me this error ?
Because you are creating a Socket and opening it in the constructor. Move that logic into run().

Java Send custom object via socket Client, Server, LAN

I want to send object (custom class) via socket from Client to Server. This is my code:
Server:
private class SocketServerThread extends Thread {
#Override
public void run() {
try {
serverSocket = new ServerSocket(socketServerPORT);
while (true) {
clientSocket = serverSocket.accept();
ObjectInputStream inObject = new ObjectInputStream(
clientSocket.getInputStream());
try {
Te xxx = (Te) inObject.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//DataInputStream dataInputStream = new DataInputStream(
//clientSocket.getInputStream());
//messageFromClient=dataInputStream.readUTF();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
//activity.msgFromC.setText(messageFromClient);
}
});
}
}
Client:
public Client(String aIPaddres, int aPort, Te u) {
AddressIP = aIPaddres;
Port = aPort;
sendUser = u;
}
protected Void doInBackground(Void... arg0) {
Socket clientSocket = null;
try {
clientSocket = new Socket(AddressIP, Port);
ObjectOutputStream outObject = new ObjectOutputStream(
clientSocket.getOutputStream());
outObject.writeObject(sendUser);
//DataOutputStream daneWyjsciowe = new DataOutputStream(
//clientSocket.getOutputStream());
//daneWyjsciowe.writeUTF("Czesc!" );
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//response = "IOException: " + e.toString();
} finally {
if (clientSocket != null) {
try {
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
Custom class (Te.class):
public class Te implements Serializable {
public String message;
public Te(String m){
message=m;
}
}
When I passing simple data i.e. String there is no problem. But now I want to pass object, but there is always ClassNotFoundException at server. I read lot of stacks but I didnt find answer. Could U help me?

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 network client-server (file sneding), stuck in client receive loop

i tried to make a simple client-server (with some gui) the server sends the data and the client receive it (the save of the file works too) but the client seems to be stucked in the receive-loop.
I started both threads with ".start()".
I have marked the position of the problem with bold style.
My some of you have a idea why the programm in the client dont goes on... - best wishes ghali
Server:
public class Server extends Thread implements Runnable{
public File choosenfile;
public int port = 42001;
public boolean running = true;
public String myAdress = "localhost";
public ServerSocket serverSocket;
public BufferedInputStream bis;
public boolean debug = true;
public OutputStream os;
public void run() {
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(running){
Socket socket = null;
try {
System.out.println("Listening on port: "+port);
socket = serverSocket.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* Dies ist die stelle an der man einen Thread aufmachen kann
*/
// 1. File-Hülle anlegen dazu muss man deren größere wissen
if(debug) System.out.println("Server: 1.");
int count;
byte[] buffer = new byte[1024];
try {
os = socket.getOutputStream();
} catch (IOException e1) {
e1.printStackTrace();
}
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(choosenfile));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
while ((count = in.read(buffer)) > 0) {
os.write(buffer, 0, count);
os.flush();
}
} catch (IOException e1) {
e1.printStackTrace();
}
if(debug) System.out.println("Server: finish sending");
try {
os.flush();
if(debug) System.out.println("Server: close");
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
running =false;
}
}
}
Client:
public class Client extends Thread implements Runnable{
public Gui gui; //graphical surface
public boolean running = true;
public boolean debug =true;
//Networkstuff
Socket socket;
DataInputStream is;
public byte[] returnFile;
public Client(Gui gui){
this.gui = gui;
}
public void run() {
try {
socket = new Socket(InetAddress.getByName(gui.inetAdress),gui.portServer);
} catch (UnknownHostException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(gui.path);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedOutputStream out = new BufferedOutputStream(fos);
byte[] buffer = new byte[1024];
int count;
InputStream in = null;
try {
in = socket.getInputStream();
int i =0;
}
catch (IOException e1) {
e1.printStackTrace();
}
try {
while((count=in.read(buffer)) >0){
fos.write(buffer, 0, count);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
**//folloing functions are not executed anymore and i dont know why**
gui.loadPicture();
try {
fos.close();
socket.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
It's quite simple. read() blocks until
data is available in the stream, or
the stream is closed
The server sends bytes to the stream, but never closes it, so the client reading from this stream doesn't have any way to know if some more data will come or not, so it blocks.
Close the stream at server-side, or design a protocol allowing the client to know when to stop reading (like for example sending the number of bytes in the file, then sending these bytes).

Android sends UDP packets to a Java client over WiFi

I'm creating 2 programs which one of them sends UDP packets from an Adnroid device and a second one (Java) receives them. So it works good if I use WiFi-router. But if I use a direct connection the Java application doesn't receive these packets. Under the direct connection I mean creating HOTSPOT on computer and connecting to it by the Android device. I used code snippet bellow:
Server's code:
public class UDPServer {
InetAddress groupAddress;
DatagramPacket packet;
byte[] buffer;
DatagramSocket socket;
static String ip = "227.0.25.57";
static int port = 6789;
private boolean isRun = false;
private String message = "";
private int broadcastInterval;
public void StopBroadcasting(){
isRun = false;
}
public void StartBroadcasting(String message, int broadcastInterval){
isRun = true;
this.message = message;
this.broadcastInterval = broadcastInterval;
new Thread(runner).start();
}
Runnable runner = new Runnable() {
#Override
public void run() {
while(isRun){
try {
SendBroadcastMessage(message);
System.out.println("msg sended...");
Thread.sleep(broadcastInterval);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("Stopping UDPServer...");
}
};
public UDPServer() {
buffer = new byte[4096];
try {
groupAddress = InetAddress.getByName(ip);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
socket = new DatagramSocket();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void SendBroadcastMessage(String msg) throws IOException{
if(msg==null) return;
buffer = msg.getBytes();
packet = new //DatagramPacket(buffer, buffer.length);
DatagramPacket(buffer, buffer.length, groupAddress, port);
socket.send(packet);
}
public static void Send(String msg){
try {
InetAddress group = InetAddress.getByName(ip);
MulticastSocket s = new MulticastSocket(port);
s.joinGroup(group);
DatagramPacket hi = new DatagramPacket(msg.getBytes(), msg.length(),
group, port);
s.send(hi);
System.out.println("send...");
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
Client's code:
public class UDPClient {}
MulticastSocket socket;
InetAddress groupAddress;
DatagramPacket packet;
byte[] buffer;
static String ip = "227.0.25.57";
static int port = 6789;
public interface OnReceiveDataListener{
public abstract void onReceiveData(String data);
}
private OnReceiveDataListener ReceiveDataListener = null;
public void setReceiveDataListener(OnReceiveDataListener ReceiveDataListener) {
this.ReceiveDataListener = ReceiveDataListener;
}
public OnReceiveDataListener getReceiveDataListener() {
return ReceiveDataListener;
}
private boolean isRun = false;
private Thread broadcastReceiver;
public void StopBroadcasting(){
isRun = false;
if(broadcastReceiver!=null)
broadcastReceiver.interrupt();
}
public void StartBroadcasting(){
isRun = true;
broadcastReceiver = new Thread(runner);
broadcastReceiver.start();
}
Runnable runner = new Runnable() {
#Override
public void run() {
while(isRun){
try {
String msg = ReceiveBroadcastMessage();
if(ReceiveDataListener!=null)
ReceiveDataListener.onReceiveData(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
public UDPClient(){
buffer = new byte[4096];
try {
groupAddress = InetAddress.getByName(ip);
socket = new MulticastSocket(port);
socket.joinGroup(groupAddress);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public String ReceiveBroadcastMessage() throws IOException{
packet = new DatagramPacket(buffer, buffer.length);
System.out.println("before receive");
socket.receive(packet);
System.out.println(packet.getData());
return new String(packet.getData());
}
public void DeInit(){
try {
socket.leaveGroup(groupAddress);
} catch (IOException e) {
e.printStackTrace();
}
socket.close();
}
MulticastSocket msocket;
public static void Receive(){
MulticastSocket msocket;
try {
msocket = new MulticastSocket(port);
InetAddress group = InetAddress.getByName(ip);
msocket.joinGroup(group);
byte[] inbuf = new byte[1024];
DatagramPacket packet = new DatagramPacket(inbuf, inbuf.length);
System.out.println("before receive");
msocket.receive(packet);
System.out.println("after receive");
int numBytesReceived = packet.getLength();
System.out.println(new String(packet.getData()));
msocket.leaveGroup(group);
msocket.close();
System.out.println(numBytesReceived);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
If you could see I have 2 methods of sending and receiving packets. The both don't work! What do I wrong?
Help me please.
I've found solution:
http://code.google.com/p/boxeeremote/wiki/AndroidUDP

Categories