Play sound either from external or internal speake

2019-09-02 06:35发布

Suppose I have a MediaPlayer class object which is playing some music. Now I want to change the music to play either from device's internal speaker or already plugged in earphone.

Let's say just by tapping a button. Is that possible?

1条回答
▲ chillily
2楼-- · 2019-09-02 07:07

I can't comment becuase I don't have enough reputation, so I'll post it.

Just do a small quick search: 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;}
         }
      }

      ...
   }
}
查看更多
登录 后发表回答