其他分享
首页 > 其他分享> > Android Studion错误Okhttp3单击按钮后未上传音频文件

Android Studion错误Okhttp3单击按钮后未上传音频文件

作者:互联网

您好昨天,我在将文件上传到服务器(https://www.youtube.com/watch?v=K48jnbM8yS4)时看到了一个使用okhtpp3的教程,我按照该教程进行了学习,并且运行正常,但是现在我正在尝试开发一个具有录制按钮来录制音频并将其保存到内部存储以及另一个应用的应用按钮上传音频文件.

但是它没有上传文件.

我的应用程式码:

        public class MainActivity extends AppCompatActivity{


        private String n="";

        private Button mRecordBtn,uploadBtn;
        private TextView mRecordLabel;
        private MediaRecorder mRecorder;

        private String mFileName = null;
        private static final String LOG_TAG = "Record_log";

        final int REQUEST_PERMISSION_CODE =1000;

        private ProgressDialog progress;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);


            if(!checkPermissionFromDevice()){
                requestPermission();

            }

            mRecordLabel =(TextView) findViewById(R.id.recordLbl);
            mRecordBtn =(Button)findViewById(R.id.recordBtn);


            mFileName = Environment.getExternalStorageDirectory() + "/file.3gp";



            mRecordBtn.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {

                    if (checkPermissionFromDevice()) {




                    if (event.getAction() == MotionEvent.ACTION_DOWN) {
                        startRecording();
                        mRecordLabel.setText("Recording Started...");

                    } else if (event.getAction() == MotionEvent.ACTION_UP) {

                        stopRecording();
                        mRecordLabel.setText("Recording Stoped...");
                    }

                }
                else{
                        requestPermission();
                    }
                    return false;
                }
            });


                uploadBtn =(Button)findViewById(R.id.uplaodBtn);
                uploadBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        sendFile();

                    }
                });


        }

        private void startRecording() {
            mRecorder = new MediaRecorder();
            mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            mRecorder.setOutputFile(mFileName);
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);


            try {
                mRecorder.prepare();
            } catch (IOException e) {
                Log.e(LOG_TAG, "prepare() failed");
            }

            mRecorder.start();
        }

        private void stopRecording() {
            mRecorder.stop();
            mRecorder.release();
            mRecorder = null;





        }

        private void requestPermission(){

            ActivityCompat.requestPermissions(this,new String[]{

                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.READ_EXTERNAL_STORAGE
            },REQUEST_PERMISSION_CODE);
        }

        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            switch(requestCode) {
                case REQUEST_PERMISSION_CODE: {
                    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                        Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
                    else{
                        Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
                    }

                }


                break;
            }


        }

        private boolean checkPermissionFromDevice(){

            int write_internal_storage_result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            int record_audio_result =ContextCompat.checkSelfPermission(this,Manifest.permission.RECORD_AUDIO);
            int read_internal_storage_result =ContextCompat.checkSelfPermission(this,Manifest.permission.READ_EXTERNAL_STORAGE);

            return  write_internal_storage_result == PackageManager.PERMISSION_GRANTED && record_audio_result == PackageManager.PERMISSION_GRANTED && read_internal_storage_result == PackageManager.PERMISSION_GRANTED;


        }



        private void sendFile() {



            OkHttpClient client = new OkHttpClient();
            File f = new File(mFileName);
            String content_type  = getMimeType(f.getPath());
            String file_path = f.getAbsolutePath();

            RequestBody file_body = RequestBody.create(MediaType.parse(content_type),f);
            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("title", content_type)
                    .addFormDataPart("uploaded_file",file_path.substring(file_path.lastIndexOf("/")+1), file_body)
                    .build();

            Request request = new Request.Builder()
                    .url("http://192.168.8.100/etrack/save_audio.php")
                    .post(requestBody)
                    .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
    //                Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_LONG).show();
                }

                @Override
                public void onResponse(Call call, final Response response) throws IOException {
    //                if (!response.isSuccessful()) {
    //                    Toast.makeText(MainActivity.this, "Response error", Toast.LENGTH_LONG).show();
    //                }
                }
            });
        }

    private String getMimeType(String path){

        String extension = MimeTypeMap.getFileExtensionFromUrl(path);
        return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);


    }
}

这是我的PHP代码:

    <?php

$file_path = "images/";

$file_path = $file_path . basename($_FILES['uploaded_file']['name']);

if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$file_path)) {
    echo "success";
}else {
    echo "error";
}

?>

我的构建:gradle代码:

    apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    defaultConfig {
        applicationId "www.teamruby.com.samplerecord"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    repositories {
        maven {
            url "http://dl.bintray.com/lukaville/maven"
        }
    }
    productFlavors {
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:24.2.'
    implementation 'com.android.support:design:24.2.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.squareup.okhttp3:okhttp:3.6.0'
}

解决方法:

File f = new File(mFileName);
MultipartBody.Builder data = new MultipartBody.Builder();
                data.setType(MultipartBody.FORM);
                data.addFormDataPart("uploaded_file", "file.3gp", RequestBody.create(MediaType.parse("media/type"), f));
                RequestBody requestBody = data.build();

                Request request = new Request.Builder()
                        .url("192.168.8.100/etrack/save_audio.php").post(requestBody)
                        .build();

标签:okhttp3,audio-recording,mysql,android
来源: https://codeday.me/bug/20191108/2010166.html