2017-06-05 265 views
1

我想通過使用單個播放按鈕執行三個功能。 第一個過程 - 當我們點擊播放按鈕時,mediaplayer應該播放音頻。 第二個過程 - 當用戶第二次點擊播放按鈕時,音頻應該暫停。 第三個過程 - 當用戶單擊第三次播放按鈕時,音頻應從暫停的歌曲中恢復。如何使用媒體播放器播放和暫停音頻?

的嘗試下面的代碼

if (!mediaPlayer.isPlaying()) { 
       mediaPlayer.reset(); 
       try { 
        mediaPlayer.setDataSource(path); 
        // mediaPlayer.setOnPreparedListener((MediaPlayer.OnPreparedListener) getActivity()); 
        mediaPlayer.prepare(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
       mediaPlayer.start(); 

      } 
      else if (mediaPlayer.isPlaying()) { 
       mediaPlayer.pause(); 
      } 

      else if (!mediaPlayer.isPlaying() && mediaPlayer.getCurrentPosition() > 0) { 
       long currentPosition = mediaPlayer.getCurrentPosition(); 
       mediaPlayer.seekTo((int) currentPosition); 
       mediaPlayer.start(); 

      } 

上面的代碼不能正常工作,請幫助我如何解決這個問題。

回答

1

嘗試這種方式

public class MainActivity extends Activity { 
private Button btn; 
/** 
* help to toggle between play and pause. 
*/ 
private boolean playPause; 
private MediaPlayer mediaPlayer; 
/** 
* remain false till media is not completed, inside OnCompletionListener make it true. 
*/ 
private boolean intialStage = true; 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    btn = (Button) findViewById(R.id.button1); 
    mediaPlayer = new MediaPlayer(); 
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); 
    btn.setOnClickListener(pausePlay); 

} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.activity_main, menu); 
    return true; 
} 

private OnClickListener pausePlay = new OnClickListener() { 

    @Override 
    public void onClick(View v) { 
     // TODO Auto-generated method stub 
     // TODO Auto-generated method stub 

     if (!playPause) { 
      btn.setBackgroundResource(R.drawable.button_pause); 
      if (intialStage) 
       new Player() 
         .execute("http://www.virginmegastore.me/Library/Music/CD_001214/Tracks/Track1.mp3"); 
      else { 
       if (!mediaPlayer.isPlaying()) 
        mediaPlayer.start(); 
      } 
      playPause = true; 
     } else { 
      btn.setBackgroundResource(R.drawable.button_play); 
      if (mediaPlayer.isPlaying()) 
       mediaPlayer.pause(); 
      playPause = false; 
     } 
    } 
}; 
/** 
* preparing mediaplayer will take sometime to buffer the content so prepare it inside the background thread and starting it on UI thread. 
* @author piyush 
* 
*/ 

class Player extends AsyncTask<String, Void, Boolean> { 
    private ProgressDialog progress; 

    @Override 
    protected Boolean doInBackground(String... params) { 
     // TODO Auto-generated method stub 
     Boolean prepared; 
     try { 

      mediaPlayer.setDataSource(params[0]); 

      mediaPlayer.setOnCompletionListener(new OnCompletionListener() { 

       @Override 
       public void onCompletion(MediaPlayer mp) { 
        // TODO Auto-generated method stub 
        intialStage = true; 
        playPause=false; 
        btn.setBackgroundResource(R.drawable.button_play); 
        mediaPlayer.stop(); 
        mediaPlayer.reset(); 
       } 
      }); 
      mediaPlayer.prepare(); 
      prepared = true; 
     } catch (IllegalArgumentException e) { 
      // TODO Auto-generated catch block 
      Log.d("IllegarArgument", e.getMessage()); 
      prepared = false; 
      e.printStackTrace(); 
     } catch (SecurityException e) { 
      // TODO Auto-generated catch block 
      prepared = false; 
      e.printStackTrace(); 
     } catch (IllegalStateException e) { 
      // TODO Auto-generated catch block 
      prepared = false; 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      prepared = false; 
      e.printStackTrace(); 
     } 
     return prepared; 
    } 

    @Override 
    protected void onPostExecute(Boolean result) { 
     // TODO Auto-generated method stub 
     super.onPostExecute(result); 
     if (progress.isShowing()) { 
      progress.cancel(); 
     } 
     Log.d("Prepared", "//" + result); 
     mediaPlayer.start(); 

     intialStage = false; 
    } 

    public Player() { 
     progress = new ProgressDialog(MainActivity.this); 
    } 

    @Override 
    protected void onPreExecute() { 
     // TODO Auto-generated method stub 
     super.onPreExecute(); 
     this.progress.setMessage("Buffering..."); 
     this.progress.show(); 

    } 
} 

@Override 
protected void onPause() { 
    // TODO Auto-generated method stub 
    super.onPause(); 
    if (mediaPlayer != null) { 
     mediaPlayer.reset(); 
     mediaPlayer.release(); 
     mediaPlayer = null; 
    } 
} 
+0

我的代碼有什麼問題 –

+0

您試圖在onclick中設置DataSource,需要一定的時間才能播放,因爲通過此語句它需要時間來創建與服務器的連接。並且使用AsyncTask克服了掛起它的問題。 –

+0

是的,我已經完成了。 –

0

你可以試試這個

protected void initViews(Context context) { 
    mContext = context; 
    oneTimeOnly = 0; 
    mRootView = LayoutInflater.from(context).inflate(R.layout.view_digital_audio_content, this); 
    btn_delete = (ImageButton) mRootView.findViewById(R.id.btn_delete); 
    tv_current_duration = (TextView) mRootView.findViewById(R.id.tv_current_duration); 
    tv_total_duration = (TextView) mRootView.findViewById(R.id.tv_total_duration); 
    seekbar = (SeekBar) mRootView.findViewById(R.id.seekbar); 
    btn_Play = (ImageButton) mRootView.findViewById(R.id.btn_play); 
    seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { 
     @Override 
     public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { 
      if (mediaPlayer != null && fromUser) { 
       mediaPlayer.seekTo(progress); 
      } 
     } 

     @Override 
     public void onStartTrackingTouch(SeekBar seekBar) { 

     } 

     @Override 
     public void onStopTrackingTouch(SeekBar seekBar) { 

     } 
    }); 

    initMediaPlayer(); 

    btn_delete.setOnClickListener(this); 
    btn_Play.setOnClickListener(this); 
} 

private void initMediaPlayer() { 
    transactionDetail = FCSingleton.getTransactionDetails(); 
    TransactionDetail.DigitalContent digitalContent = transactionDetail.getDigtalContent(DigitalContentActivity.DigitalContentType.AUDIO); 
    try { 
     if (digitalContent != null) { 
      Uri audioUri = Uri.parse(digitalContent.getmThumbContent()); 
      QLog.i("Play audio " + audioUri.getPath()); 
      mediaPlayer = MediaPlayer.create(mContext, audioUri); 
      mediaPlayer.prepare(); 
      updateMediaTime(); 
      mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { 
       @Override 
       public void onPrepared(MediaPlayer mediaPlayer) { 
        mediaPlayer.start(); 
        mediaPlayer.seekTo(0); 
        finalTime = mediaPlayer.getDuration(); 
        startTime = mediaPlayer.getCurrentPosition(); 
       } 
      }); 
      mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { 
       @Override 
       public void onCompletion(MediaPlayer mediaPlayer) { 
        mediaPlayer.pause(); 
        updateMediaUI(); 
        startTime = 0; 
        seekbar.setProgress((int) startTime); 
        updateMediaTime(); 
       } 
      }); 
     } 
    } catch (Exception e) { 
     QLog.e(e); 
    } 
} 

private void updateMediaUI() { 
    if (mediaPlayer.isPlaying()) { 
     btn_Play.setBackgroundResource(R.drawable.digital_audio_pause); 
    } else { 
     btn_Play.setBackgroundResource(R.drawable.digital_audioplay); 
     startTime = mediaPlayer.getCurrentPosition(); 
     seekbar.setProgress((int) startTime); 
     updateMediaTime(); 
    } 
} 

@Override 
public void onClick(View view) { 
    switch (view.getId()) { 
     case R.id.btn_delete: 
      oneTimeOnly = 0; 
      transactionDetail.removeDigtalContent(DigitalContentActivity.DigitalContentType.AUDIO); 
      if (mediaPlayer != null) { 
       mediaPlayer.stop(); 
       mediaPlayer.release(); 
       mediaPlayer = null; 
      } 
      ((ViewGroup) getParent()).removeView(this); 
      if (mFragment.get() != null) { 
       mFragment.get().removeDigitalContent(transactionDetail, DigitalContentActivity.DigitalContentType.AUDIO); 
      } 
      break; 
     case R.id.btn_play: 
      if (mediaPlayer.getDuration() <= 0) { 
       initMediaPlayer(); 
      } 
      if (!mediaPlayer.isPlaying()) { 
       mediaPlayer.start(); 
       if (finalTime <= 0) { 
        finalTime = mediaPlayer.getDuration(); 
       } 

       startTime = mediaPlayer.getCurrentPosition(); 

       if (oneTimeOnly == 0) { 
        seekbar.setMax((int) finalTime); 
        oneTimeOnly = 1; 
       } 

       updateMediaTime(); 

       seekbar.setProgress((int) startTime); 

       durationHandler.postDelayed(updateSeekBarTime, 100); 
      } else { 
       mediaPlayer.pause(); 
       durationHandler.removeCallbacks(updateSeekBarTime); 
      } 
      updateMediaUI(); 
      break; 
    } 
} 

private void updateMediaTime() { 
    tv_total_duration.setText(String.format("%2d:%02d", 
      TimeUnit.MILLISECONDS.toMinutes((long) finalTime), 
      TimeUnit.MILLISECONDS.toSeconds((long) finalTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) finalTime))) 
    ); 

    tv_current_duration.setText(String.format("%2d:%02d", 
      TimeUnit.MILLISECONDS.toMinutes((long) startTime), 
      TimeUnit.MILLISECONDS.toSeconds((long) startTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) startTime))) 
    ); 
} 

//handler to change seekBarTime 
private Runnable updateSeekBarTime = new Runnable() { 
    public void run() { 
     if (mediaPlayer == null) { 
      return; 
     } 
     if (mediaPlayer.isPlaying()) { 
      //get current position 
      startTime = mediaPlayer.getCurrentPosition(); 
      //set seekbar progress 
      seekbar.setProgress((int) startTime); 
      //set time remaing 
      double timeRemaining = finalTime - startTime; 
      updateMediaTime(); 

      //repeat yourself that again in 100 miliseconds 
      durationHandler.postDelayed(this, 100); 
     }else{ 
      for (int i = mediaPlayer.getDuration(); i >= mediaPlayer.getCurrentPosition(); i--){ 

      } 
     } 
     updateMediaUI(); 
    } 
}; 

@Override 
public void pauseMedia() { 
    if (mediaPlayer != null) { 
     mediaPlayer.pause(); 
     updateMediaUI(); 
     durationHandler.removeCallbacks(updateSeekBarTime); 
    } 
} 
0

你可以試試這個

holder.btPlay.setOnClickListener(new View.OnClickListener() { 
@Override 
public void onClick(View view) { 


    if (mediaPlayer != null && mediaPlayer[0] != null && mediaPlayer[0].isPlaying()) { 
     mediaPlayer[0].stop(); 
     mediaPlayer[0].release(); 
     return; 
    } 
    mediaPlayer = new MediaPlayer[]{MediaPlayer.create(context, soundUri)}; 
    mediaPlayer[0].setOnPreparedListener(new MediaPlayer.OnPreparedListener() { 
            @Override 
            public void onPrepared(MediaPlayer mp) {mp.start(); 
            } 
           }); 
    mediaPlayer[0].setOnCompletionListener(new MediaPlayer.OnCompletionListener() { 
     @Override 
     public void onCompletion(MediaPlayer mp) { 
      try { 
       mp.release(); 
      } catch (Exception e) { 

      } 
      mediaPlayer[0] = null; 
     } 
    }); 
    mediaPlayer[0].setOnErrorListener(new MediaPlayer.OnErrorListener() { 
     @Override 
     public boolean onError(MediaPlayer mp, int what, int extra) { 
      try { 
       mp.release(); 
      } catch (Exception e) { 

      } 
      mediaPlayer[0] = null; 
      return false;} 
    }); 
} 

}

相關問題