video streaming from Android without saving on sdcard - java

I have code:
private MediaRecorder recorder;
String hostname = "192.168.1.125";
int port = 1935;
Socket socket;
ParcelFileDescriptor pfd;
public void start()
{
try {
socket = new Socket(InetAddress.getByName(hostname), port);
pfd = ParcelFileDescriptor.fromSocket(socket);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
recorder.setOutputFile(pfd.getFileDescriptor());
// String filename = String.format("/sdcard/%d.mp4", System.currentTimeMillis());
//
// recorder.setOutputFile(filename);
try
{
recorder.prepare();
recorder.start();
}
catch (IllegalStateException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
And Server side:
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args)
{
try
{
System.out.println("create sock");
ServerSocket svsock = new ServerSocket(1935);
System.out.println("accept");
Socket sock = svsock.accept();
System.out.println("buffer read");
FileOutputStream outFile = null;
String filename = String.format("%d.mp4", System.currentTimeMillis());
try {
outFile = new FileOutputStream(filename);
System.out.println(filename);
} catch (IOException e1) {
e1.printStackTrace();
}
InputStream is = new DataInputStream(sock.getInputStream());
byte[] byteBuffer = new byte[1024];
int allsize = 0;
while(sock.isConnected()) {
int size = is.read(byteBuffer);
if (size == -1){
break;
} else {
outFile.write(byteBuffer, 0, size);
}
allsize += size;
}
System.out.println("close size=" + allsize);
outFile.close();
sock.close();
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("endmain");
}
}
I test it on Android 2.2.2 (HTC quiet brilliant) and all works fine. When I press "start" button Server create file and record data from stream to file. After this file is normally play in VLC player and etc.
But when I test it on Android 4.0.4 (Galaxy S2) Server create file and record data from stream to file but not play in VLC (and other players too) and give me error
mp4 error: MP4 plugin discarded (no moov,foov,moof box)
avcodec error: Could not open �codec demux error: Specified event object handle is invalid
ps error: cannot peek
main error: no suitable demux module for `file/:///C:/1345461283455.mp4'
I also try to upload this file to youtube, but after upload youtube give me error like file format is unsupported.
But Android 4.0.4 (Galaxy S2) succesfully create and then play file when I save it on phone memory (not stream to server)
I think problem maybe on server side, or something changed on android 4.0.4.
Please, help me.
Thanks in advance.

try this
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setOutputFile(pfd.getFileDescriptor());
I think it should solve the problem. Give it a try and see if it helps ...

Related

android downloading multiple files with InputStream FileOutputStream

So I have an app which downloads certain files, dedicated to a client of mine who is hosting his files on a remote location, and i'm doing so using the code below:
public class DownloadService extends IntentService {
private int result = Activity.RESULT_CANCELED;
public DownloadService() {
super("DownloadService");
}
#Override
protected void onHandleIntent(Intent intent) {
String urlPath = intent.getStringExtra(URL);
String fileName = intent.getStringExtra(FILENAME);
File output = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
fileName);
if (output.exists()) {
output.delete();
}
URLConnection streamConnection = null;
InputStream stream = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlPath);
streamConnection = url.openConnection();
stream = streamConnection.getInputStream();
streamConnection.connect();
long lengthofFile = streamConnection.getContentLength();
InputStream reader = stream;
bis = new BufferedInputStream(reader);
fos = new FileOutputStream(output.getPath());
int next = -1;
int progress = 0;
int bytesRead = 0;
byte buffer[] = new byte[1024];
while ((bytesRead = bis.read(buffer)) > 0) {
fos.write(buffer, 0, bytesRead);
progress += bytesRead;
int progressUpdate = (int)((progress * 100) / lengthofFile);
Intent testIntent = new Intent(".MESSAGE_INTENT");
testIntent.putExtra(PERCENTAGE, progressUpdate);
sendBroadcast(testIntent);
}
result = Activity.RESULT_OK;
fos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
publishResults(output.getAbsolutePath(), result);
}
private void publishResults(String outputPath, int result) {
Intent intent = new Intent(".MESSAGE_INTENT");
intent.putExtra(FILEPATH, outputPath);
intent.putExtra(RESULT, result);
sendBroadcast(intent);
}
}
and to call this service i would use:
Intent intent = new Intent(MainActivity.getAppContext(), DownloadService.class);
intent.putExtra(DownloadService.FILENAME, downloadFileName[item]);
intent.putExtra(DownloadService.URL, urlDownload[item]);
MainActivity.getAppContext().startService(intent);
now this allows user to download one file at a time, however if the user downloads another file, the second file will have to wait till the first file is done downloading.
now what is happening in my case is:
1- First download FILE_1 is downloading, and in the status is says FILE_1.
2- User clicks a new file download, the status changes the first file name to the second file name, and waits till FILE_1 finishes download to start with FILE_2 however the active download is changed from FILE_1 to FILE_2.
questions:
is there a way to call DownloadService multiple times for multiple files?
is it possible to fix the problem i'm facing? treating download intent services as two different intents?
UPDATE
I managed to solve this issue by assigning a unique Int ID per file, each ID will point to a position in the listview which displays the files being downloaded or queued, then i work with each file on it's own.
Following code uses commons-io-2.4.jar library to make your work easy by handling low level data movements as you would focus on method in hand
URL someUrl = new URL("your url String"); //
File someFile = new File("your file, where you want to save the data");
FileUtils.copyURLToFile(someUrl, someFile );
if you want to call this statement few time to download different files from the server following code might give you an idea what you might want to do, but you will have to write it's equivalent code to run in android which you want to probably AsyncTask
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.io.FileUtils;
public class DownloadTest {
public static void main(String[] args) {
Thread thread = new Thread(){
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
try {
dowanloadFile(new URL("some url"), new File("some file"));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
thread.start();
}
private static void dowanloadFile(URL url, File file){
try {
FileUtils.copyURLToFile(url, file );
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

error when base64String arrived from android to nodejs via socketio

i work on an app who will send image from android to nodejs via socket io and i got this error when i send data who has size like 700,00 KB in node js and i don't know how to someone can help me to work it better ???
This is my java code
File myFile = new File (selectedImagePath);
int ficher = (int) myFile.length();
System.out.println(""+size(ficher));
int file_size = Integer.parseInt(String.valueOf(myFile.length()/1024));
System.out.println(""+file_size);
size(ficher);
FileInputStream imageInFile = null;
try {
imageInFile = new FileInputStream(myFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte imageData[] = new byte[(int) myFile.length()];
try {
imageInFile.read(imageData);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Convert to base64;
String imageDatastring = Base64.encodeToString(imageData, SELECT_PICTURE);
socket.emit("img", imageDatastring, "MAK", "MAK");
And my javascript code (node js) is here
socket.on('img', function(msg, usr, username){
console.log(' Message from : '+username+' \n Message is : '+msg+"\n to : "+usr)
console.log(usernames[usr])
console.log(usernames)
io.sockets.socket(usernames[usr]).emit('event', msg, username);
fs.writeFile(username+ "- to -"+usr+'.png', msg, "base64", function(err){if(err){console.log(err)}})
});
This is error i got
AAAL9wOAGFzc2V0cy9z\nZXR0aW5nc2NyZWVuLnBuZ1BLBQYAAAAAmQCZAMgnAACf/w4AAAA\n","243
810840505","apk","23:10"]}
debug - emitting heartbeat for client ig4QpjbTaEgr20jOs6IA
Assertion failed: end <= source_len, file src\smalloc.cc, line 280
C:\xampp\htdocs\socketio_android-master\socketio_android-master>
I use socket io version 0.9.16
Thanks to all!!

File is not uploading on Ftp server in java?

Hello Every one i am working one project where i need to upload file on my ftp server with my java standalone application
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
public class Ftpdemo {
public static void main(String args[]) {
// get an ftpClient object
FTPClient ftpClient = new FTPClient();
ftpClient.setConnectTimeout(300);
FileInputStream inputStream = null;
try {
// pass directory path on server to connect
ftpClient.connect("ftp.mydomain.in");
// pass username and password, returned true if authentication is
// successful
boolean login = ftpClient.login("myusername", "mypassword");
if (login) {
System.out.println("Connection established...");
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
inputStream = new FileInputStream("/home/simmant/Desktop/mypic.png");
boolean uploaded = ftpClient.storeFile("user_screens/test3.png",inputStream);
if (uploaded) {
System.out.println("File uploaded successfully !");
} else {
System.out.println("Error in uploading file !");
}
// logout the user, returned true if logout successfully
boolean logout = ftpClient.logout();
if (logout) {
System.out.println("Connection close...");
}
} else {
System.out.println("Connection fail...");
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
its working fine for the data which is 1 or 2 kb but when i try to upload the file which is of 50 kb and 100 kb then it not working fine. The image uploaded on the server is blank .
As far as I can see, there is nothing wrong with the code. As you're saying 1 or 2 kb of data uploading works fine. So, In my opinion, there is problem with your internet. Might be it's too slow to upload a file size of 50 kb or more.
There is noting wrong with your code only issue with the file or internet speed.Code is working fine here and Also there is recommended that NOT TO USE FTP DETAILS DIRECTLY please avoid this stuff from application you have better option to use web service for your server related stuff.
Good Luck
It seems you had not made connection Instances properly.
Please refer my working code:
public class FTPUploader {
FTPClient ftp = null;
public FTPUploader() throws Exception {
ftp = new FTPClient();
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(new FileOutputStream("c:\\ftp.log"))));
int reply;
ftp.connect(Constant.FTP_HOST);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
throw new Exception(Constant.FTP_SERVER_EXCEPTION);
}
ftp.login(CommonConstant.FTP_USERNAME, Constant.FTP_PASSWORD);
ftp.setFileType(FTP.TELNET_TEXT_FORMAT);
ftp.enterLocalPassiveMode();
}
public boolean uploadFile(File localFileFullName, String fileName) throws Exception {
InputStream input = new FileInputStream(localFileFullName);
boolean reply = this.ftp.storeFile("'" + fileName +"'", input);
disconnect();
return reply;
}
public void disconnect() {
if (this.ftp.isConnected()) {
try {
this.ftp.logout();
this.ftp.disconnect();
} catch (IOException e) {
System.out.println(this.getClass()+ e);
}
}
}
public static void main(String[] args) throws Exception {
System.out.println("Start");
FTPUploader ftpUploader = new FTPUploader();
System.out.println(ftpUploader.uploadFile(new File("C:\\test.txt"), "Destinate_DIR"));
System.out.println("Done");
}
}
All the best ...!!!

Android TCP socket client/server implementation

I'm new to Java and Android, I'm trying to create a server/client application. For the moment I'm running the server on the PC and the client is on an Android device. The communication takes place and all works fine, but I want to differentiate incoming messages from the client in order to do different actions on the server. Here's the code for the server. The client is pretty easy and works well. For example when I send "Name" from the client, the serve should answer with "Matteo" but it always answers with "Something else" and I can't understand why! I imagine that the problem is in the statement if (dataInputStream.equals("Name")) {
Thank you.
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server1 {
public static void main(String[] args){
ServerSocket serverSocket = null;
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
serverSocket = new ServerSocket(8888);
System.out.println("Listening on port 8888");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(true){
try {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
System.out.println(socket.getInetAddress() + " : " + dataInputStream.readUTF());
if (dataInputStream.equals("Name")) {
dataOutputStream.writeUTF("Matteo!");
}
else if (dataInputStream.equals("Surname")) {
dataOutputStream.writeUTF("Rossi!");
}
else {
dataOutputStream.writeUTF("Something else!");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if( socket!= null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataInputStream!= null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataOutputStream!= null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
DataInputStream represents the handle to stream of data coming from the socket, but not the data itself. So .equals() compares it with another DataInputStream not with a String. You are comparing it directly with a string, which obviously returns false.
Just like you are writing data with writeUTF(), you need to read data from the socket connection through that DataInputStream. Use one of the read() methods described here or if you know that your client will send whole lines, you can wrap it in a BufferedReader and use the following:
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(dataInputStream));
String input = bufferedReader.readLine();
if (input.equals("Name")
{
dataOutputStream.writeUTF("Matteo!");
}
else ...
On another note, in Java 7, you can use switch statements on String too, instead of .equals()
The trick is that you should read something from the DataInputStream. Eg.
byte[] buffer = new byte[ 1024 ];
dataInputStream.read( buffer );
if ( new String( buffer ).equals( "Name" ) ) { /* do your stuff */ }
This is much abbreviated, but you could work from there.
Cheers,
Maybe look into an ObjectInputStream you can then read the object and use the:
instanceof
keyword to differntiate between objects

Android: Dowloaded files got deleted when the app restarts

I download audio files from server using
try {
// URL url = new URL("http://commonsware.com/misc/test2.3gp");
URL url = new URL("http://192.168.0.2/supplications/"+fileName);
//URL url = new URL("http://www.msoftech.com/supplications/android/"+fileName);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
Log.v("log_tag", "PATH: " + PATH);
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1)
{
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
} catch (IOException e) {
Log.d("log_tag", "Error: " + e);
}
Log.v("log_tag", "Check: " +cd2);
Here PATH = "/data/data/packagename/sounds/filename
It works fine, audio file downloaded and played successfully, but my problem is when I click the home button and then restart the app means the folder with the downloaded audio was not found, ie, when exit the app means all the downloaded audios were deleted automatically. It throws the exception file not found.
For playing the downloaded file I used the code as below,
public void audioPlayer(String path, String fileName) throw FileNotFoundException
{
//set up MediaPlayer
FileInputStream fileInputStream = new FileInputStream(PATH+"/"+fileName);
//String command = "chmod 666 " + recordFile.toString();
try {
mp.setDataSource(fileInputStream.getFD());
// mp.setDataSource(path+"/"+filename.mp3);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
whats the problem with it what I have to do for saving the audio file permenantly.
There is nothing problem in your code it is a file permission issue.
When you download file into internal file system under application package a security is assigned to it like "-rw------" this means your file is accessible for the same application only.As android is on Linux based so every file have some permission.
Your file would be there but not accessible to other application like media player etc, so these application throws error like file not found.(you can check though DDMS tool).
Just change the file path to external drive.
Accept the answer if it is helpful.

Categories

Resources