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. 執行結果
音量是dbm指的是頻率的震幅,雖然以電壓的高低來看是指音量的大小,但是怕的是震幅是使用電壓的大小來計算,所以可以先測測看相同電壓的各階層為準位,是否音量為不同大小!
回覆刪除電壓偏移量
回覆刪除