I am trying to make a wifi p2p video chat application.I can establish a wifi-p2p connection and I made a simple wifi p2p text chat application. How to capture the video , send and receive it?
I have tried the following code.
When I try to run this , it always gives some exception such as :illegalstateexception mediarecorder.start() or java.net.UnknownHostException
Sender Thread:
public class SendVideoThread implements Runnable{
public void run(){
try {
if(SERVERIP!=null){
handler.post(new Runnable() {
#Override
public void run() {
}
});
serverSocket = new ServerSocket(SERVERPORT);
while(true) {
//listen for incoming clients
Socket client = serverSocket.accept();
handler.post(new Runnable(){
#Override
public void run(){
}
});
try{
final ParcelFileDescriptor pfd = ParcelFileDescriptor.fromSocket(client);
handler.post(new Runnable(){
#Override
public void run(){
recorder = new MediaRecorder();
recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setOutputFile(pfd.getFileDescriptor());
recorder.setVideoFrameRate(20);
recorder.setVideoSize(176,144);
recorder.setVideoEncoder(MediaRecorder.VideoEncoder.H263);
//recorder.setPreviewDisplay(mHolder.getSurface());
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
recorder.start();
}
});
} catch (Exception e) {
handler.post(new Runnable(){
#Override
public void run(){
}
});
e.printStackTrace();
}
}
} else {
handler.post(new Runnable() {
#Override
public void run(){
}
});
}
} catch (Exception e){
handler.post(new Runnable() {
#Override
public void run() {
}
});
e.printStackTrace();
}
}
}
Receiver Thread:
public class ReceiveVideoThread implements Runnable{
#Override
public void run() {
try {
clientSocket = new Socket(Data.socket.getInetAddress(),SERVERPORT);
handler.post(new Runnable() {
#Override
public void run() {
}
});
handler.post(new Runnable() {
#Override
public void run() {
try {
ParcelFileDescriptor pfd = ParcelFileDescriptor.fromSocket(clientSocket);
pfd.getFileDescriptor().sync();
mp.setDataSource(pfd.getFileDescriptor());
pfd.close();
mp.setDisplay(mHolder);
mp.prepareAsync();
mp.start();
} catch (IOException e) {
e.printStackTrace();
}
}
});
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Related
I write this function to get video time . This functions works fine but when I backpress then it throws exception .
public void videoTimer ()
{
try
{
running = true;
final int duration = mVideoView.getDuration();
thread = new Thread(new Runnable()
{
public void run()
{
do
{
tvVideoTimer.post(new Runnable()
{
public void run()
{
int time = (duration - mVideoView.getCurrentPosition()) / 1000;
tvVideoTimer.setText(getTimeString(mVideoView.getCurrentPosition()));
}
});
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
if (!running) break;
}
while (mVideoView.getCurrentPosition() <= duration);
}
});
thread.start();
}
catch (Exception e)
{
e.printStackTrace();
}
}
Am trying to play a .wav file using media-player. Actually, I had done so far shown below. It's playing an updating the progress correctly but the problem media player is not seeking completely. Media-player stops giving out progress before the total duration of the file and stops updating progress. I have also implemented OnComplete listener also am not getting the callback. Here is my code can anyone spot me with where am missing.
public void playAudioFile() {
try {
mMediaPlayer.reset();
setMediaPlayerSource();
mMediaPlayer.prepare();
mMediaPlayer.start();
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
Graphbar.setProgress(mMediaPlayer.getDuration());
}
});
bPlay.setBackgroundResource(R.drawable.pause_selector);
new Thread(new Runnable() {
#Override
public void run() {
System.out.println("Playing");
updateProgressBar();
}
}).start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void updateProgressBar() {
Graphbar.setProgress(0);
Graphbar.setMax(mMediaPlayer.getDuration());
mHandler.postDelayed(mUpdateTimeTask, 0);
}
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
if(mMediaPlayer.isPlaying()){
long totalDuration = Graphbar.getMax();
long currentDuration =mMediaPlayer.getCurrentPosition();
String TotalDur = Utilities.milliSecondsToTimer(totalDuration);
tvTimeRight.setText(TotalDur);
tvTimeLeft.setText(""+ Utilities.milliSecondsToTimer(currentDuration));
System.out.println(currentDuration+"/"+totalDuration);
Graphbar.setProgress((int)currentDuration);
mHandler.postDelayed(this, 1);
}
}
};
private void setMediaPlayerSource() {
String audioFile = getFilename();
try {
mMediaPlayer.setDataSource(audioFile);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
for total duration use mediaplayer.getduration. Remove unnecessary code from the runnable handler , because it will create load to ur seek bar . Because at every second u are calculating something and updating layout based on that calculation .
I would suggest you to use chronometer view of android.
public void playAudioFile() {
try {
mMediaPlayer.reset();
setMediaPlayerSource();
mMediaPlayer.prepare();
mMediaPlayer.start();
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
Graphbar.setProgress(mMediaPlayer.getDuration());
}
});
bPlay.setBackgroundResource(R.drawable.pause_selector);
//set this only for once , because for one song total duration is always constant.
updateProgressBar();
}
public void updateProgressBar() {
Graphbar.setProgress(0);
Graphbar.setMax(mMediaPlayer.getDuration());
mHandler.postDelayed(mUpdateTimeTask, 0);
long totalDuration = mMediaPlayer.getDuration();
String TotalDur = Utilities.milliSecondsToTimer(totalDuration);
tvTimeRight.setText(TotalDur);
}
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
if(mMediaPlayer.isPlaying()){
//long totalDuration = mMediaPlayer.getDuration();=> no need of calculating total time and updating it to seekbar at every second
long currentDuration =mMediaPlayer.getCurrentPosition();
tvTimeLeft.setText(""+ Utilities.milliSecondsToTimer(currentDuration));
System.out.println(currentDuration+"/"+totalDuration);
Graphbar.setProgress((int)currentDuration);
mHandler.postDelayed(this, 1);
}
}
};
private void setMediaPlayerSource() {
String audioFile = getFilename();
try {
mMediaPlayer.setDataSource(audioFile);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
After asking so many question about android socket programming and getting valuable answers from stackoverflow's members i could do a well working program using sockets to connect two device over wifi.
Thanks to all.
But still i am having some problem..
i have done the program in which
** Data can be sent from client and received at serverSocket**
But still i am not getting how to Send data from server which can be received at client
Code for Server Socket
private OnClickListener bt_sendListner = new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String msg=et_msg.getText().toString();
Log.d("Msg", msg);
Thread threadsendmsg = new Thread(new Threadsendmsg(msg));
threadsendmsg.start();
}
};
public class Threadsendmsg implements Runnable{
String msg;
public Threadsendmsg(String msg) {
// TODO Auto-generated constructor stub
this.msg=msg;
}
public void run() {
// TODO Auto-generated method stub
try {
Looper.prepare();
Log.d("Msg", "Inside the thread");
//connected = true;
while (true) {
try {
Log.d("Msg", "Msg to be sent");
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(serverSocket.accept().getOutputStream())), true);
// where you issue the commands
out.println("Client: "+msg);
Log.d("Msg", "Msg sent"+out.toString());
break;
} catch (final Exception e) {
handler.post(new Runnable() {
public void run() {
// TODO Auto-generated method stub
tv_chatbox.setText("S: Error= "+ e.getMessage());
Log.d("Msg", e.getMessage());
}
});
}
}
// socket.close();
// console.append("\nC: Closed.");
} catch (final Exception e) {
handler.post(new Runnable() {
public void run() {
// TODO Auto-generated method stub
tv_chatbox.setText("S: Error= "+ e.getMessage());
Log.d("Msg", e.getMessage());
// TODO Auto-generated method stub
// console.append("\nC: Error= "+ e.getMessage());
}
});
// connected = false;
}
}
}
public class ServerThread implements Runnable {
public void run() {
try {
Looper.prepare();
if (SERVERIP != null) {
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Listening on IP: " + SERVERIP);
}
});
serverSocket = new ServerSocket(SERVERPORT);
handler.post(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), serverSocket.getLocalSocketAddress().toString()
, Toast.LENGTH_LONG).show();
serverStatus.append("\n"+serverSocket.getLocalSocketAddress().toString());
}
});
Toast.makeText(getApplicationContext(), serverSocket.getLocalSocketAddress().toString()
, Toast.LENGTH_LONG).show();
serverStatus.append("\n"+serverSocket.getLocalSocketAddress().toString());
while (true) {
// listen for incoming clients
Socket client = serverSocket.accept();
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Connected.");
}
});
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
Log.d("ServerActivity", line);
final String myline=new String(line);
handler.post(new Runnable() {
public void run() {
tv_chatbox.setText("Client said:="+myline);
// do whatever you want to the front end
// this is where you can be creative
}
});
}
break;
} catch (Exception e) {
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
} else {
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Couldn't detect internet connection.");
}
});
}
} catch (final Exception e) {
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Error"+e.getMessage());
}
});
e.printStackTrace();
}
}
}
*There is no method as ServerSocket.getOutputStream() in ServerSocket class.*Which i have used client socket...
Both client and server use the same class Socket. But client creates his socket instance manually and connects to server. Server on the other hand listens at some port and when client connects, socket for server is created and returned from method accept().
In your code you can use
client.getOutputStream();
I want to call new url after My custom Music Player complete played but It do not call and send new url to my player. Help me please thank you.
public void onCompletion(MediaPlayer arg0)
{
playing = "Stopped";
new Thread(new Runnable()
{
#Override
public void run()
{
now++;
try
{
onCompleteURL = new URL(musicUrl[now]);
onCompleteURLConnection = onCompleteURL.openConnection();
onCompleteReadIn = new BufferedReader(new InputStreamReader(onCompleteURLConnection.getInputStream()));
onCompleteUrl = onCompleteReadIn.readLine();
onCompleteReadIn.close();
}
catch (Exception e)
{
e.printStackTrace();
}
waitingGetNextDataHandler1.sendEmptyMessage(0);
}
}).start();
waitingGetNextDataHandler1 = new Handler()
{
public void handleMessage(Message msg)
{
super.handleMessage(msg);
try
{
/*mMediaPlayer.reset();
sendHTTPRequest();
startPlayer();*/
mMediaPlayer.reset();
mMediaPlayer.setDataSource(onCompleteUrl);
mMediaPlayer.prepare();
mMediaPlayer.start();
playing = "Started";
running = mMediaPlayer.isPlaying();
playPauseImageButton.setBackgroundResource(R.drawable.pause_button);
}
catch (Exception e)
{
e.printStackTrace();
}
if(mMediaPlayer != null)
{
if(mMediaPlayer.isPlaying() == true)
{
playPauseImageButton.setBackgroundResource(R.drawable.pause_button);
}
else
{
playPauseImageButton.setBackgroundResource(R.drawable.play_button);
}
setValue();
}
}
};
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ThraedDemo objDemo = new ThraedDemo();
Thread objThread = new Thread() {
#Override
public void run() {
objDemo.firstMethod();
}
};
objThread.start();
}
class ThraedDemo {
private void firstMethod() {
Thread objThread = new Thread() {
#Override
public void run() {
try {
((ImageView)findViewById(R.id.ImageViewnumber)).setImageResource(nums[n]);
Thread.sleep(10000);
Log.v("Thread","1111111111111111sleep");
} catch (InterruptedException ex) {
System.out.println("interuped exception" + ex.getMessage());
}
secondMethod();
}
private void secondMethod() {
Thread objThread = new Thread() {
#Override
public void run() {
try {
((ImageView)findViewById(R.id.ImageViewResult)).setImageResource(nums[n+1]);
n++;
Thread.sleep(10000);
Log.v("Thread","22222222222 sleep");
} catch (InterruptedException ex) {
System.out.println("interuped exception" + ex.getMessage());
}
firstMethod();
}
};
objThread.start();
}
};
objThread.start();
}
}
I use the above code but it is not running.it got CalledFromWrongThreadException what is the problem inb the above code.Please give me some suggestions.Thanks in advance
I think you can't do view modifications from another thread than the UI thread, so either create handlers in the oncreate and post your thread to it, or use AsyncTask, or runOnUIThread method to send portions of code directly to the UI thread.
I edited your 2nd function code, I see your code is loop forever cause the firstMethod call secondMethod and the secondMethod call the new firstMethod to start and then loop forever. I removed it and moved the code update ImageView into the UI Thread, could you try this:
class ThraedDemo {
private void firstMethod() {
Thread objThread = new Thread() {
#Override
public void run() {
try {
runOnUiThread(new Runnable() {
public void run(){
((ImageView)findViewById(R.id.ImageViewnumber)).setImageResource(nums[n]);
}
});
Thread.sleep(10000);
Log.v("Thread","1111111111111111sleep");
} catch (InterruptedException ex) {
System.out.println("interuped exception" + ex.getMessage());
}
secondMethod();
}
};
objThread.start();
}
private void secondMethod() {
Thread objThread2 = new Thread() {
#Override
public void run() {
try {
runOnUiThread(new Runnable() {
public void run(){
((ImageView)findViewById(R.id.ImageViewnumber)).setImageResource(nums[n+1]);
}
});
n++;
Thread.sleep(10000);
Log.v("Thread","22222222222 sleep");
} catch (InterruptedException ex) {
System.out.println("interuped exception" + ex.getMessage());
}
}
};
objThread2.start();
}
}