我想从手机的麦克风中捕捉声音,并在屏幕上实时显示每 1000 个样本的平均值。这是我到目前为止的代码,但我没有在屏幕上看到任何值,它是空白的。我究竟做错了什么?我是 Android 开发的新手,所以任何帮助都会有所帮助。
import android.os.Bundle;
import android.widget.TextView;
import android.app.Activity;
import android.media.AudioRecord;
import android.media.MediaRecorder.AudioSource;
import android.media.AudioFormat;
public class MainActivity extends Activity {
public boolean recording; //variable to start or stop recording
public TextView averagevalue; //text to appear on screen
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
averagevalue = (TextView) findViewById(R.id.text1);
}
public void Record(){
AudioRecord recorder;
short audioData[];
int bufferSize;
bufferSize=AudioRecord.getMinBufferSize(44100,AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT); //get the buffer size to use with this audio record
recorder = new AudioRecord (AudioSource.MIC,44100,AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,bufferSize); //instantiate the AudioRecorder
recording=true; //variable to use start or stop recording
audioData = new short [bufferSize]; //short array that pcm data is put into.
while (recording) { //loop while recording is needed
if (recorder.getState()==android.media.AudioRecord.STATE_INITIALIZED) // check to see if the recorder has initialized yet.
if (recorder.getRecordingState()==android.media.AudioRecord.RECORDSTATE_STOPPED)
recorder.startRecording(); //check to see if the Recorder has stopped or is not recording, and make it record.
else {
recorder.read(audioData,0,bufferSize); //read the PCM audio data into the audioData array
//analyze sound
int totalAbsValue = 0;
int samplesquantity = 1000;
short sample = 0;
float averageAbsValue = 0.0f;
for (int i = 0; i < samplesquantity; i += 1) {
sample = (short)audioData[i];
totalAbsValue += Math.abs(sample);
}
averageAbsValue = totalAbsValue / samplesquantity;
averagevalue.setText(Float.toString(averageAbsValue));
}//else recorder started
} //while recording
if (recorder.getState()==android.media.AudioRecord.RECORDSTATE_RECORDING) recorder.stop(); //stop the recorder before ending the thread
recorder.release(); //release the recorders resources
recorder=null; //set the recorder to be garbage collected.
}
}
这是 XML 文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"/>
</RelativeLayout>