Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to record a video directly on Helix Server from my Android device?

I am new to server side development. I want to work on an application and I need to record a video on Helix Server from my Android device through my application. I have installed the Helix Server on a Windows Server PC.

In the Android application, I am trying to upload a recorded video on the Helix Server. I have implemented my application for recording the video on SD card but I would like to record and save that video on Helix Server directly. I have implemented my Android application as follows:

public class NewRecordingVideo extends Activity implements SurfaceHolder.Callback {
    private MediaRecorder recorder;
    boolean flag = false;
    boolean startedRecording = false;
    boolean stoppedRecording = false;
    SurfaceHolder mHolder;
    SurfaceView videoSView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        setContentView(R.layout.activity_main);
        recorder = new MediaRecorder();
        recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
        recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_RECOGNITION);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        recorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
        videoSView = ((SurfaceView)findViewById(R.id.surfaceView1));
        mHolder=videoSView.getHolder();
        mHolder.addCallback(this);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        ((Button)findViewById(R.id.startBtn)).setOnClickListener(
            new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if(startedRecording == false) {
                    recorder.start();
                    startedRecording = true;

                    Toast.makeText(NewRecordingVideo.this,
                        "Your video is recording", Toast.LENGTH_LONG).show();

                 } else if (startedRecording == true && stoppedRecording == false) {
                     recorder.stop();
                     recorder.release();
                     recorder = null;
                     stoppedRecording = true;
                 }
             }
         });

        ((Button)findViewById(R.id.stopBtn)).setOnClickListener(
            new OnClickListener() {

            @Override
            public void onClick(View v) {
                recorder.stop();
                recorder.release();
                recorder = null;
                stoppedRecording = true;

                Toast.makeText(NewRecordingVideo.this,
                    "Your video recorded ", Toast.LENGTH_LONG).show();
                finish();
            }
        }); 
    }

    public Surface getSurface() {
        return mHolder.getSurface();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format,
        int width, int height) {

        // TODO Auto-generated method stub  
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {

        try {

            Socket socket = new Socket("IP address", 8008);
            ParcelFileDescriptor pfd = ParcelFileDescriptor.fromSocket(socket);
            Log.v("find about connection","====>"+socket.isConnected());
            recorder.setOutputFile("/sdcard/recording.3gp");

            // Here I would like to record my video (recording.3gp) on helix server directly    
            recorder.setPreviewDisplay(mHolder.getSurface());
            recorder.prepare();

        } catch (Exception e) {
            String message = e.getMessage();
            recorder.release();
            recorder = null;
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (recorder != null) {
            recorder.release();
            recorder = null;
        }
    }
}

From the code above: How can I save my video recording file on Helix server directly? Should I do any implementation on server side development?

like image 372
prasad.gai Avatar asked Feb 27 '13 04:02

prasad.gai


1 Answers

The ratio between the size of a video and a network upload capacity in a given interval of time is to low to simultaneously upload/record video stream, unless the user has a very fast LTE cellular connection.

However, when the recording is done, you can upload the file to your server via a FTP protocol. It is recommended to give each recorded file an Universal Unique Identifier (UUID) to be able to make the difference between all the other recorded files. I used this code (not tested for Android, but works fine on JavaSE 7). Since it is a quite long (but quick) process, I made you a summary. (Nice, huh?)

Summary

1) Generate a UUID with UUID.randomUUID().toString(); that will be used during the whole process to identify the recorded file.
2) Record the file with as name "sdcard/" + uuid + ".3gp"
3) When recording ends, upload the file to your server via a FTP upload.
4) Order your remote server to execute the PHP script that do whatever it needs to do with the recorded file, like database manipulation, etc. (if there is such a script, if you don't need to do this, just skip this step).
5) Order your remote server to delete the file, if needed to. (done via another PHP script)

Code

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

public class FTPUploader {
    static void doUpload(String uuid) {

      File fileSource = new File("/sdcard/" + uuid + ".3gp");
      // Or new File("/sdcard/recording.3gp");

      String fileName = fileSource.getName();

      /** YOUR SERVER'S INFORMATIONS **/
      String userName = "USERNAME";
      String password = "PASSWORD";
      String ftpServer = "FTP.SERVER.COM";
      /****/

      StringBuffer sb = new StringBuffer("ftp://");

      sb.append(userName);
      sb.append(':');
      sb.append(password);
      sb.append('@');

      sb.append(ftpServer);
      sb.append("/"); 
            /**WARNING: Path extension; it will be added after connection
            *The file must be at your server's root. Otherwise the PHP script won't detect it.
            **/
      sb.append(fileName);

      sb.append(";type=i");


      BufferedInputStream bis = null;
      BufferedOutputStream bos = null;
      try {

            URL url = new URL(sb.toString());
            URLConnection urlc = url.openConnection();
            bos = new BufferedOutputStream(urlc.getOutputStream());
            bis = new BufferedInputStream(new FileInputStream(fileSource));

            int i;

            // read byte by byte until end of stream
            while ((i = bis.read()) != -1) {
                  bos.write(i);
            }
      } catch (Exception e) {
            e.printStackTrace();
      } finally {

            if (bis != null)
                  try {
                        bis.close();
                  } catch (IOException ioe) {
                        ioe.printStackTrace();
                        System.out.println("IO exception after if bis " + ioe);
                  }
            if (bos != null)
                  try {
                        bos.close();
                  } catch (IOException ioe) {
                        ioe.printStackTrace();
                        System.out.println("IO exception after if " + ioe);
                  }
      }
}
}  



import java.util.UUID;

public class Main {


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


        String uuid = UUID.randomUUID().toString();
        //Assuming you set your file's name as uuid + ".3gp"
        FTPUploader.doUpload(uuid);            
        //Launches a FTP Upload


        //Then, if you want to ask your server to "process" the file you gave him, you can perform a simple HTTP request:

        try {
    String url = "http://YOURSITE.COM/shell.php";
    String charset = "iso-8859-1";
    String param1 = uuid;
    String query = String.format("id=%s", URLEncoder.encode(param1, charset));

        URLConnection connection = new URL(url + "?" + query).openConnection();
        connection.setRequestProperty("Accept-Charset", charset);
        connection.getInputStream();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
        //This try {}catch{} requests a PHP script: this script is "triggered" just like if it was loaded in your web browser, with as parameter the file UUID (`shell.php?id=UUID`), so that he knows wich file on his server he has to process.

}  

BONUS: If you want to delete the file from your server when you are done with it, you can execute the same line as before, but replacing "shell.php" by another PHP script that you can call "delete.php". It would contain the following lines:

<?php
$recordedFile = $_GET['id'] . ".3gp";
unlink($recordedFile);
?>

For example: Following request http://www.YOURSERVER.com/delete.php?id=123456789 deletes http://www.YOURSERVER.com/123456789.3gp on your server.

Another sample code

Few weeks ago, I set up an Java app (I called it Atom...) that analyses the voice and answer all the questions (using Google (unofficial) Voice Recognition API and Wolfram|Alpha API). You should definitely take a look at it on GitHub, there are all the files used, both Desktop-side and Server-side. Hope I've helped!

EDIT: To work with your Helix server

I found this tutorial about How to Manage and Use FTP on simplehelix.com, and this video Windows Server 2008 R2 - Configuring an FTP Server. You only have to follow the instructions, but skip the step called Logging into an FTP account because it only explains how to manage the files from an application client (like FileZilla or CuteFTP). This is done with of the Java snippet I've written above. Also, if it can help you, I found this video.

NOTE: In the first code (Java), unless the root directory that your FTP server accesses is the folder that contains every media files, you will have to replace sb.append("/"); by the path to the folder where the streamable media files are/should be located. Form example, sb.append("/username/media/");.

like image 104
guillaume Avatar answered Oct 31 '22 15:10

guillaume