尝试将音频文件上传到服务器时出现Android问题 [英] Android issue while trying to Upload audio file to server

查看:273
本文介绍了尝试将音频文件上传到服务器时出现Android问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

因此,现在文件将以 2014年1月23日12-34-55.mp4 的形式存储在sdcard中.

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

现在我已使用下面的代码将录音存储在SD卡中

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

因此,这两个目的都使用相同的getFilename().现在,这里出现问题了,当第一次调用此命令时,它将在文件卡中将文件名存储为23-Jan-2014 12-34-55.mp4,并且在录制20秒后,当此行调用将音频上传到服务器时,它应该上传此文件23-Jan-2014 12-34-15.mp4,但是为此,它正在搜索23-Jan-2014 12-34-55.mp4文件,并给我文件未找到的错误.

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.

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

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

编辑我的Logcat在下面

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)

推荐答案

这就是您需要做的,就像调用getFileName()的相同方法一样,该方法实际上通过添加当前时间和日期来实现文件名,因此,第一次调用时,它会提示您01-01-2014 12-12-20.mp4,并且在录制20秒后,当您尝试通过doUploadFile(getFileName())上传文件时,它会再次调用该方法并为您返回续订文件名将在20秒后,即01-01-2014 12-12-40.mp4.因此,这是您两次调用同一方法的问题,只需使用一次,这就是您的最终代码.

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

这篇关于尝试将音频文件上传到服务器时出现Android问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆