如何停止音乐并在Android中再次播放? [英] How to stop a music and play again in Android?

查看:127
本文介绍了如何停止音乐并在Android中再次播放?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个简单的Android MediaPlayer代码.我在停止播放歌曲并重新启动时遇到问题.在每个按钮中单击.否则,如果我不停止播放曲目,请在每个按钮中单击歌曲不播放,直到歌曲停止播放.

I am trying to write a simple Android MediaPlayer code. I am facing an issue while stopping a song and restart again. In each button click. Otherwise , if i wont stop the track then , in each button click the song is not playing , it wait until the songs stops.

我的要求是,在每个按钮中单击歌曲应从头开始.

My requirement is , in each button click the song should start from the beginning.

我的代码:

package com.example.musicexample;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends ActionBarActivity {

   Button btnPlay;
   MediaPlayer mPlayer;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

     btnPlay = (Button) findViewById(R.id.btnPlay);

     mPlayer = MediaPlayer.create(getApplicationContext(), R.raw.a);

     btnPlay.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            if(mPlayer.isPlaying()){
                mPlayer.stop();
                mPlayer.reset();
            }

            mPlayer.start();
        }
    });
} }

在上面的代码中,歌曲随后播放一次,不再播放.

In the above code , the song plays once then , it won't play again.

因此,请仔细阅读,如果我正在播放歌曲,如何停止播放曲目,然后从头开始重新播放呢.

So please go through it , please let me know , how can i stop the track if the song is playing and then restart it from beginning.

推荐答案

您可以尝试以下操作:

MediaPlayer m1 = null;

        play1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
        stopPlaying();
        m1=MediaPlayer.create(MainActivity.this, R.raw.a);
        m1.start();
        }
    });   

    private void stopPlaying() {
         if (mp1 != null) {
            m1.stop();
            m1.release();
            m1 = null;
    }

这篇关于如何停止音乐并在Android中再次播放?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆