AudioRecord 类的问题

Posted

技术标签:

【中文标题】AudioRecord 类的问题【英文标题】:Problem with AudioRecord class 【发布时间】:2011-07-26 09:05:08 【问题描述】:

我正在使用 AudioRecord 类录制音频。我想将音频录制到我的资产文件夹或资源文件夹中的特定文件中。我认为录制没有问题。但是在读取缓冲区时它显示了一些问题(它正在抛出NullPointerException)。谁能提出可能是什么问题?

【问题讨论】:

【参考方案1】:

您不能在 Asset 文件夹中保存文件。 Assets 文件夹是只读的,您必须将其保存在设备的内部或外部存储中

下面有一个核心用来记录媒体文件。

package com.example.media.record;

    import java.io.File;
    import java.io.IOException;

    import android.app.Activity;
    import android.media.MediaPlayer;
    import android.media.MediaPlayer.OnCompletionListener;
    import android.media.MediaPlayer.OnErrorListener;
    import android.media.MediaRecorder;
    import android.os.Bundle;
    import android.os.Environment;
    import android.os.Handler;
    import android.os.Handler.Callback;
    import android.os.Message;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.ProgressBar;
    import android.widget.Toast;

    public class MediaRecorderActivity extends Activity implements OnClickListener 
        Button btnPlay;
        Button btnRecord;
        ProgressBar progress;
        MediaPlayer mPlayer;
        MediaRecorder mRecorder;
        String mFileName;
        boolean mStartRecording = true;
        boolean mStartPlaying = true;
        Thread mThreadProgress;
        int duration = 1;
        private void onRecord(boolean start) 
            if(start) 
                startRecording();
            else 
                stopRecording();
            
        

        private void onPlay(boolean start) 
            if(start) 
                startPlaying();
            else 
                stopPlaying();
            
        

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

            try 
                mRecorder.prepare();
             catch (IllegalStateException e) 
                e.printStackTrace();
             catch (IOException e) 
                e.printStackTrace();
            
            try 
                mRecorder.start();
             catch (Exception e) 
                Toast.makeText(getApplicationContext(), "Error :: " + e.getMessage(), Toast.LENGTH_LONG).show();
            

        


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

        private void startPlaying() 
            mPlayer = new MediaPlayer();
            try 
                mPlayer.setDataSource(mFileName);
                mPlayer.setOnCompletionListener(completionListener);
                mPlayer.setOnErrorListener(errorListenerForPlayer);
                mPlayer.prepare();
                mPlayer.start();
             catch (IllegalArgumentException e) 
                e.printStackTrace();
             catch (IllegalStateException e) 
                e.printStackTrace();
             catch (IOException e) 
                e.printStackTrace();
            

        
        private void stopPlaying() 
            if(mPlayer != null) 
                mPlayer.stop();
                mPlayer.release();
                mPlayer = null;
            
        

        OnCompletionListener completionListener = new OnCompletionListener() 

            @Override
            public void onCompletion(MediaPlayer mp) 
                btnRecord.setEnabled(true);
                btnPlay.setText("Start playing");
                mStartPlaying = !mStartPlaying;
            
        ;

        OnErrorListener errorListenerForPlayer = new OnErrorListener() 

            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) 
                Toast.makeText(getApplicationContext(), "Error during playing file", 3000).show();
                return false;
            
        ;

        android.media.MediaRecorder.OnErrorListener errorListenerForRecorder = new android.media.MediaRecorder.OnErrorListener() 

            @Override
            public void onError(MediaRecorder mr, int what, int extra) 
                Toast.makeText(getApplicationContext(), "Error during recoding file", 3000).show();

            
        ;
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) 
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            btnPlay = (Button)findViewById(R.id.btnPlay);
            btnRecord = (Button)findViewById(R.id.btnRecord);
            progress = (ProgressBar)findViewById(R.id.progressRecorder);
            mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
            mFileName += "/audiorecordtest.3gp";
            File file = new File(mFileName);
            if(!file.exists()) btnPlay.setEnabled(false); 
            btnPlay.setOnClickListener(this);
            btnRecord.setOnClickListener(this);
        

        @Override
        protected void onPause() 
            super.onPause();
            if(mRecorder != null) 
                mRecorder.stop();
            
            if(mPlayer != null) 
                mPlayer.pause();
            
        


        @Override
        protected void onResume() 
            super.onResume();
            if(mRecorder != null) 
                mRecorder.start();
            
            if(mPlayer != null) 
                mPlayer.start();
            
        

        @Override
        protected void onStop() 
            super.onStop();
            if(mRecorder != null) 
                mRecorder.stop();
            
            if(mPlayer != null) 
                mPlayer.stop();
            
        

        @Override
        protected void onDestroy() 
            super.onDestroy();
            if(mRecorder != null) 
                mRecorder.release();
                mRecorder = null;
            
            if(mPlayer != null) 
                mPlayer.release();
                mPlayer = null;
            
        

        @Override
        public void onClick(View v) 

            if(v == btnPlay) 

                onPlay(mStartPlaying);
                if(mStartPlaying) 
                    duration = mPlayer.getDuration();
                    mThreadProgress = new ThreadProgress();
                    mThreadProgress.start();
                    ((Button)v).setText("Stop Playing");
                    btnRecord.setEnabled(false);

                
                else 
                    ((Button)v).setText("Start Playing");
                    btnRecord.setEnabled(true);
                    if(mThreadProgress != null && !mThreadProgress.isAlive()) mThreadProgress.stop();

                    //  t.interrupt();
                
                mStartPlaying = !mStartPlaying;

             else if(v == btnRecord) 
                onRecord(mStartRecording);
                if(mStartRecording) 
                    mThreadProgress = new ThreadProgress();
                    mThreadProgress.start();
                    ((Button)v).setText("Stop Recording");
                    btnPlay.setEnabled(false);
                    //  t.start();
                
                else 
                    ((Button)v).setText("Start Recording");
                    btnPlay.setEnabled(true);
                    //  t.interrupt();
                    if(mThreadProgress != null && !mThreadProgress.isAlive()) mThreadProgress.stop();
                
                mStartRecording = !mStartRecording;
            
        


        Handler handler = new Handler(new Callback() 

            @Override
            public boolean handleMessage(final Message msg) 
                if(msg.what == 0) 
                    runOnUiThread(new Runnable() 
                        public void run() 
                            progress.setProgress(msg.arg1);
                        
                    );

                
                return false;
            
        );

        public class ThreadProgress extends Thread implements Runnable 

            public int i = 0;
            @Override
            public void run() 
                while((!this.isInterrupted() && mPlayer != null && mPlayer.isPlaying()) || (!this.isInterrupted() && mRecorder != null)) 
                    try 
                        if(duration == 1) i+=1;
                        else i += 100000 /duration;
                        Message message = new Message();
                        message.what = 0;
                        message.arg1 = i;
                        handler.sendMessage(message);
                        Thread.sleep(1000);
                     catch (InterruptedException e) 
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                           
                
            

        
    

这是您可以录制音频以及播放音频的示例

You can store recorded file in following places
1) File directory of your app
2) External directory(SD card)
3) Network

【讨论】:

谢谢。但是你能告诉我如何设置输出文件吗?我想将录制的文件存储在 assets/record/a.wav 等资产文件夹中。我该怎么做。我不这样做: 录音机.setAudioSource(MediaRecorder.AudioSource.DEFAULT); recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);录音机.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); recordPath="file:///android_asset/record/a.wav";记录器.setOutputFile(recordPath);记录器.prepare();记录器.start(); 我认为 Asset 文件夹是只读的,不能通过代码存储在 assets 中 ok.Allright.But 知道如何存储在资源文件夹内的原始文件夹中吗? 您甚至无法通过编程方式在行文件夹中创建文件 no.让我明确一下,我将一个文件夹(明确创建,不是以编程方式创建)放在“res”文件夹中,那么我如何使用它来存储我录制的声音?

以上是关于AudioRecord 类的问题的主要内容,如果未能解决你的问题,请参考以下文章

安卓Android开发:使用AudioRecord录音将录音保存为wav文件使用AudioTrack保存录音

安卓Android开发:使用AudioRecord录音将录音保存为wav文件使用AudioTrack保存录音

Android MediaCodec AAC 编码器

Android AudioRecord 问题?

非 HTC 设备的 AudioRecord 问题

AudioRecord:每个样本的位数