有時候,程式需要管理系統音量,或者直接讓系統靜音,這就可以藉助AudioManager來實現。在通過getSystemService(Service.AUDIO_SERVICE)方法擷取系統音頻管理器(AudioManager)後,就可以調用AudioManager如下常用方法控制手機音頻了:
下面用一個簡單樣本來示範AudioManager的控制手機音頻,代碼如下:
Activity:
package com.guyun.audiotest;import android.app.Activity;import android.app.Service;import android.media.AudioManager;import android.media.MediaPlayer;import android.os.Bundle;import android.view.View;import android.widget.CompoundButton;import android.widget.CompoundButton.OnCheckedChangeListener;import android.widget.ToggleButton;public class AudioTestActivity extends Activity {// 聲明AudioManager對象private AudioManager aManager;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_audio_test);// 擷取系統的音頻服務aManager = (AudioManager) getSystemService(Service.AUDIO_SERVICE);// 獲得ToggleButton按鈕ToggleButton tb = (ToggleButton) findViewById(R.id.activity_audio_test_tb);tb.setOnCheckedChangeListener(new OnCheckedChangeListener() {@Overridepublic void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {// 指定調節音樂的音頻,根據isChecked確定是否需要靜音aManager.setStreamMute(AudioManager.STREAM_MUSIC, isChecked);}});}public void click(View v) {switch (v.getId()) {case R.id.activity_audio_test_btn_play:// 初始化MediaPlayer對象,準備播放音樂MediaPlayer mplayer = MediaPlayer.create(AudioTestActivity.this,R.raw.girl);// 設定迴圈播放mplayer.setLooping(true);// 開始播放mplayer.start();break;case R.id.activity_audio_test_btn_up:// 指定調節音樂的音頻,增大音量,而且顯示音量圖形示意aManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);break;case R.id.activity_audio_test_btn_down:// 指定調節音樂的音頻,降低音量,而且顯示音量圖形示意aManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);}}}
布局XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <Button android:id="@+id/activity_audio_test_btn_play" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="click" android:text="播放" /> <Button android:id="@+id/activity_audio_test_btn_up" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="click" android:text="增大音量" /> <Button android:id="@+id/activity_audio_test_btn_down" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="click" android:text="減少音量" /> <ToggleButton android:id="@+id/activity_audio_test_tb" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textOff="設定為靜音" android:textOn="取消靜音" /></LinearLayout>