如何使用媒体播放器播放和暂停音频?

时间:2017-06-05 07:20:35

标签: android media-player

我想使用单个播放按钮执行这三个功能。   第一个过程 - 当我们点击播放按钮时,媒体播放器应播放音频。   第二个过程 - 当用户第二次点击播放按钮时,应暂停音频。   第三个过程 - 当用户点击第三次播放按钮时,音频应该从暂停的歌曲中恢复。

尝试了下面的代码

 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();

            }

以上代码无效,请帮我解决这个问题。

3 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分: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);
    }
}

答案 2 :(得分: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;}
    });
}

}