以编程方式从外部或内部扬声器播放声音

时间:2016-05-17 15:44:32

标签: android android-audiomanager

假设我有一个正在播放音乐的 MediaPlayer 类对象。现在我想将音乐更改为从设备的内置扬声器或已插入耳机播放。

我们只需按一下按钮即可。这可能吗?

1 个答案:

答案 0 :(得分:1)

我无法发表评论,因为我没有足够的声誉,所以我会发布它。

只需进行一次小型快速搜索:Switching between earpiece and speaker

import android.media.MediaPlayer;
import android.media.AudioManager;

public class MediaPlayer {
   private MediaPlayer mMediaPlayer;
   private AudioManager mAudioManager;
   private Button mButton;
   private boolean isPlayingOnSpeaker = false;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      ...

      mMediaPlayer = MediaPlayer.create(this, R.raw.song);
      mMediaPlayer.prepareAsync();
      mMediaPlayer.start();

      mButton = (Button) findViewById(R.id.button);

      mButton.setOnClickListener(new View.OnClickListener() {
      @Override
         public void onClick(View v) {
            context = getActivity().getBaseContext();

            mAudioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);        
            mAudioManager.setMode(AudioManager.STREAM_MUSIC);

            if(isPlayingOnSpeaker)
               {mAudioManager.setSpeakerphoneOn(false); isPlayingOnSpeaker=false;}
            else {mAudioManager.setSpeakerphoneOn(true); isPlayingOnSpeaker=true;}
         }
      }

      ...
   }
}