Android:如何停止媒体播放器点击按钮

时间:2011-03-29 08:56:11

标签: android media-player

我有一个播放和停止按钮。当我运行以下代码时,播放按钮顺利进行。但是当我点击停止按钮时,我收到一条强制关闭消息。

我是android dev的新手。提前谢谢了! :)

package com.example.hellomedia;

import java.io.IOException;


import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;

public class HelloMedia extends Activity {


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

        final MediaPlayer mPlayer = MediaPlayer.create(HelloMedia.this, R.raw.nicholas);

        setContentView(R.layout.main);

        final Handler mHandler = new Handler();

        final TextView customTextBG = (TextView) findViewById(R.id.customTextBG);
        final TextView customTextHL = (TextView) findViewById(R.id.customTextHL);

        customTextBG.setText("Nicholas was… \n\nOlder than sin, ");
        customTextHL.setText("");

        final String words[] = {
                "Nicholas ", // 0
                "was... \n\n", // 1
                "Older ", // 2
                "than ", // 3
                "sin, ", // 4
        };

        final long startEndTime[][]={
                {   //start time
                    1148,// 0,0
                    1826, // 0,1
                    2766,// 0,2
                    3079,// 0,3
                    3549,// 0,4

                },
                {   //end time
                    1357,// 1,0
                    2192, // 1,1
                    3027,// 1,2
                    3183,// 1,3
                    3966,// 1,4
                }
            };



        customTextBG.setText("Nicholas was… \n\nOlder than sin, ");
        customTextHL.setText("");




        View.OnClickListener handler = new View.OnClickListener(){
            public void onClick(View v) {

                switch (v.getId()) {
                    case R.id.widget30: // PLAY

                        if( !mPlayer.isPlaying() ){

                            try {
                                mPlayer.prepare();
                            } catch (IllegalStateException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                    e.printStackTrace();
                            }

                            mPlayer.start();

                            mHandler.post(new Runnable(){

                                    public void run(){ 
                                    final long currentPos = mPlayer.getCurrentPosition();

                                        int x = 0;
                                        while( x < 102){
                                            if( currentPos > startEndTime[0][x] && currentPos < startEndTime[1][x] ){//0
                                            customTextHL.append(words[x]);
                                            words[x]="";
                                        }
                                        x++;
                                    } mHandler.postDelayed(this, 1);
                                    }

                              });
                        }

                        break;

                    case R.id.widget31: // RESET

                        mHandler.post(new Runnable(){

                            public void run(){ 
                                customTextBG.setText("Nicholas was… \n\nOlder than sin, ");
                                customTextHL.setText("");
                            }

                      });

                        mPlayer.stop();
                        mPlayer.release();

                        break;
                }
            }
        };

        // BUTTONS
        findViewById(R.id.widget30).setOnClickListener(handler); // PLAY
        findViewById(R.id.widget31).setOnClickListener(handler); // RESET

    }
}

我的main.xml代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/widget29"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<TextView
android:textStyle="bold" 
android:id="@+id/customTextBG" 
android:textSize="18sp" 
android:text="@+id/customTextBG" 
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/widget31"
android:layout_alignParentLeft="true"
>
</TextView>
<TextView
android:textStyle="bold" 
android:id="@+id/customTextHL" 
android:textSize="18sp" 
android:text="@+id/customTextHL" 
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/widget31"
android:layout_alignParentLeft="true"
android:textColor="#00FF00"
>
</TextView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/widget30"
android:text="@string/reset" android:id="@+id/widget31">
</Button>
<Button
android:id="@+id/widget30"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:text="@string/play">
</Button>
</RelativeLayout>

5 个答案:

答案 0 :(得分:2)

首先,不要尝试:

mHandler.post(new Runnable(){

    public void run(){ 
        customTextBG.setText("Nicholas was… \n\nOlder than sin, ");
        customTextHL.setText("");
    }

}); 

和停止播放器的代码:

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

第二,你可以提供你的xmlfiles,然后我们可以测试它并查看错误。

答案 1 :(得分:1)

像这样放一个try catch块 -

try { 
       mPlayer.stop();
       mPlayer.release(); 
  } catch(Exception ex) { 
     ex.printStackTrace() 
  }

如果您的设备设置为调试应用程序,请在catch块中放置一个断点,并告诉我们异常所说的内容。您也可以使用模拟器进行调试。

答案 2 :(得分:1)

以上代码被修改为以下代码并根据您的要求输出。当您通过MediaPlayer.create(....)方法创建媒体播放器时,无需再次准备它。一旦释放或重置方法,就应该要求它们重新初始化数据源。

public class HelloMedia extends Activity {
   MediaPlayer mPlayer;
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

             mPlayer = MediaPlayer.create(HelloMedia .this, R.raw.sleepaway);

        setContentView(R.layout.main);

        final Handler mHandler = new Handler();

        final TextView customTextBG = (TextView) findViewById(R.id.customTextBG);
        final TextView customTextHL = (TextView) findViewById(R.id.customTextHL);

        customTextBG.setText("Nicholas was… \n\nOlder than sin, ");
        customTextHL.setText("");

        final String words[] = {
                "Nicholas ", // 0
                "was... \n\n", // 1
                "Older ", // 2
                "than ", // 3
                "sin, ", // 4
        };

        final long startEndTime[][]={
                {   //start time
                    1148,// 0,0
                    1826, // 0,1
                    2766,// 0,2
                    3079,// 0,3
                    3549,// 0,4

                },
                {   //end time
                    1357,// 1,0
                    2192, // 1,1
                    3027,// 1,2
                    3183,// 1,3
                    3966,// 1,4
                }
            };



        customTextBG.setText("Nicholas was… \n\nOlder than sin, ");
        customTextHL.setText("");




        View.OnClickListener handler = new View.OnClickListener(){
            public void onClick(View v) {

                switch (v.getId()) {
                    case R.id.widget30: // PLAY
                        try{
                            if(mPlayer==null)
                                 mPlayer = MediaPlayer.create(HelloMedia .this, R.raw.sleepaway);
                        if( !mPlayer.isPlaying() )
                        {

                          if(!mPlayer.isPlaying())
                            mPlayer.start();

            mHandler.post(new Runnable(){

                             public void run(){ 
                                 if(mPlayer!=null)
                                 if(mPlayer.isPlaying()){
                                    final long currentPos = mPlayer.getCurrentPosition();
                                        int x = 0;
                                        while( x < 5){
                                            if( currentPos > startEndTime[0][x] && currentPos < startEndTime[1][x] ){//0
                                            customTextHL.append(words[x]);
                                            words[x]="";
                                        }
                                        x++;
                                    } mHandler.postDelayed(this, 1);
                                    }

                             }});
                        }
                        }catch (Exception e) {
                            e.printStackTrace();
                            // TODO: handle exception
                        }

                        break;

                    case R.id.widget31: // RESET

                        mHandler.post(new Runnable(){

                            public void run(){ 
                                customTextBG.setText("Nicholas was… \n\nOlder than sin, ");
                                customTextHL.setText("");
                            }

                      });

                        try{
                        if(mPlayer.isPlaying())
                        {
                              mPlayer.stop();
                              mPlayer.reset();
                              mPlayer=null;
                        }
                        }catch (Exception e) {

                            e.printStackTrace();
                            // TODO: handle exception
                        }


                        break;
                }
            }
        };

        // BUTTONS
        findViewById(R.id.widget30).setOnClickListener(handler); // PLAY
        findViewById(R.id.widget31).setOnClickListener(handler); // RESET

    }
}

答案 3 :(得分:0)

这是我的代码,已经过测试并正常运行

package com.example.com.mak.mediaplayer;

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

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer mpp;
mpp=MediaPlayer.create(this,R.raw.red); //mp3 file in res/raw folder
    Button btnplay=(Button)findViewById(R.id.btnplay); //Play
        btnplay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View vone) {
                mpp.start();}
        });
    Button btnpause=(Button)findViewById(R.id.btnpause); //Pause
        btnpause.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View vtwo) {
                if(mpp.isPlaying())
                {
        mpp.pause();
        mpp.seekTo(0);
                }
            }
        });

}

}

答案 4 :(得分:0)

if(mPlayer != null){
 mPlayer.release();

}