Android:可靠的音频录制,所有设备

标签 android mediarecorder amr

有人可以与我分享一种使用 MediaRecorder 在所有设备上录制音频的可靠方法吗?我只是想录制一个低比特率 AMR 格式的音频文件,根据谷歌的说法,这是所有设备的标准。那是一堆废话。

根据我的经验,有许多非品牌设备、平板电脑等在使用默认的 AudioEncoder.AMR_NB 时会严重失败。我的解决方法目前是使用反射来轮询父类(super class)中的编码器,然后使用错误监听器循环遍历每个编码器以查看哪个编码器不会失败。这不仅不优雅,而且不能捕获所有设备。我还尝试过将 AudioEncoder 和 OutputFormat 选项设置为默认值(常量 0),但这在某些设备上也严重失败。

如果默认 AMR 编码器不起作用,我将使用以下方法:

Class encoderClass = MediaRecorder.AudioEncoder.class;
Field[] encoders = encoderClass.getFields();

然后我循环遍历每个编码器,设置一个错误监听器。如果它成功结束,我将其设置为默认编码器作为设置。

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

try {
    int enc = encoders[i].getInt(null);
    recorder.reset();
    recorder.setAudioSource(AudioSource.MIC);
    recorder.setOutputFormat(OutputFormat.THREE_GPP);
    recorder.setAudioEncoder(enc);  //testing the encoder const here
    recorder.setOutputFile(amrPath);
    recorder.setMaxDuration(3000);
    recorder.setOnInfoListener(new OnInfoListener() {

如果监听器捕获错误,我将继续循环:

if (arg1 == MediaRecorder.MEDIA_RECORDER_ERROR_UNKNOWN) {

此技术适用于大多数设备。剩下的呢? 我仍然有一些设备出现问题,坦率地说我想要 对于几乎所有设备来说都是可靠的???

最佳答案

好吧,由于没有人愿意发布解决方案,这就是我现在正在使用的解决方案,它可以工作,但有点困惑。我从 setupAudio() 方法开始,该方法尝试三种常见的音频编码器和容器设置。这适用于大多数设备。如果它不起作用,则默认使用另一种方法 setupAltAudio() ,该方法循环遍历为设备列出的编码器值并尝试每个值。我确信有人会插嘴说“为什么不使用 OnErrorListener()”?这对许多设备不起作用,因为它们会抛出奇怪的非 fatal error ,如果我对此做出响应,我可能会停止有效的录制设置。

设置 MediaRecorder 时通常会发生不可恢复的错误,因此我困惑地捕获了 setAudioEncoder() 、prepare() 和 start() 方法。如果它在这里引发异常,则说明我没有有效的录音设置。我还没有清理这段代码,其中有一些可以改进的元素。音频编码器成功后,我将编码器和容器值保存到设置并重新运行 setupAudio() 方法。这次会发生什么,它会获取这些设置并直接进入 startRecording()。因此,总而言之,我首先尝试最常见的 MediaRecorder 设置,然后使用反射循环每个编码器作为试错方法。 编辑: setupAltAudio 缺少一个细节。主循环需要初始化 (i) 为设置中的 audioLoop 值。这会跟踪上次测试的编码器。

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

关于Android:可靠的音频录制,所有设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12362918/

相关文章:

android - 应用程序启动时应用程序类不运行?

android - MediaRecorder.AudioSource.VOICE_CALL 不适用于 Android 4.1.2 中的通话录音

android - 使用 MediaRecorder 录制屏幕特定 View

java - Java 中的 AMR 到 WAV 转换器

java - 编码器/解码器 PCM 到 AMR Android

Android RIL speech_codec_info

java - 通过字符串引用id android

android - Android 中更高效的 map 叠加

java - 如何从 fragment B 中删除 fragment A 中的列表项?

android - 录制声音时获取分贝值?