0

我正在尝试将通过麦克风获得的音频样本传递给扬声器
这是我正在使用的代码,使用我在此处获得的建议

public class MainActivity extends Activity {
    AudioManager am = null;
    AudioRecord record =null;
    AudioTrack track =null;
    final int SAMPLE_FREQUENCY = 44100;
    final int SIZE_OF_RECORD_ARRAY = 1024;  // 1024 ORIGINAL
    final int WAV_SAMPLE_MULTIPLICATION_FACTOR = 1;
    int i= 0;
    boolean isPlaying = true;
    class MyThread extends Thread{
        private boolean passThroughMode = true;
        /*
        @Override
        public void run(){
            recordAndPlay(passThroughMode);
        }
        */

        MyThread(){
            super();
        }

        MyThread(boolean newPTV){
            this.passThroughMode = newPTV;
        }

        @Override
        public void run(){
            short[] lin = new short[SIZE_OF_RECORD_ARRAY];
            int num = 0;
            // am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
            // am.setMode(AudioManager.MODE_IN_COMMUNICATION);
            record.startRecording();
            track.play();
            // while (passThroughMode) {
            while (!isInterrupted()) {
                num = record.read(lin, 0, SIZE_OF_RECORD_ARRAY);
                for(i=0;i<lin.length;i++)
                    lin[i] *= WAV_SAMPLE_MULTIPLICATION_FACTOR; 
                track.write(lin, 0, num);
            }
        }
        /*
        public void stopThread(){
            passThroughMode = false;
        }
        */
    }

    MyThread newThread;

    private void init() {
        int min = AudioRecord.getMinBufferSize(SAMPLE_FREQUENCY, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
        record = new AudioRecord(MediaRecorder.AudioSource.VOICE_COMMUNICATION, SAMPLE_FREQUENCY, AudioFormat.CHANNEL_IN_MONO,
                                 AudioFormat.ENCODING_PCM_16BIT, min);
        int maxJitter = AudioTrack.getMinBufferSize(SAMPLE_FREQUENCY, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
        track = new AudioTrack(AudioManager.MODE_IN_COMMUNICATION, SAMPLE_FREQUENCY, AudioFormat.CHANNEL_OUT_MONO,
                               AudioFormat.ENCODING_PCM_16BIT, maxJitter, AudioTrack.MODE_STREAM);
     }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setVolumeControlStream(AudioManager.MODE_IN_COMMUNICATION);
        init();
        newThread = new MyThread(true);
        newThread.start();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
/*  
    private void recordAndPlay(boolean pTM) {
        short[] lin = new short[SIZE_OF_RECORD_ARRAY];
        int num = 0;
        am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        am.setMode(AudioManager.MODE_IN_COMMUNICATION);
        record.startRecording();
        track.play();
        while (pTM) {
            num = record.read(lin, 0, SIZE_OF_RECORD_ARRAY);
            for(i=0;i<lin.length;i++)
                lin[i] *= WAV_SAMPLE_MULTIPLICATION_FACTOR; 
            track.write(lin, 0, num);
        }
    }
*/  
    public void passStop(View view){
        Button playBtn = (Button) findViewById(R.id.playBtn);  
        // /*
        if(!isPlaying){
            record.startRecording();
            track.play();
            isPlaying = true;
            playBtn.setText("Pause");
        }
        else{
           record.stop();
           track.pause();
           isPlaying=false;
           playBtn.setText("Pass through");
        }
        // */
    }

/*
    @SuppressWarnings("deprecation")
    @Override
    public void onDestroy(){
        newThread.stop();
    }
    */

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // android.os.Process.killProcess(android.os.Process.myPid());
        // killProcess(android.os.Process.myPid());
        // newThread.stopThread();
        newThread.interrupt();
    }
}

在第一次运行期间,程序运行良好,麦克风的声音传递到扬声器,当我按下返回按钮时,线程似乎也停止了,所以当应用程序退出时,传递停止。但是,如果我再次运行该应用程序,则不会发生传递。是否

newThread = new MyThread(true);
newThread.start();  

每次执行应用程序时都启动一个新线程(即调用 onCreate()),还是由于某种原因它会记住旧线程的状态?如何完全重置此应用程序,以便每次执行时都会启动一个全新的应用程序?

- - 编辑 - -

无中断的替代版本:

public class MainActivity extends Activity {
    AudioManager am = null;
    AudioRecord record =null;
    AudioTrack track =null;
    final int SAMPLE_FREQUENCY = 44100;
    final int SIZE_OF_RECORD_ARRAY = 1024;  // 1024 ORIGINAL
    final int WAV_SAMPLE_MULTIPLICATION_FACTOR = 1;
    int i= 0;
    boolean isPlaying = true;
    class MyThread extends Thread{
        private volatile boolean passThroughMode = true;
         /*
        @Override
        public void run(){
            recordAndPlay(passThroughMode);
        }
        // */


        // /*
        MyThread(){
            super();
        }

        MyThread(boolean newPTV){
            this.passThroughMode = newPTV;
        }
        // */

        // /*
        @Override
        public void run(){
            short[] lin = new short[SIZE_OF_RECORD_ARRAY];
            int num = 0;
            // am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
            // am.setMode(AudioManager.MODE_IN_COMMUNICATION);
            record.startRecording();
            track.play();
            while (passThroughMode) {
            // while (!isInterrupted()) {
                num = record.read(lin, 0, SIZE_OF_RECORD_ARRAY);
                for(i=0;i<lin.length;i++)
                    lin[i] *= WAV_SAMPLE_MULTIPLICATION_FACTOR; 
                track.write(lin, 0, num);
            }
            record.stop();
            track.stop();
            record.release();
            track.release();
        }
        // */

        // /*
        public void stopThread(){
            passThroughMode = false;
        }
        // */
    }

    MyThread newThread;

    private void init() {
        int min = AudioRecord.getMinBufferSize(SAMPLE_FREQUENCY, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
        record = new AudioRecord(MediaRecorder.AudioSource.VOICE_COMMUNICATION, SAMPLE_FREQUENCY, AudioFormat.CHANNEL_IN_MONO,
                                 AudioFormat.ENCODING_PCM_16BIT, min);
        int maxJitter = AudioTrack.getMinBufferSize(SAMPLE_FREQUENCY, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
        track = new AudioTrack(AudioManager.MODE_IN_COMMUNICATION, SAMPLE_FREQUENCY, AudioFormat.CHANNEL_OUT_MONO,
                               AudioFormat.ENCODING_PCM_16BIT, maxJitter, AudioTrack.MODE_STREAM);
     }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setVolumeControlStream(AudioManager.MODE_IN_COMMUNICATION);
        init();
        Log.d("MYLOG", "onCreate() called");

        //Toast.makeText(getApplicationContext(), "HERE", Toast.LENGTH_SHORT).show();
        // newThread = new MyThread(true); // -> Moved this to onResume();
        // newThread = new MyThread();
        // newThread.start(); // -> Moved this to onResume()
        // newThread.run();
    }

    @Override
    protected void onResume(){
        super.onResume();
        // newThread.stopThread();
        Log.d("MYLOG", "onResume() called");
        newThread = new MyThread(true);
        newThread.start(); 
    }

    @Override
    protected void onPause(){
        super.onPause();
        Log.d("MYLOG", "onPause() called");
        newThread.stopThread();
        // android.os.Process.killProcess(android.os.Process.myPid());
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

     /* 
    private void recordAndPlay(boolean pTM) {
        short[] lin = new short[SIZE_OF_RECORD_ARRAY];
        int num = 0;
        am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        am.setMode(AudioManager.MODE_IN_COMMUNICATION);
        record.startRecording();
        track.play();
        while (pTM) {
            num = record.read(lin, 0, SIZE_OF_RECORD_ARRAY);
            for(i=0;i<lin.length;i++)
                lin[i] *= WAV_SAMPLE_MULTIPLICATION_FACTOR; 
            track.write(lin, 0, num);
        }
    }
// */   
    public void passStop(View view){
        Button playBtn = (Button) findViewById(R.id.playBtn);  
        // /*
        if(!isPlaying){
            record.startRecording();
            track.play();
            isPlaying = true;
            playBtn.setText("Pause");
        }
        else{
           record.stop();
           track.pause();
           isPlaying=false;
           playBtn.setText("Pass through");
        }
        // */
    }

     /*
    @SuppressWarnings("deprecation")
    @Override
    public void onDestroy(){
        // newThread.stop();
        newThread.stopThread();
    }
    // */

    // /*
    @Override
    protected void onDestroy() {
        super.onDestroy();
        newThread.stopThread();
        // android.os.Process.killProcess(android.os.Process.myPid());
        // killProcess(android.os.Process.myPid());
        // newThread.interrupt();
         Log.d("MYLOG", "onDestroy() called");
    }
    // */
}  

---编辑2---

08-20 20:57:58.266: D/MYLOG(21936): onResume() called
08-20 20:57:58.266: W/dalvikvm(21936): threadid=11: thread exiting with uncaught exception (group=0x416f5700)
08-20 20:57:58.266: E/AndroidRuntime(21936): FATAL EXCEPTION: Thread-897
08-20 20:57:58.266: E/AndroidRuntime(21936): java.lang.IllegalStateException: startRecording() called on an uninitialized AudioRecord.
08-20 20:57:58.266: E/AndroidRuntime(21936):    at android.media.AudioRecord.startRecording(AudioRecord.java:517)
08-20 20:57:58.266: E/AndroidRuntime(21936):    at com.example.mypassthrough.MainActivity$MyThread.run(MainActivity.java:54)
08-20 20:57:58.286: D/MYLOG(21936): onPause() called
08-20 20:57:58.366: D/MYLOG(21936): onDestroy() called
4

2 回答 2

1

Thread不,跨Activity实例的对象没有状态持久性。但是,您错误地假设每次运行应用程序时都会获得一个新的 Activity。活动将持续存在,直到 Android 操作系统决定删除它们。只有在您再次进入应用程序时才会创建一个新实例 - 否则,您将获得与以前相同的 Activity,并且onCreate()在这种情况下不会再次调用

换句话说,您应该使用onResume()andonPause()来代替 init/deinit。请查看生命周期页面了解更多详情。

编辑:另一个问题是你interrupt()用来控制线程的流程。这并不总是一个好主意,因为interrupt()它有几个副作用,甚至可能不会true根据线程的情况将中断状态设置为。您应该改用“shouldStop”字段,因为那时语义是由您设置的。

请注意,这个“shouldStop”字段应该是一个字段,将其作为参数传递是行不通的。你应该有这样的东西MyThread

    @Override
    public void run(){
        short[] lin = new short[SIZE_OF_RECORD_ARRAY];
        int num = 0;
        record.startRecording();
        track.play();
        while (passThroughMode) {
            num = record.read(lin, 0, SIZE_OF_RECORD_ARRAY);
            for(i=0;i<lin.length;i++)
                lin[i] *= WAV_SAMPLE_MULTIPLICATION_FACTOR; 
            track.write(lin, 0, num);
        }
    }

并且,在onPause()

@Override
protected void onPause() {
    super.onPause();
    newThread.stopThread();
}

如果线程仍然没有停止,那么一个调用正在阻塞它,这对于 I/O 操作是典型的。

编辑 2:另一个问题是你没有stop()release()你的AudioTrackand AudioRecordwhile 播放器线程被关闭(在while循环之后)。使用与 I/O 相关的东西时的经验法则是,它通常附加到“本机”资源,这需要明确的“手动”释放(有时是分配)。在这些情况下,您应该始终检查类 API。

编辑 3: ...并且该MyThread实例以及您的所有其他资源都应该在 中完全onResume()初始化,包括在那里创建新实例,而不是在 on 中onCreate()

于 2013-08-20T10:13:34.637 回答
0

您的线程是一个内部类,它具有并使用对外部类的引用,MainActivity. 这样,线程的第二个实例的运行方式可能与第一个不同,即使新线程对象本身没有从前一个实例继承任何内容。正如@TheTerribleSwiftTomato 所说,您的活动可能会持续存在。

于 2013-08-20T10:15:21.597 回答