0

私の場合は MediaRecorder である、メモリからオブジェクトを取得する方法を知りたいです。これが私のクラスです:

ミミッククラス:

public class MyMic  {

    MediaRecorder recorder2;
    File file;
    private Context c;

    public MyMic(Context context){
        this.c=context;
        recorder2=  new MediaRecorder();
    }

    private void stopRecord() throws IOException {
        recorder2.stop();
        recorder2.reset();
        recorder2.release();
    }

    private void startRecord() {

        recorder2.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder2.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        recorder2.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        recorder2.setOutputFile(file.getPath());
        try {
            recorder2.prepare();
            recorder2.start();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

私のレシーバークラス:

public class MyReceiver extends BroadcastReceiver {

    private Context c;
    private MyMic myMic;
    @Override
    public void onReceive(Context context, Intent intent) {
        this.c=context;
        myMic = new MyMic(c);
        if(my condition = true){
        myMic.startRecord();
        }else

        myMic.stopRecord();
    }
}

したがって、それを呼び出しstartRecord()ているときに新しいものを作成しMediaRecorderますが、クラスを2回インスタンス化すると、オブジェクトを取得できません。MediaRecorder彼の住所で私のものを取り戻せますか.

4

1 に答える 1

1

次のように startRecord() メソッド内ではなく、作成するクラスのコンストラクター内に MediaRecorder のコンストラクターを配置する必要があります。

public class MyMic  {

MediaRecorder recorder2;
File file;
private Context c;


public MyMic(Context context){
    this.c=context;
    recorder2=  new MediaRecorder();

}


private void stopRecord() throws IOException {
    recorder2.stop();
    recorder2.reset();
    recorder2.release();

}


private void startRecord() {

    recorder2.setAudioSource(MediaRecorder.AudioSource.MIC);
    recorder2.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    recorder2.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    recorder2.setOutputFile(file.getPath());
    try {
        recorder2.prepare();
        recorder2.start();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}



}

また、コンストラクタ内のロジックで何をしようとしているのかを正確に理解することはできませんが、おそらくあなたのやり方でやるべきではありません。記録を開始/停止するたびにクラスの新しいインスタンスを作成する必要があるように、クラスを作成しないでください。最終目標は、一度インスタンス化して参照を保持するオブジェクトである必要があります。これにより、好きなときに開始/停止を呼び出すことができます。

このクラスを内部から使用しているアクティビティ (または他の Android 構造) を投稿できますか? もしそうなら、私はあなたがよりきれいな方法で2つを結びつけるのを手伝うことができます.

于 2012-06-12T16:14:23.413 に答える