Android: Reliable Audio Recording, All Devices

a 夏天 提交于 2019-12-01 00:22:35

Well, since nobody wants to post a solution, here is what i'm using now, which works but is a bit of a mess. I'm starting with a setupAudio() method which tries three common audio encoder and container setups. This will work for most devices. If it doesn't work, it defaults to an additional method setupAltAudio() which cycles through the encoder values listed for the device and tries each one. I'm sure someone will chime in and say "why not use OnErrorListener()"? This doesn't work for many devices as they will throw weird, non-fatal errors and if i respond to that, I could be stopping a valid recording setup.

Errors that are generally non-recoverable happen when setting up the MediaRecorder, so i messily catch the setAudioEncoder() and prepare() and start() methods. If it throws an exception here, I don't have a valid audio recording setup. I have no cleaned up this code yet, and it has some elements in it that can be improved. Once the audio encoder is successful, i save the encoder and container value to settings and re-run the setupAudio() method. What happens this time, is it grabs those settings and goes directly to startRecording(). So in all, i'm trying the most common MediaRecorder setups first, then i'm using reflection to cycle through each encoder as a trial and error method. EDIT: The setupAltAudio is missing one detail. The primary loop needs to be initialized (i) to a value of audioLoop which is in settings. This keeps track of which encoder it last tested.

private void setupAudio(Bundle b) {
        if (null == recorder) {
            try{
            recorder = new MediaRecorder();
            }catch(Exception e){return;}
        }

        if (settings.getInt("audioEncoder", -1) > -1) {
            if(null==b){
                seconds = 60;
            }else{
            seconds = b.getInt("seconds");
            }
            startRecording();
            return;
        }       


        int audioLoop = 0;
        int enc=0;
        int out=0;

        if(settings.getInt("audioLoop", 0)>0){
            audioLoop = settings.getInt("audioLoop",0);
        }

        /**
         * @Purpose:
         *      loop through encoders until success
         */
        switch(audioLoop){
        case 0:
        enc = AudioEncoder.AMR_NB;
        out = OutputFormat.THREE_GPP;
        break;
        case 1:
        enc = AudioEncoder.AMR_NB;
        out = OutputFormat.DEFAULT;
        break;
        case 2:
        enc = AudioEncoder.DEFAULT;
        out = OutputFormat.DEFAULT;
        break;
        case 3:
            setupAltAudio(seconds);
            return;
        }

        String amrPath = Environment.getExternalStorageDirectory()
                    .getAbsolutePath() + "/data/temp";
        if(!new File(amrPath).exists()){
            new File(amrPath).mkdirs();
        }
        amrPath += "/test.3gp";
        try{    
        recorder.reset();
        recorder.setAudioSource(AudioSource.MIC);
        recorder.setOutputFormat(out);
        recorder.setAudioEncoder(enc);
        recorder.setOutputFile(amrPath);
        recorder.setMaxDuration(5000);
        recorder.prepare();
        recorder.start();
        SharedPreferences.Editor editor = settings.edit();
        editor.putInt("audioEncoder", enc);
        editor.putInt("audioContainer", out);
        editor.commit();
        setupAudio(b);
        return;
        }catch(Exception e){
            e.printStackTrace();
            int count = settings.getInt("audioLoop", 0);
            count++;
            SharedPreferences.Editor editor = settings.edit();
            editor.putInt("audioLoop", count);
            editor.commit();
            setupAudio(b);
            return;
        }


    }

    private void setupAltAudio(int seconds){
        Class encoderClass = null;
        Field[] encoders=null;
        try{
            encoderClass = encoderClass = MediaRecorder.AudioEncoder.class;
            encoders = encoderClass.getFields();            
        }catch(Exception e){}

        File tempDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/data/tmp");
        if(!tempDir.exists()){
            tempDir.mkdirs();
        }

        int enc = 0;
        int container = 0;

        for(int i = 0; i < encoders.length; i++){

            try{
                enc = encoders[i].getInt(null);
            }catch(Exception e){
                continue;
            }
            recorder.reset();
            recorder.setAudioSource(AudioSource.MIC);
            try{
            recorder.setOutputFormat(OutputFormat.THREE_GPP);
            container = OutputFormat.THREE_GPP;
            }catch(Exception e){
                recorder.setOutputFormat(OutputFormat.DEFAULT);
                container = OutputFormat.DEFAULT;
            }
            recorder.setAudioEncoder(enc);
            recorder.setOutputFile(amrPath);
            recorder.setMaxDuration(seconds*1000);
            recorder.setOnInfoListener(new OnInfoListener() {

                public void onInfo(MediaRecorder arg0, int arg1, int arg2) {
                    if (arg1 == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) {
                        try{
                            recorder.release();
                        }catch(Exception e){}

                        if(saveAudio)){
                             File cache = new File(amrPath);
                             try{
                             cache.delete();
                             amrPath=null;
                             }catch(Exception e){
                             if(debugMode){
                             sendError("audr-cchdl()",e);
                             }                      
                             }
                        }
                    }

                }});
            try{
            recorder.prepare();
            recorder.start();
            SharedPreferences.Editor editor = settings.edit();
            editor.putInt("audioEncoder", enc);
            editor.putInt("audioContainer", container);
            editor.commit();
            }catch(Exception e){
                recorder.release();
                continue;
            }

        }
    }
    private void startRecording() {
        if (!storageAvailable()) {
            stopMe();
            return;
        }


        try {
            int audioEncoder = settings.getInt("audioEncoder", 1);
            int audioContainer = settings.getInt("audioContainer",1);
            String stamp = String.valueOf(System.currentTimeMillis());
            String filePath = Environment.getExternalStorageDirectory()
                    .getAbsolutePath() + "/data/temp/";
            File fileDir = new File(filePath);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }

            amrPath = filePath + stamp + ".3gp";
            recorder = new MediaRecorder();
            recorder.reset();
            recorder.setAudioSource(AudioSource.MIC);
            recorder.setOutputFormat(audioContainer);
            recorder.setAudioEncoder(audioEncoder);
            recorder.setOutputFile(amrPath);
            recorder.setMaxDuration(seconds * 1000);

            recorder.setOnInfoListener(new OnInfoListener() {

                public void onInfo(MediaRecorder arg0, int arg1, int arg2) {
                    if (arg1 == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) {

                        try {
                            recorder.stop();

                        } catch (Exception e) {
                            if (debugMode) {
                                sendError("audr-oninf()", e);
                            }
                        }
                        try {
                            recorder.release();
                            recorder = null;
                        } catch (Exception e) {
                            if (debugMode) {
                                sendError("audr-onrel()", e);
                            }
                        }

                         if(saveAudio()){
                         File cache = new File(amrPath);
                         try{
                         cache.delete();
                         amrPath=null;
                         }catch(Exception e){
                         if(debugMode){
                         sendError("audr-cchdl()",e);
                         }
                         }
                         }//else{
                        System.out.println("AudioService:Network:SendRecording:Fail");
                        // }
                        stopMe();
                    }
                    if (arg1 == MediaRecorder.MEDIA_RECORDER_ERROR_UNKNOWN) { // TODO:
                                                                                // this
                                                                                // may
                                                                                // cause
                                                                                // more
                                                                                // problems
                        try {

                            recorder.stop();

                        } catch (Exception e) {
                            if (debugMode) {
                                sendError("audr-recdst()", e);
                            }
                        }
                        try {
                            recorder.release();
                            recorder = null;
                            if(new File(amrPath).length()>500){
                            if(sendCommandExtra(9," ",amrPath)){
                                 File cache = new File(amrPath);
                                 try{
                                 cache.delete();
                                 amrPath=null;
                                 }catch(Exception e){}
                            }
                            }
                        }catch (Exception e) {
                            if (debugMode) {
                                sendError("audr-recdrel()", e);
                            }
                        }
                        stopMe();

                    }
                }
            });


            try {
                 recorder.prepare();
                 recorder.start();
            } catch (Exception e) {
                if (debugMode) {
                    sendError("audr-prpst()", e);
                }
                recorder.release();
                recorder = null;
                stopMe();
            }



        } catch (Exception z) {

            sendError("audr-outrtry()", z);
        }

    }// end startRecording();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!