2014-01-21 2 views
0

앱을 만들고 레이아웃 하나 (레이아웃 A라고 함)에서 미디어 플레이어를 재생 한 다음 다른 레이아웃 (레이아웃 B라고 부름)에 갔을 때 레이아웃 A의 사운드는 레이아웃 B에서 계속 재생되며, 레이아웃 A로 돌아 가면 미디어 플레이어가 이전에 연주 한 음악을 계속 재생하기를 원합니다.두 미디어 플레이어가 동시에 재생

player = MediaPlayer.create(this, R.raw.sound); 
    if(!isMuted()) 
    { 
     player.setLooping(true); 
     player.start(); 
    } 

... 

    btn.setOnClickListener(new View.OnClickListener() 
    { 
     @Override 
     public void onClick(View arg0) 
     { 
      // TODO Auto-generated method stub 
      Intent intent = new Intent(A.this, B.class); 
      stop=1; 
      startActivity(intent);   
     } 
    }); 

그리고 코드 :

player = MediaPlayer.create(this, R.raw.sound); 
.... 
:

레이아웃 B에서
@Override 
protected void onPause() 
{ 
    super.onPause(); 
    if (stop!=1) 
    { 
     //stop=1 if i go to another layout, for example when i want to go to Layout B 
     //if the device is automatically locked, i want the media player is paused and it resumed when i unlock the device, so i use stop!=1 to know whether the sound should be paused or not 
     player.pause(); 
     length = player.getCurrentPosition(); 
    } 
} 

@Override 
protected void onResume() 
{ 
    super.onResume(); 
    if(!isMuted()) 
    { 
     //isMuted is method to know whether the sound is muted or not, if it isn't muted, then the sound is resumed 
     player.seekTo(length); 
     player.setLooping(true); 
     player.start(); 
    } 
} 

, 난에서 onCreate이 코드를 사용

레이아웃 A의

난에서 onCreate이 코드 세트

그리고이 코드 :

protected void onPause() 
{ 
    super.onPause(); 
    player.pause(); 
    length = player.getCurrentPosition(); 
} 

@Override 
protected void onResume() 
{ 
    super.onResume(); 
    if(!isMuted()) 
    { 
     if(player.isPlaying()) 
     { 

     } 
     else 
     { 
      player.seekTo(length); 
      player.setLooping(true); 
      player.start(); 
     } 
    } 
} 

그러나 이것은 문제입니다.

  1. 내가 레이아웃 B, 레이아웃 A와 레이아웃 B에서 미디어 플레이어에서 미디어 플레이어에 갔다

    는 같은 시간에 재생됩니다, 그래서 소리가 한 번에 동시에 재생됩니다.

  2. 레이아웃 A로 돌아 가면 레이아웃 B의 미디어 플레이어가 중지되고 레이아웃 A의 미디어 플레이어가 처음부터 다시 재생되고 중지되며 이전에 재생 된 미디어 플레이어가 계속되지 않았습니다. .

  3. 장치가 잠겨있을 때 일시 중지해야하는지 여부를 나타내는 표시기를 사용했지만 미디어 플레이어는 계속 재생됩니다. 코드를 수정 했습니까?

답변

0

서비스를 사용하여 음악을 재생하고 일시 중지/중지하는 것이 좋습니다. 그런 방식으로 음악을 다루기 위해 액티비티를 사용하지 않는 것이 좋습니다. 서비스를 시작한 다음 서비스를 재생할 수 있습니다. 서비스는 백그라운드에서 실행되며 Activity에 비해 자동으로 너무 자주 파괴되지 않습니다. 다음은 필요한 앱 코드의 예입니다. media player sound continue in all activities

관련 문제