假设我有一个正在播放音乐的 MediaPlayer 类对象。现在我想将音乐更改为从设备的内置扬声器或已插入耳机播放。
我们只需按一下按钮即可。这可能吗?
答案 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;}
}
}
...
}
}