Android: record decibel from microphone

荒凉一梦 提交于 2019-12-08 12:22:55

问题


i've got problem on implementing this functionality in Android... i need only to output the decibel redorded from the microphone, and it's a thing that i can't understand:

public class Noise extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    MediaRecorder recorder=new MediaRecorder();
    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    Timer timer=new Timer();
    timer.scheduleAtFixedRate(new RecorderTask(recorder), 0, 500);
}
private class RecorderTask extends TimerTask{
    TextView risultato=(TextView) findViewById(R.id.risultato_recorder);
    private MediaRecorder recorder;
    public RecorderTask(MediaRecorder recorder){
        this.recorder = recorder;
    }
    public void run(){
        risultato.setText(""+recorder.getMaxAmplitude());
    }
}
}

In the textview, the result is printed the first time only, and it's 0, and then the app crash with: 11-29 14:43:27.133: E/AndroidRuntime(25785): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

I've searched around, but i can't find a comprehensive example... only examples with a lot of things and class that i don't need. can i fix this problem?


回答1:


UI components can only be modified from the UI thread.

Your task is running in a background thread, so you need to force the TextView update to be done in the UI thread. You can achieve it with the Activity.runOnUiThread method.

Try this:

public void run(){
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            risultato.setText("" + recorder.getMaxAmplitude());
        }
    });
}

instead of

public void run(){
    risultato.setText(""+recorder.getMaxAmplitude());
}


来源:https://stackoverflow.com/questions/13627284/android-record-decibel-from-microphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!