0

我是android应用程序开发的新手。现在我的挑战是在我的 UI 中添加两个按钮,一个用于播放 mp3 文件,另一个用于停止它。我能够成功地做第一个,当我尝试做一个停止时,我看不到任何结果。我的代码如下:

package ir.polyglotcenter.childrenmostfrequentwords;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Main extends Activity {

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button myButtonOne = (Button) findViewById(R.id.btn_audio);
    myButtonOne.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            MediaPlayer media = MediaPlayer.create(Main.this, R.raw.audio);
            media.start();

        }
    });
    //this is to stop the audio flow
    Button myButtonTwo = (Button) findViewById(R.id.btn_stop);
    myButtonTwo.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            MediaPlayer media = MediaPlayer.create(Main.this, R.raw.audio);
            media.stop();

        }
    });

}
}
4

2 回答 2

1

试试这个代码:

public class Main extends Activity {

    protected MediaPlayer mMediaPlayer;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mMediaPlayer = MediaPlayer.create(Main.this, R.raw.audio);

        Button myButtonOne = (Button) findViewById(R.id.btn_audio);
        myButtonOne.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                mMediaPlayer.prepare();
                mMediaPlayer.start();
            }
        });
        //this is to stop the audio flow
        Button myButtonTwo = (Button) findViewById(R.id.btn_stop);
        myButtonTwo.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if(mMediaPlayer.isPlaying())
                    mMediaPlayer.stop();
            }
        });

    }
}
于 2013-03-11T05:11:47.873 回答
1

播放和停止所有行的所有歌曲。

要点是在 if 或任何循环的循环中实现 MediaPlayer:

if(playandstop==true){
mp=MediaPlayer.create(MainActivity.this, resourceIIIDD);
mp.start();
playandstop=false;
}else{
    mp.stop();
    playandstop=true;
}
于 2015-10-04T11:40:38.483 回答