2016-08-22 10 views
1

画面が消えても(ユーザーが電話をロックしている場合でも)音楽を続けたい、ユーザーがホームボタンを押したときに一時停止して再びアプリに戻ると、画面が消えたときに音楽を再生する続ける

public class prathmeshvara extends AppCompatActivity implements Runnable, View.OnClickListener, SeekBar.OnSeekBarChangeListener{ 
TextView tv25; 
Button b47, b48, but32; 
int count = 0; 
MediaPlayer play3; 
SeekBar seek_bar3; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_prathmeshvara); 
    ActionBar actionBar=getSupportActionBar(); 
    actionBar.setDisplayShowHomeEnabled(true); 
    actionBar.setIcon(R.mipmap.icon); 
    tv25 = (TextView) findViewById(R.id.textView25); 
    tv25.setText(Html.fromHtml(getString(R.string.twentyone))); 
    b47 = (Button) findViewById(R.id.b47); 
    b48 = (Button) findViewById(R.id.b48); 
    seek_bar3 = (SeekBar) findViewById(R.id.seekBar3); 
    seek_bar3.setOnSeekBarChangeListener(this); 
    seek_bar3.setEnabled(false); 
    but32 = (Button) findViewById(R.id.button32); 
    but32.setOnClickListener(this); 
} 

public void run() { 
    int currentPosition = play3.getCurrentPosition(); 
    final int total = play3.getDuration(); 
    while (play3 != null && currentPosition < total) { 
     try { 
      Thread.sleep(1000); 
      currentPosition = play3.getCurrentPosition(); 
     } catch (InterruptedException e) { 
      return; 
     } catch (Exception e) { 
      return; 
     } 
     seek_bar3.setProgress(currentPosition); 
    } 
} 

public void onClick(View v) { 
    if (v.equals(but32)) { 
     if (play3 == null) { 
      play3 = MediaPlayer.create(getApplicationContext(), R.raw.prathameshwara); 
      seek_bar3.setEnabled(true); 
     } 
     if (play3.isPlaying()) { 
      play3.pause(); 
      but32.setBackgroundResource(R.drawable.play); 
     } else { 
      play3.start(); 
      but32.setBackgroundResource(R.drawable.pause); 
      seek_bar3.setMax(play3.getDuration()); 
      new Thread(this).start(); 
     } 
    } 
    play3.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { 
     @Override 
     public void onCompletion(MediaPlayer mp) { 
      play3.seekTo(0); 
      but32.setBackgroundResource(R.drawable.play); 
     } 
    }); 
} 

@Override 
protected void onPause() 
{ 
    super.onPause(); 
    if (play3!= null) 
    { 
     play3.pause(); 
    } 
} 

@Override 
protected void onResume() 
{ 
    super.onResume(); 
    if ((play3 != null) && (!play3.isPlaying())) { 
     but32.setBackgroundResource(R.drawable.play); 
     but32.setOnClickListener(this); 
    } 
} 
@Override 
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { 
    try { 
     if (play3.isPlaying() || play3 != null) { 
      if (fromUser) 
       play3.seekTo(progress); 
     } else if (play3 == null) { 
      Toast.makeText(getApplicationContext(), "First Play", Toast.LENGTH_SHORT).show(); 
      seek_bar3.setProgress(0); 
     } 
    } catch (Exception e) { 
     Log.e("seek bar", "" + e); 
     seek_bar3.setEnabled(false); 
    } 
} 

@Override 
public void onStartTrackingTouch(SeekBar seekBar) { 

} 

@Override 
public void onStopTrackingTouch(SeekBar seekBar) { 

} 
} 

答えて

1

基本的にあなたがonPause()文でplay3.pauseを行うべきではありませんあなたの目標を達成するために:ここに私のコードです

....ファイルブラウザを介して音楽を演奏するユーザーに似て...彼が一時停止したところから再開:

@Override 
protected void onPause() 
{ 
    super.onPause(); 
    if (play3!= null) 
    { 
     play3.pause(); 
    } 
} 

あなたのアプリが一時停止状態になると、再生が一時停止します。 Btwは時間をかけてAudioFocusの処理を実装することを忘れないでください。

+0

あなたは私の既存のコードとRESOにいくつかの変更を行うAudioFocus – Devk

0

私はAudioFocusについてのすべてを学んできた、それはこれらのソースから取り扱います:

Media playback the right way (Big Android BBQ 2015)

How to properly handle audio interruptions

Managing Audio Focus

AudioManager

AudioManager.OnAudioFocusChangeListener

そして、makeweightで、ここでは、メモリの束を食べて、彼らはあまりにもそれを使用したい場合には他のアプリのためのメディアコーデックを解放しないようにアプリのメディアresoursesをクリーンアップに関するいくつかの情報を持っている:

お使いのプレーヤーアクティビティで

Cleaning up MediaPlayer resources

+0

カントで私を助けてください可能性があり問題を抱えています.....最近私がコーディングを開始したので、私はそれを理解できません.... – Devk

0

Releasing the MediaPlayeronCreate前:

import android.media.AudioManager; 

...

また
int result = mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener, 
        AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT); 

      if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED){ 
       // we have audio focus now 

       // Create and setup the {@link MediaPlayer} for the audio resource associated with the current word 
       mMediaPlayer = MediaPlayer.create(YourActivity.this, word.getAudioResourceId()); 

       // Start the audio file 
       mMediaPlayer.start(); 

       // Setup a listener on the media player, so that we can stop and release the 
       // media player once the sound has finished playing. 
       mMediaPlayer.setOnCompletionListener(mCompletionListener); 
      } 

は、私はあなたがあなたのプレイヤーの活動にこれを追加することをお勧め(ただし、内部 onCreate)適切にメディアリソースを解放し、それを使用するために、停止ボタンが触れたとき: onClickメソッド内
/** Handles audio focus when playing a sound file */ 
private AudioManager mAudioManager; 

/** 
* This listener gets triggered when the {@link MediaPlayer} has completed 
* playing the audio file. 
*/ 


/** 
* This listener gets triggered whenever the audio focus changes 
* (i.e., we gain or lose audio focus because of another app or device). 
*/ 
private AudioManager.OnAudioFocusChangeListener mOnAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener(){ 
    @Override 
    public void onAudioFocusChange(int focusChange){ 
     if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT || 
       focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) { 
       // The AUDIOFOCUS_LOSS_TRANSIENT case means that we've lost audio focus for a 
       // short amount of time. The AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK case means that 
       // our app is allowed to continue playing sound but at a lower volume. We'll treat 
       // both cases the same way because our app is playing short sound files. 

       // Pause playback and reset player to the start of the file. That way, we can 
       // play the word from the beginning when we resume playback. 
       mMediaPlayer.pause(); 
       mMediaPlayer.seekTo(0); 
     } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) { 
       // The AUDIOFOCUS_GAIN case means we have regained focus and can resume playback. 
       mMediaPlayer.start(); 
     } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) { 
       // The AUDIOFOCUS_LOSS case means we've lost audio focus and 
       // Stop playback and clean up resources 
       releaseMediaPlayer(); 
     } 
    } 
}; 

それ以外の場合には再生を停止しなければならないとき:

/** 
* Clean up the media player by releasing its resources. 
*/ 
private void releaseMediaPlayer() { 
    // If the media player is not null, then it may be currently playing a sound. 
    if (mMediaPlayer != null) { 
     // Regardless of the current state of the media player, release its resources 
     // because we no longer need it. 
     mMediaPlayer.release(); 

     // Set the media player back to null. For our code, we've decided that 
     // setting the media player to null is an easy way to tell that the media player 
     // is not configured to play an audio file at the moment. 
     mMediaPlayer = null; 

     // Regardless of whether or not we were granted audio focus, abandon it. This also 
     // unregisters the AudioFocusChangeListener so we don't get anymore callbacks. 
     mAudioManager.abandonAudioFocus(mOnAudioFocusChangeListener); 
    } 
} 
関連する問題