Android MediaPlayer 停止和播放

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12266502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 10:15:33  来源:igfitidea点击:

Android MediaPlayer Stop and Play

androidmedia-player

提问by Mohammad Hammad

I'm creating Android application contains 2 buttons, on click on each button play a mp3 file. The problem is when I play button1it plays sound1, when I click button2it plays sound2.

我正在创建包含 2 个按钮的 Android 应用程序,点击每个按钮播放一个 mp3 文件。问题是当我播放button1它时sound1,当我点击button2它时播放sound2

I check on each button the other player if it's working and I stop it and play the clicked one

我检查其他玩家的每个按钮是否正常工作,然后停止它并播放点击的按钮

But If I click on same button twice it's keep first audio playing in the background and play another one again

但是如果我点击同一个按钮两次,它会在后台播放第一个音频并再次播放另一个

I tried to check isPlaying()and to stop it, but it doesn't work!

我试图检查isPlaying()并阻止它,但它不起作用!

I want If I click on button1it play sound1and if clicked on it again it stop it and play it again from beginning.

我想要如果我点击button1它播放sound1,如果再次点击它会停止它并从头开始播放。

My code:

我的代码:

package com.hamoosh.playaudio;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class PlayaudioActivity extends Activity {
/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button b= (Button) findViewById(R.id.button1);
        Button b2= (Button) findViewById(R.id.button2);
        final TextView t= (TextView) findViewById(R.id.textView1);

        final MediaPlayer mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.far);
        final MediaPlayer mp1 = MediaPlayer.create(PlayaudioActivity.this, R.raw.beet);

        b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mp1.isPlaying()) {

                    mp1.stop();
                }

                mp.start();
            }

        });

        b2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mp.isPlaying()) {

                    mp.stop();
                }
                mp1.start();
            }
        });
    }
}

Hope if there any better code that can use multiple buttons as an array or something to not check each button and player every time.

希望是否有更好的代码可以使用多个按钮作为数组或其他东西,而不是每次都检查每个按钮和播放器。

回答by Mario

You should use only one mediaplayer object

您应该只使用一个媒体播放器对象

    public class PlayaudioActivity extends Activity {

        private MediaPlayer mp;

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            Button b = (Button) findViewById(R.id.button1);
            Button b2 = (Button) findViewById(R.id.button2);
            final TextView t = (TextView) findViewById(R.id.textView1);

            b.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    stopPlaying();
                    mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.far);
                    mp.start();
                }

            });

            b2.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    stopPlaying();
                    mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.beet);
                    mp.start();
                }
            });
        }

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

回答by Ruchir Baronia

To stop the Media Player without the risk of an Illegal State Exception, you must do

要在不存在非法状态异常风险的情况下停止媒体播放器,您必须执行

  try {
        mp.reset();
        mp.prepare();
        mp.stop();
        mp.release();
        mp=null;
       }
  catch (Exception e)
         {
           e.printStackTrace();
         }

rather than just

而不仅仅是

try {
       mp.stop();
       mp.release();
       mp=null;
    } 
catch (Exception e) 
    {
      e.printStackTrace();
    }

回答by Javier

According to the MediaPlayerlife cycle, which you can view in the Android API guide, I think that you have to call reset()instead of stop(), and after that prepare again the media player (use only one) to play the sound from the beginning. Take also into account that the sound may have finished. So I would also recommend to implement setOnCompletionListener()to make sure that if you try to play again the sound it doesn't fail.

根据MediaPlayer生命周期,您可以在Android API指南中查看,我认为您必须调用reset()而不是stop(),然后再次准备媒体播放器(仅使用一个)从头开始播放声音。还要考虑到声音可能已经结束。因此,我还建议实施setOnCompletionListener()以确保如果您再次尝试播放声音,它不会失败。

回答by dyingStudent

just in case someone comes to this question, I have the easier version.

以防万一有人遇到这个问题,我有更简单的版本。

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

        Button b = (Button) findViewById(R.id.button);
        Button b2 = (Button) findViewById(R.id.button2);


        b.setOnClickListener(new View.OnClickListener() {

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

        b2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mp.stop();
               // mp.start();
            }
        });
    }

回答by pallavi agrawal

I may have not got your answer correct, but you can try this:

我可能没有得到你的正确答案,但你可以试试这个:

public void MusicController(View view) throws IOException{
    switch (view.getId()){
        case R.id.play: mplayer.start();break;
        case R.id.pause: mplayer.pause(); break;
        case R.id.stop:
            if(mplayer.isPlaying()) {
                mplayer.stop();
                mplayer.prepare(); 
            }
            break;

    }// where mplayer is defined in  onCreate method}

as there is just one thread handling all, so stop() makes it die so we have to again prepare it If your intent is to start it again when your press start button(it throws IO Exception) Or for better understanding of MediaPlayer you can refer to Android Media Player

因为只有一个线程处理所有,所以 stop() 让它死了所以我们必须再次准备它如果您的意图是在按下开始按钮时再次启动它(它抛出 IO 异常)或者为了更好地理解 MediaPlayer请参阅Android 媒体播放器