AudioManager音频管理器控制手机音频实例
AudioManager音频管理器 MediaPlayer ToggleButton
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.app.Service;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ToggleButton;
public class AudioTest extends Activity {
Button play;
Button up;
Button down;
AudioManager aManager;
ToggleButton mute;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio_test);
//获取系统的音频服务
aManager = (AudioManager) getSystemService(Service.AUDIO_SERVICE);
//获取界面中的三个按钮和一个ToggleButton控件
play = (Button) findViewById(R.id.play);
up = (Button) findViewById(R.id.up);
down = (Button) findViewById(R.id.down);
mute = (ToggleButton) findViewById(R.id.mute);
//为play按钮的单击事件绑定监听器
play.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 初始化MediaPlayer对象,准备播放音乐
MediaPlayer mPlayer = MediaPlayer.create(AudioTest.this, R.raw.earth);
//设置循环播放
mPlayer.setLooping(true);
//开始播放
mPlayer.start();
}
});
up.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 指定调节音乐的音频,增大音量,而且显示音量图形示意
aManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
}
});
down.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 指定调节音乐的音频,降低音量,而且显示音量图形示意
aManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
}
});
mute.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// 指定调解音乐的音频,根据isChecked确定是否需要静音
aManager.setStreamMute(AudioManager.STREAM_MUSIC, isChecked);
}
});
}
}