Android audioManager解决MediaPlayer AudioTrack 调节音量问题

在听筒模式下

am.setSpeakerphoneOn(false);   
setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);   
am.setMode(AudioManager.MODE_IN_CALL); 

我用Mediaplayer AudioTrack调节音量总是失败

at.setStereoVolume(vol, vol);   
player.setVolume(vol,vol);  

后来 决定用AudioManager来调节音量

AudioManager可以修改系统Android系统的音量

下面介绍几个AudioManager的几个音量调整方面的方法.

首先是得到AudioManager实例:

AudioManager am=(AudioManager)getSystemService(Context.AUDIO_SERVICE);

调整音量方法有两种,一种是渐进式,即像手动按音量键一样,一步一步增加或减少,另一种是直接设置音量值.

1、渐进式 

public void adjustStreamVolume (int streamType, int direction, int flags)   
  
am.adjustStreamVolume (AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);  

解释一下三个参数

  1. 第一个streamType是需要调整音量的类型,这里设的是媒体音量,可以是:
  2. STREAM_ALARM 警报
  3. STREAM_MUSIC 音乐回放即媒体音量
  4. STREAM_NOTIFICATION 窗口顶部状态栏Notification,
  5. STREAM_RING 铃声
  6. STREAM_SYSTEM 系统
  7. STREAM_VOICE_CALL 通话
  8. STREAM_DTMF 双音多频,不是很明白什么东西
  9. 第二个direction,是调整的方向,增加或减少,可以是:
  10. ADJUST_LOWER 降低音量
  11. ADJUST_RAISE 升高音量
  12. ADJUST_SAME 保持不变,这个主要用于向用户展示当前的音量
  13. 第三个flags是一些附加参数,只介绍两个常用的
  14. FLAG_PLAY_SOUND 调整音量时播放声音
  15. FLAG_SHOW_UI 调整时显示音量条,就是按音量键出现的那个

2、直接设置音量值的方法: 

public void setStreamVolume (int streamType, int index, int flags)   
  
am.setStreamVolume(AudioManager.STREAM_MUSIC, am.getStreamMaxVolume(AudioManager.STREAM_MUSIC), AudioManager.FLAG_PLAY_SOUND);   
am.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL);//得到听筒模式的最大值   
am.getStreamVolume(AudioManager.STREAM_VOICE_CALL);//得到听筒模式的当前值  

第一个和第三个参数与上面的相同

第二个参数是一个音量的int值,getStreamMaxVolume(int streamType)得到的是该类型音量的最大值,可以根据这个值计算你需要的音量,我这里直接调到最大.

最后我的代码:

package com.lp;   
  
  
import java.io.File;   
import java.io.FileInputStream;   
import java.io.FileNotFoundException;   
import java.io.IOException;   
import java.io.InputStream;   
  
import Android.app.Activity;   
import Android.content.Context;   
import Android.media.AudioFormat;   
import Android.media.AudioManager;   
import Android.media.AudioTrack;   
import Android.os.Bundle;   
import Android.view.View;   
import Android.view.View.OnClickListener;   
import Android.widget.Button;   
import Android.widget.SeekBar;   
/**  
 * AudioTrack 播放音频 如wav格式  
 * 并允许调节音量  
 * @author Administrator  
 *  
 */  
public class MainActivity5 extends Activity {   
    private Button play;   
    private Button stop;   
    private SeekBar soundValue;   
       
    private AudioTrack at;   
    private AudioManager am;   
    @Override  
    public void onCreate(Bundle savedInstanceState) {   
        super.onCreate(savedInstanceState);   
        setContentView(R.layout.main_sk);   
        am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);   
        play = (Button)findViewById(R.id.main_sk_play);   
        stop = (Button)findViewById(R.id.main_sk_stop);   
        soundValue = (SeekBar)findViewById(R.id.skbVolume);   
        setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);   
        play.setOnClickListener(new OnClickListener() {   
            @Override  
            public void onClick(View v) {   
                   
                if(am.isSpeakerphoneOn()){   
                    am.setSpeakerphoneOn(false);   
                }   
                //setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);   
                am.setMode(AudioManager.MODE_IN_CALL);   
                System.out.println(am.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL));   
                System.out.println("&&&&&&&&&&&&&");   
                System.out.println(am.getStreamVolume(AudioManager.STREAM_VOICE_CALL));   
                //am.setStreamVolume(streamType, index, flags)   
                   
                int bufferSizeInBytes = AudioTrack.getMinBufferSize(44100, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);   
                   
                if(at==null){   
                    at = new AudioTrack(AudioManager.STREAM_VOICE_CALL, 44100, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSizeInBytes, AudioTrack.MODE_STREAM);   
                    System.out.println("22222");   
                    //at.setStereoVolume(100f, 100f);   
                    at.setStereoVolume(0.7f, 0.7f);//设置当前音量大小   
                    new AudioTrackThread().start();   
                }else{   
                    if(at.getPlayState()==AudioTrack.PLAYSTATE_PLAYING){   
                        System.out.println("111111111");   
                    }else{   
                        System.out.println("33333");   
                        at = new AudioTrack(AudioManager.STREAM_VOICE_CALL, 44100, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSizeInBytes, AudioTrack.MODE_STREAM);   
                        new AudioTrackThread().start();   
                    }   
                }   
                   
            }   
        });   
           
        stop.setOnClickListener(new OnClickListener() {   
               
            @Override  
            public void onClick(View v) {   
                if(at.getPlayState()==AudioTrack.PLAYSTATE_PLAYING){   
                    try{   
                        at.stop();   
                    }catch (IllegalStateException e)   
                    {   
                        e.printStackTrace();   
                    }   
                    at.release();   
                    am.setMode(AudioManager.MODE_NORMAL);   
                }   
            }      
        });   
           
//        soundValue.setMax(100);//音量调节的极限   
//        soundValue.setProgress(70);//设置seekbar的位置值   
        soundValue.setMax(am.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL));   
        soundValue.setProgress(am.getStreamVolume(AudioManager.STREAM_VOICE_CALL));   
           
        soundValue.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {   
               
            @Override  
            public void onStopTrackingTouch(SeekBar seekBar) {   
//              float vol=(float)(seekBar.getProgress())/(float)(seekBar.getMax());   
//              System.out.println(vol);   
//              at.setStereoVolume(vol, vol);//设置音量   
                am.setStreamVolume(AudioManager.STREAM_VOICE_CALL, seekBar.getProgress(), AudioManager.FLAG_PLAY_SOUND);   
            }   
               
            @Override  
            public void onStartTrackingTouch(SeekBar seekBar) {   
                // TODO Auto-generated method stub   
            }   
               
            @Override  
            public void onProgressChanged(SeekBar seekBar, int progress,   
                    boolean fromUser) {   
                // TODO Auto-generated method stub   
            }   
        });   
    }   
       
    class AudioTrackThread extends Thread{     
  
        @Override  
        public void run() {   
            byte[] out_bytes = new byte[44100];   
               
            InputStream is = getResources().openRawResource(R.raw.start);       
            int length ;   
            try{   
                at.play();   
            }catch (IllegalStateException e)   
            {   
                e.printStackTrace();   
            }   
            try {   
                while((length = is.read(out_bytes))!=-1){   
                    //System.out.println(length);   
                    at.write(out_bytes, 0, length);   
                }   
            } catch (IOException e) {   
                e.printStackTrace();   
            }   
            if(at.getPlayState()==AudioTrack.PLAYSTATE_PLAYING){   
                try{   
                    at.stop();   
                }catch (IllegalStateException e)   
                {   
                    e.printStackTrace();   
                }   
                at.release();   
                am.setMode(AudioManager.MODE_NORMAL);   
            }   
        }   
           
    }   
                   
}  

当然还要添加权限

<uses-permission Android:name="android.permission.MODIFY_AUDIO_SETTINGS" />   
<uses-permission Android:name="android.permission.WRITE_EXTERNAL_STORAGE" />   
<uses-permission Android:name="android.permission.RECORD_AUDIO" />


你可能感兴趣的:(Android audioManager解决MediaPlayer AudioTrack 调节音量问题)