專案功能:能經由麥克風(MIC)讀取音量,並將數值顯示在TextView上
1. 新增專案
Project Name: voiceTest
Package Name: com.example.voicetest
Activity Name: MainActivity
SDK API: 15
2. 在TextView 新增 id
android:id="@+id/text1"
完整的main.xml如下:
3. 使用MediaRecorder來記錄聲音,並利用Handler來定時讀取音量的資訊,MainActivity.java完整程式列表。
package com.example.voicetest;
import java.io.IOException;
import android.media.AudioManager;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity {
private MediaRecorder mRecorder = null;
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
double ringerVol = mRecorder.getMaxAmplitude();
TextView tv = (TextView) findViewById(R.id.text1);
tv.setText(Double.toString(ringerVol));
handler.sendMessageDelayed(Message.obtain(), 300);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (mRecorder == null) {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOutputFile("/dev/null");
try {
mRecorder.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mRecorder.start();
}
handler.sendEmptyMessageDelayed(0, 1000);
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (mRecorder != null) {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
4.新增權限
5. 執行結果