1

我有一个简单的 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();
    }
4

1 回答 1

0

MODIFY_AUDIO_SETTINGS permissionManifest 中需要它才能工作。

AudioManager am=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
am.setMode(AudioManager.MODE_NORMAL);
MediaPlayer mp=new MediaPlayer();
Uri ringtoneUri=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
try
{
    mp.setDataSource(getApplicationContext(), ringtoneUri);
    mp.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
    mp.prepare();
    mp.start();
}
catch(Exception e)
{
    //exception caught in the end zone
}
于 2014-12-05T11:54:27.377 回答