首先,如果下面的代码看起来很糟糕并且格式不正确,我应该道歉。我对编程知之甚少,所以我从不同来源获取了一些程序并将它们组合在一起。
在应用程序中,我想显示来自手机麦克风的声音的频率(使用过零方法)。 当我运行应用程序时,它会显示一次频率,但不会更新它。
1)您能否帮我找到在同一文本框中重复显示频率值的解决方案(或在屏幕上更合适的小部件中)?
* 2)是否可以在没有按钮的情况下制作此应用程序。我的意思是应用程序在启动后立即显示频率?*已解决
谢谢!
package alar.alar.com.frequencyFreq;
import android.app.Activity;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final int RECORDER_SAMPLERATE = 8000;
private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO;
private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
public AudioRecord recorder = null;
int numCrossing, p;
short audioData[];
public int frequency;
public boolean recording;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE,
RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING);
recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
RECORDER_SAMPLERATE, RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING, bufferSize);
recorder.startRecording();
recording = true;
audioData = new short[bufferSize];
recorder.read(audioData, 0, bufferSize);
numCrossing = 0;
for (p = 0; p < bufferSize - 1; p++) {
if ((audioData[p] > 0 && audioData[p + 1] <= 0) ||
(audioData[p] < 0 && audioData[p + 1] >= 0)) {
numCrossing++;
}
}
frequency = (8000 / bufferSize) * (numCrossing / 2);
TextView textView = (TextView) this.findViewById(R.id.textView);
textView.setText(String.valueOf(frequency));
}//onCreate
}//activity
答案 0 :(得分:0)
试试这个
private Timer timer;
private TimerTask timerTask;
public void onPause(){ super.onPause();
timer.cancel();
} public void onResume(){
super.onResume();
try {
timer = new Timer(); timerTask = new TimerTask() {
@Override
public void run() {
//your method }
};
timer.schedule(timerTask, 1000, 1000); } catch (IllegalStateException e){ android.util.Log.i("Damn", "resume error"); } }