AudioRecord 类的问题

发布于 2024-11-26 01:07:04 字数 125 浏览 0 评论 0原文

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

I am recording audio using AudioRecord class.I want to record audio into a particular file in my asset folder or resource folder.I think there is no problem in recording.but while reading buffer it is showing some problem(it is throwing NullPointerException).Can anyone suggest what may be the problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ぽ尐不点ル 2024-12-03 01:07:04

您无法将文件保存在 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

You can not save file inside Asset folder. Assets folder is read only instead of it you will have to save it in the internal or external storage of your device

Below there is a core to record the media file.

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

        }
    }

This is the example you can record audio as well as play audio

You can store recorded file in following places
1) File directory of your app
2) External directory(SD card)
3) Network
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文