我有一个简单的 mp 服务来播放、暂停、恢复音频。一切正常。但是,昨晚我决定为用户添加一个将音频路由到耳机或扬声器的功能,并且一直在与mp.setAudioStreamType()
.
问题是在服务连接和 mp 创建时我无法更改它。我不想终止服务和/或取消绑定和重新绑定,因为这需要大量重构 我应该如何在播放音频时更改 AudioStreamType?
这是我的代码:
玩家服务:
public class PService extends Service {
private MediaPlayer mp = new MediaPlayer();
public static final String PLAYING_FINISHED_MSG = "1";
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
mp.stop();
mp.release();
}
private void playSong(String file) {
try {
mp.reset();
mp.setDataSource(file);
mp.setAudioStreamType(MYAPP.getAudioStreamType());
mp.prepare();
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer arg0) {
Intent i = new Intent();
i.setAction(MDService.PLAYING_FINISHED_MSG);
sendBroadcast(i);
}
});
切换路由按钮 onclick
currentlyPlayingFile = file;
currentlyPlayingPhone = phone;
lastDurationBeforePause = mpInterface.getCurrentPosition();
if(MYAPP.getAudioStreamType() == AudioManager.STREAM_MUSIC)
{
MYAPP.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
recording_player_route_button.setImageResource(R.drawable.route_off);
}
else{
MYAPP.setAudioStreamType(AudioManager.STREAM_MUSIC);
recording_player_route_button.setImageResource(R.drawable.route_on);
}
try {
mpInterface.playFile(file);
player_seekbar.setProgress(0);
player_seekbar.setMax(mpInterface.getDuration());
//seekto last millisecond after switching from/to sepaker
if(seekTo>0)
{
mpInterface.seekTo(seekTo);
}
isPauseButtonPressed = false;
handleSeekBarUpdate.postDelayed(handleSeekBarUpdateJob, 1);
} catch (RemoteException e) {
e.printStackTrace();
}