在 Android 上录制和保存音频

发布于 2024-11-05 08:32:14 字数 4689 浏览 3 评论 0原文

我正在开发一个 android (2.2) 应用程序来录制音频。该代码似乎运行良好,甚至将文件保存在 SD 卡上,但当我尝试在 Mac 上播放音频文件时,没有任何反应。几乎就像文件是空的。我尝试将它们另存为 .mp3 和 .wav 但没有成功。我的代码如下:

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

import android.media.MediaRecorder;
import android.os.Environment;

public class AudioRecorder {

    private MediaRecorder recorder = new MediaRecorder();

    private File outfile = null;

    public AudioRecorder(){}

    public void startRecording(String audioFile) throws IOException {
        String state = android.os.Environment.getExternalStorageState();
        if(!state.equals(android.os.Environment.MEDIA_MOUNTED))  {
            throw new IOException("SD Card is not mounted.  It is " + state + ".");
        }

        // make sure the directory we plan to store the recording in exists
        File directory = new File(path).getParentFile();
        if (!directory.exists() && !directory.mkdirs()) {
            throw new IOException("Path to file could not be created.");
        }
        try{
            File storageDir = new File(Environment
                    .getExternalStorageDirectory(), "/audio/");
            storageDir.mkdir();
            outfile=File.createTempFile(audioFile, ".wav",storageDir);
            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            recorder.setOutputFile(outfile.getAbsolutePath());
        }catch(IOException e){
            e.printStackTrace();
        }

        try{
            recorder.prepare();
        }catch(IllegalStateException e){
            e.printStackTrace();
        }

        recorder.start();
        }

    public void stop() throws IOException {
        recorder.stop();
        recorder.release();
        }
}

我的活动:

/**
 * Recording Activity
 */


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

import com.seekika.android.app.helpers.AudioRecorder;

import android.app.Activity;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;

public class Record extends Activity {

    private static final String TAG="RecordActivity";

    private int SETTINGS=Menu.FIRST;
    private int LOGOUT=Menu.FIRST + 1;
    private int EXIT=Menu.FIRST + 2;

    //components
    private Button mBtnStartRecording;
    private Button mBtnStopRecording;

    private Chronometer mChronometer;


    private String audioFileName="";
    final AudioRecorder recorder = new AudioRecorder();

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recordstory);
        initComponents();
    }

    public void initComponents(){
        mChronometer=(Chronometer)findViewById(R.id.chrono);
        mBtnStopRecording=(Button)findViewById(R.id.btn_stop_recording);
        mBtnStopRecording.setEnabled(false);

        mBtnStopRecording.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //stop timer
                stopRecording();
                //stop recording and save audio file to SD card

            }
        });

        mBtnStartRecording=(Button)findViewById(R.id.btn_start_recording);
        mBtnStartRecording.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                startRecording();
                mBtnStartRecording.setEnabled(false);
                mBtnStopRecording.setEnabled(true);
                //start recording audio
                //start timer

            }
        });

    }

    private void startRecording(){
        mChronometer.setBase(SystemClock.elapsedRealtime());
        mChronometer.start();


        try{
            String myRecording="Seekika-" + System.currentTimeMillis();
            Log.i(TAG, "Start Recording");
            recorder.startRecording(myRecording);
        }catch(IOException e){
            Log.e(TAG,"IOException error");
            e.printStackTrace();
        }

    }

    private void stopRecording(){
        mChronometer.stop();

        try{
            recorder.stop();
        }catch(IOException e){
            e.printStackTrace();
        }

    }


}

I'm developing an android (2.2) app to record audio. The code seems to run fine and even saves the files on the SD Card, but when I try and play the audio files on my Mac nothing happens. Almost like the files are empty. I've tried saving them as .mp3 and .wav but no luck. My code is below:

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

import android.media.MediaRecorder;
import android.os.Environment;

public class AudioRecorder {

    private MediaRecorder recorder = new MediaRecorder();

    private File outfile = null;

    public AudioRecorder(){}

    public void startRecording(String audioFile) throws IOException {
        String state = android.os.Environment.getExternalStorageState();
        if(!state.equals(android.os.Environment.MEDIA_MOUNTED))  {
            throw new IOException("SD Card is not mounted.  It is " + state + ".");
        }

        // make sure the directory we plan to store the recording in exists
        File directory = new File(path).getParentFile();
        if (!directory.exists() && !directory.mkdirs()) {
            throw new IOException("Path to file could not be created.");
        }
        try{
            File storageDir = new File(Environment
                    .getExternalStorageDirectory(), "/audio/");
            storageDir.mkdir();
            outfile=File.createTempFile(audioFile, ".wav",storageDir);
            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            recorder.setOutputFile(outfile.getAbsolutePath());
        }catch(IOException e){
            e.printStackTrace();
        }

        try{
            recorder.prepare();
        }catch(IllegalStateException e){
            e.printStackTrace();
        }

        recorder.start();
        }

    public void stop() throws IOException {
        recorder.stop();
        recorder.release();
        }
}

My Activity:

/**
 * Recording Activity
 */


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

import com.seekika.android.app.helpers.AudioRecorder;

import android.app.Activity;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;

public class Record extends Activity {

    private static final String TAG="RecordActivity";

    private int SETTINGS=Menu.FIRST;
    private int LOGOUT=Menu.FIRST + 1;
    private int EXIT=Menu.FIRST + 2;

    //components
    private Button mBtnStartRecording;
    private Button mBtnStopRecording;

    private Chronometer mChronometer;


    private String audioFileName="";
    final AudioRecorder recorder = new AudioRecorder();

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recordstory);
        initComponents();
    }

    public void initComponents(){
        mChronometer=(Chronometer)findViewById(R.id.chrono);
        mBtnStopRecording=(Button)findViewById(R.id.btn_stop_recording);
        mBtnStopRecording.setEnabled(false);

        mBtnStopRecording.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //stop timer
                stopRecording();
                //stop recording and save audio file to SD card

            }
        });

        mBtnStartRecording=(Button)findViewById(R.id.btn_start_recording);
        mBtnStartRecording.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                startRecording();
                mBtnStartRecording.setEnabled(false);
                mBtnStopRecording.setEnabled(true);
                //start recording audio
                //start timer

            }
        });

    }

    private void startRecording(){
        mChronometer.setBase(SystemClock.elapsedRealtime());
        mChronometer.start();


        try{
            String myRecording="Seekika-" + System.currentTimeMillis();
            Log.i(TAG, "Start Recording");
            recorder.startRecording(myRecording);
        }catch(IOException e){
            Log.e(TAG,"IOException error");
            e.printStackTrace();
        }

    }

    private void stopRecording(){
        mChronometer.stop();

        try{
            recorder.stop();
        }catch(IOException e){
            e.printStackTrace();
        }

    }


}

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

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

发布评论

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

评论(2

南冥有猫 2024-11-12 08:32:14

不知道你是否可以使用这个,但这对我有用:

public void recordAudio(String fileName) {
    final MediaRecorder recorder = new MediaRecorder();
    ContentValues values = new ContentValues(3);
    values.put(MediaStore.MediaColumns.TITLE, fileName);
    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
    recorder.setOutputFile("/sdcard/sound/" + fileName);
    try {
      recorder.prepare();
    } catch (Exception e){
        e.printStackTrace();
    }

    final ProgressDialog mProgressDialog = new ProgressDialog(MyActivity.this);
    mProgressDialog.setTitle(R.string.lbl_recording);
    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    mProgressDialog.setButton("Stop recording", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        mProgressDialog.dismiss();
        recorder.stop();
        recorder.release();
        }
    });

    mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
        public void onCancel(DialogInterface p1) {
            recorder.stop();
            recorder.release();
        }
    });
    recorder.start();
    mProgressDialog.show();
}

Don' know if you can use this, but this works for me:

public void recordAudio(String fileName) {
    final MediaRecorder recorder = new MediaRecorder();
    ContentValues values = new ContentValues(3);
    values.put(MediaStore.MediaColumns.TITLE, fileName);
    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
    recorder.setOutputFile("/sdcard/sound/" + fileName);
    try {
      recorder.prepare();
    } catch (Exception e){
        e.printStackTrace();
    }

    final ProgressDialog mProgressDialog = new ProgressDialog(MyActivity.this);
    mProgressDialog.setTitle(R.string.lbl_recording);
    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    mProgressDialog.setButton("Stop recording", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        mProgressDialog.dismiss();
        recorder.stop();
        recorder.release();
        }
    });

    mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
        public void onCancel(DialogInterface p1) {
            recorder.stop();
            recorder.release();
        }
    });
    recorder.start();
    mProgressDialog.show();
}
土豪我们做朋友吧 2024-11-12 08:32:14
 recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
 recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

这意味着您想要创建(记录)一个 OUTPUTFORMAT 为 RAW_AMR 的文件

,但仅提供文件名为 .mp3 的文件路径,我想是不行的。这可能就是问题所在。

检查创建的项目的详细信息(长按文件并单击详细信息),它提供有关文件的一些信息,例如 Windows 右键单击​​属性。

 recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
 recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

This means that you want to create (record) a file with OUTPUTFORMAT as RAW_AMR

But just providing a file path with a file name as .mp3 I guess would not do. And that might be the problem.

Check details of the items create (long press on the file and click details) it gives some info about the file, like the windows right click properties.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文