2013/05/15

Android 控制媒體音量

最近同學有遇到控制Android的音量大小,剛好之前有接觸過AudioMange這個類別,不過當初的範例好像刪掉了!
所以又找了一篇文章來參考參考摟XDD






Android音量控制主要是透過AudioManger這個類別來控制的。我們可以用AudioManger來控制鈴聲大小及音樂大小等


本範例是控制媒體音量大小,且不顯示在螢幕上,如果需要顯示在螢幕上可以將
audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,AudioManager.ADJUST_RAISE, AudioManager.FLAG_VIBRATE);
改成
audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);


首先取得系統的AUDIO_SERVICE服務
audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);

接著將btn_Raise點擊動作設定為音量升高
 private Button.OnClickListener listenerRAISE = new OnClickListener() {
  @Override
  public void onClick(View v) {
   audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
     AudioManager.ADJUST_RAISE, AudioManager.FLAG_VIBRATE);
  }
 };

再來btn_Raise點擊動作設定為音量降低
 private Button.OnClickListener listenerLOWER = new OnClickListener() {
  @Override
  public void onClick(View v) {
   audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
     AudioManager.ADJUST_LOWER, AudioManager.FLAG_VIBRATE);
  }
 };



package com.example.audiocontrol;
package com.example.audiocontrol;

import android.app.Activity;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

 private AudioManager audioManager;
 private Button btn_Raise;
 private Button btn_Lower;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
  btn_Raise = (Button) findViewById(R.id.button1);
  btn_Lower = (Button) findViewById(R.id.button2);
  btn_Raise.setOnClickListener(listenerRAISE);
  btn_Lower.setOnClickListener(listenerLOWER);
 }

 private Button.OnClickListener listenerRAISE = new OnClickListener() {
  @Override
  public void onClick(View v) {
   audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
     AudioManager.ADJUST_RAISE, AudioManager.FLAG_VIBRATE);
  }
 };

 private Button.OnClickListener listenerLOWER = new OnClickListener() {
  @Override
  public void onClick(View v) {
   audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
     AudioManager.ADJUST_LOWER, AudioManager.FLAG_VIBRATE);
  }
 };
}


當我們觸發了音量增加時direction會等於1,當降低時direction會等於-1



參考資料:
http://www.eoeandroid.com/thread-79020-1-1.html