Android issue while trying to Upload audio file to

2019-07-23 20:00发布

问题:

I am trying to upload audio file to server when recording gets finished. I have set CurrentDate and Time as audio file name as you can see that in below code.

 private String getFilename() {
        String filepath = Environment.getExternalStorageDirectory().getPath();
        File file = new File(filepath, AUDIO_RECORDER_FOLDER);

        SimpleDateFormat sdfDate = new SimpleDateFormat("dd-MMM-yyyy hh-mm-ss");
        String currentDateandTime = sdfDate.format(new Date());

        if (!file.exists()) {
            file.mkdirs();
        }
        return (file.getAbsolutePath() + "/" + currentDateandTime + file_exts[currentFormat]);
}

So now file will be stored as 23-Jan-2014 12-34-55.mp4 inside the sdcard.

private void startRecording() {
        recorder = new MediaRecorder();
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setOutputFormat(output_formats[currentFormat]);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        recorder.setOutputFile(getFilename());
        recorder.setOnErrorListener(errorListener);
        recorder.setOnInfoListener(infoListener);
        try {
            recorder.prepare();
            recorder.start();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void stopRecording() {
        if (null != recorder) {
            recorder.stop();
            recorder.reset();
            recorder.release();
            recorder = null;
            doAudioFileUpload(getFilename());
        }
    }

    private void doAudioFileUpload(String path) {
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        DataInputStream inStream = null;
        String existingFileName = path;

        System.out.println("Inside of doupload nd path is === " + path);

        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024 * 1024;
        String urlString = "http://server-link/folder-name/upload_audio.php";
        try {
            // ------------------ CLIENT REQUEST
            FileInputStream fileInputStream = new FileInputStream(new File(
                    existingFileName));
            // open a URL connection to the Servlet
            URL url = new URL(urlString);
            // Open a HTTP connection to the URL
            conn = (HttpURLConnection) url.openConnection();
            // Allow Inputs
            conn.setDoInput(true);
            // Allow Outputs
            conn.setDoOutput(true);
            // Don't use a cached copy.
            conn.setUseCaches(false);
            // Use a post method.
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
                    + existingFileName + "\"" + lineEnd);
            dos.writeBytes(lineEnd);
            // create a buffer of maximum size
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            // read file and write it into form...
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            while (bytesRead > 0) {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }
            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            // close streams
            Log.e("Debug", "File is written");
            fileInputStream.close();
            dos.flush();
            dos.close();
        } catch (MalformedURLException ex) {
            Log.e("Debug", "error: " + ex.getMessage(), ex);
        } catch (IOException ioe) {
            Log.e("Debug", "error: " + ioe.getMessage(), ioe);
        }
        // ------------------ read the SERVER RESPONSE
        try {
            inStream = new DataInputStream(conn.getInputStream());
            String str;

            while ((str = inStream.readLine()) != null) {
                Log.e("Debug", "Server Response " + str);
            }
            inStream.close();

        } catch (IOException ioex) {
            Log.e("Debug", "error: " + ioex.getMessage(), ioex);
        }
    } 

Now i have used below line to store my recording in SD-card

recorder.setOutputFile(getFilename());

and below line for uploading audio file to server.

doAudioFileUpload(getFilename());

so it is using same getFilename() for both purpose. Now problem occurs here when first time recorder.setOutputFile(getFilename()); this calls it will store file name in sd-card as 23-Jan-2014 12-34-55.mp4 and after 20 Second's of recording when this line calls to upload audio to server it should upload 23-Jan-2014 12-34-15.mp4 this file but instead of this it is searching for 23-Jan-2014 12-34-55.mp4 file and giving me error of File not found.

So basically after recording starts , when i call doAudioFileUpload(getFilename()); , it starts searching for currentDateandTime file not the file which i have recorded.

I have tried to upload file with some dynamic name and it is working fine but when i try to do the same with this date and time it is giving error.

Please help me solve this issue. Any help would be appreciated. Thanks in advance...

Edit My Logcat is below

01-23 14:12:54.716: I/System.out(9279): Inside of doupload nd path is === /mnt/sdcard/AudioRecorder/23-Jan-2014 02-12-54.mp4
01-23 14:12:54.765: E/Debug(9279): error: /mnt/sdcard/AudioRecorder/23-Jan-2014 02-12-54.mp4: open failed: ENOENT (No such file or directory)
01-23 14:12:54.765: E/Debug(9279): java.io.FileNotFoundException: /mnt/sdcard/AudioRecorder/23-Jan-2014 02-12-54.mp4: open failed: ENOENT (No such file or directory)
01-23 14:12:54.765: E/Debug(9279):  at libcore.io.IoBridge.open(IoBridge.java:448)
01-23 14:12:54.765: E/Debug(9279):  at java.io.FileInputStream.<init>(FileInputStream.java:78)
01-23 14:12:54.765: E/Debug(9279):  at iqualtech.skirr.Record_AudioPG.doAudioFileUpload(Record_AudioPG.java:293)
01-23 14:12:54.765: E/Debug(9279):  at iqualtech.skirr.Record_AudioPG.stopRecording(Record_AudioPG.java:271)
01-23 14:12:54.765: E/Debug(9279):  at iqualtech.skirr.Record_AudioPG.access$0(Record_AudioPG.java:265)
01-23 14:12:54.765: E/Debug(9279):  at iqualtech.skirr.Record_AudioPG$4.onClick(Record_AudioPG.java:124)
01-23 14:12:54.765: E/Debug(9279):  at android.view.View.performClick(View.java:3517)
01-23 14:12:54.765: E/Debug(9279):  at android.view.View$PerformClick.run(View.java:14155)
01-23 14:12:54.765: E/Debug(9279):  at android.os.Handler.handleCallback(Handler.java:605)
01-23 14:12:54.765: E/Debug(9279):  at android.os.Handler.dispatchMessage(Handler.java:92)
01-23 14:12:54.765: E/Debug(9279):  at android.os.Looper.loop(Looper.java:154)
01-23 14:12:54.765: E/Debug(9279):  at android.app.ActivityThread.main(ActivityThread.java:4624)
01-23 14:12:54.765: E/Debug(9279):  at java.lang.reflect.Method.invokeNative(Native Method)
01-23 14:12:54.765: E/Debug(9279):  at java.lang.reflect.Method.invoke(Method.java:511)
01-23 14:12:54.765: E/Debug(9279):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
01-23 14:12:54.765: E/Debug(9279):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
01-23 14:12:54.765: E/Debug(9279):  at dalvik.system.NativeStart.main(Native Method)
01-23 14:12:54.765: E/Debug(9279): Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
01-23 14:12:54.765: E/Debug(9279):  at libcore.io.Posix.open(Native Method)
01-23 14:12:54.765: E/Debug(9279):  at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
01-23 14:12:54.765: E/Debug(9279):  at libcore.io.IoBridge.open(IoBridge.java:432)
01-23 14:12:54.765: E/Debug(9279):  ... 16 more
01-23 14:12:54.766: D/AndroidRuntime(9279): Shutting down VM
01-23 14:12:54.766: W/dalvikvm(9279): threadid=1: thread exiting with uncaught exception (group=0x40e14258)
01-23 14:12:54.771: E/AndroidRuntime(9279): FATAL EXCEPTION: main
01-23 14:12:54.771: E/AndroidRuntime(9279): java.lang.NullPointerException
01-23 14:12:54.771: E/AndroidRuntime(9279):     at iqualtech.skirr.Record_AudioPG.doAudioFileUpload(Record_AudioPG.java:342)
01-23 14:12:54.771: E/AndroidRuntime(9279):     at iqualtech.skirr.Record_AudioPG.stopRecording(Record_AudioPG.java:271)
01-23 14:12:54.771: E/AndroidRuntime(9279):     at iqualtech.skirr.Record_AudioPG.access$0(Record_AudioPG.java:265)
01-23 14:12:54.771: E/AndroidRuntime(9279):     at iqualtech.skirr.Record_AudioPG$4.onClick(Record_AudioPG.java:124)
01-23 14:12:54.771: E/AndroidRuntime(9279):     at android.view.View.performClick(View.java:3517)
01-23 14:12:54.771: E/AndroidRuntime(9279):     at android.view.View$PerformClick.run(View.java:14155)
01-23 14:12:54.771: E/AndroidRuntime(9279):     at android.os.Handler.handleCallback(Handler.java:605)
01-23 14:12:54.771: E/AndroidRuntime(9279):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-23 14:12:54.771: E/AndroidRuntime(9279):     at android.os.Looper.loop(Looper.java:154)
01-23 14:12:54.771: E/AndroidRuntime(9279):     at android.app.ActivityThread.main(ActivityThread.java:4624)
01-23 14:12:54.771: E/AndroidRuntime(9279):     at java.lang.reflect.Method.invokeNative(Native Method)
01-23 14:12:54.771: E/AndroidRuntime(9279):     at java.lang.reflect.Method.invoke(Method.java:511)
01-23 14:12:54.771: E/AndroidRuntime(9279):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
01-23 14:12:54.771: E/AndroidRuntime(9279):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
01-23 14:12:54.771: E/AndroidRuntime(9279):     at dalvik.system.NativeStart.main(Native Method)

回答1:

This is what you need to do, as in the same method you are calling getFileName() which actually implements the name of file by adding current time and date, so the first time you call, it gives you say 01-01-2014 12-12-20.mp4 and after 20 seconds recording when you try to upload file via doUploadFile(getFileName()) it again calls that method and returns you a renewed file name that will be 20 seconds later that is 01-01-2014 12-12-40.mp4 . So here is your issue of calling same method twice, just use it once and here is your final code.

String myFileName = "";

@Override onCreate(){
    //Your recording process
    //Your uploading process
}
private void startRecording() {
    myFileName = getFilename();
    recorder = new MediaRecorder();
    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    recorder.setOutputFormat(output_formats[currentFormat]);
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    recorder.setOutputFile(myFileName);
    recorder.setOnErrorListener(errorListener);
    recorder.setOnInfoListener(infoListener);
    try {
        recorder.prepare();
        recorder.start();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private void stopRecording() {
    if (null != recorder) {
        recorder.stop();
        recorder.reset();
        recorder.release();
        recorder = null;
        doAudioFileUpload(myFileName);
    }
}


回答2:

I think you're trying to record, save to sccard then upload to server, right?

Then, why not try using FileObserver instead? With FileObserver you can listen to any file operation in the directory, get the last added file (and its metadata) and then upload it using a service.

 // set up a file observer to watch this directory on sd card 
 observer = new FileObserver(pathToWatch) {

     @Override
     public void onEvent(int event, String file) {
         if(event == FileObserver.CREATE && !file.endWith(".mp4")){ 
             Log.d(TAG, "File created [" + pathToWatch + file + "]");       
             Toast.makeText(getBaseContext(), file + " was saved!",Toast.LENGTH_LONG).show();                 
             // upLoadFileToServer();
         }
     }
 };

 observer.startWatching(); //START OBSERVING