尝试将音频文件上传到服务器时出现Android问题

时间:2014-01-23 08:42:38

标签: android audio file-upload audio-recording android-mediarecorder

我正在尝试在录制结束时将音频文件上传到服务器。我已将CurrentDate和Time设置为音频文件名,您可以在下面的代码中看到。

 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]);
}

所以现在文件将被存储为sdcard中的 2014年1月23日12-34-55.mp4

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);
        }
    } 

现在我用下面的行将我的录音存储在SD卡中

recorder.setOutputFile(getFilename());

以及将音频文件上传到服务器的行。

doAudioFileUpload(getFilename());

因此它同时使用相同的getFilename()。现在问题发生在第一次recorder.setOutputFile(getFilename());这个调用时它会将文件名存储在SD卡中23-Jan-2014 12-34-55.mp4,并且在20秒的记录之后当这一行调用上传音频到服务器时它应该上传23-Jan-2014 12-34-15.mp4此文件,但不是这样,而是搜索23-Jan-2014 12-34-55.mp4文件,并向我显示找不到文件的错误。

所以基本上在录制开始后,当我调用doAudioFileUpload(getFilename());时,它开始搜索currentDateandTime文件,而不是我录制的文件。

我尝试使用一些动态名称上传文件,但它工作正常但是当我尝试对此日期和时间执行相同操作时会出错。

请帮我解决这个问题。任何帮助,将不胜感激。提前谢谢......

修改我的Logcat位于

之下
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)

2 个答案:

答案 0 :(得分:1)

我认为你正在尝试录制,保存到sccard然后上传到服务器,对吗?

然后,为什么不尝试使用FileObserver呢?使用FileObserver,您可以侦听目录中的任何文件操作,获取最后添加的文件(及其元数据),然后使用服务上传。

 // 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 

答案 1 :(得分:1)

这是你需要做的,就像你调用getFileName()的方法一样,它实际上通过添加当前时间和日期来实现文件名,所以第一次调用时,它会告诉你{ {1}}当您尝试通过01-01-2014 12-12-20.mp4上传文件后20秒录制时,它再次调用该方法并返回续订的文件名{{1} }秒后,即doUploadFile(getFileName())。所以这是你两次调用同一个方法的问题,只需使用一次,这是你的最终代码。

20
相关问题