Android 媒体播放器开始停止开始

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20563729/
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 03:03:15  来源:igfitidea点击:

Media Player start stop start

androidmedia-player

提问by Slim C.

I am making a new android sound application. I made a clickable button to play sound when I click on it. But I also want it to stop playing sound when I click for the second time. That part works fine now here is the problem, when I click again on button to play sound again, it doesn't play it, Media player is completely stopped. I was looking on forums but I can't seem to find an answer that could help me. Here is my Activity:

我正在制作一个新的 android 声音应用程序。当我点击它时,我做了一个可点击的按钮来播放声音。但我也希望它在我第二次点击时停止播放声音。现在这部分工作正常,问题是,当我再次单击按钮再次播放声音时,它不播放,媒体播放器完全停止。我在论坛上寻找,但似乎找不到可以帮助我的答案。这是我的活动:

  MediaPlayer mpButtonClick1;
MediaPlayer mpButtonClick2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.prvi);

    final MediaPlayer mpButtonClick1 = MediaPlayer.create(this, R.raw.spalshm);
    final MediaPlayer mpButtonClick2 = MediaPlayer.create(this, R.raw.splashs);


    Button dugme = (Button) findViewById(R.id.dugme);
    dugme.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (mpButtonClick1.isPlaying()) {
                mpButtonClick1.stop();
                mpButtonClick1.reset();

            }
            else {              
                mpButtonClick1.start();

            }


        }   

    });

When I try to write mpButtonClick1.prepare(); I get error Unhandled Exception Type IOE exception

当我尝试编写 mpButtonClick1.prepare(); 我收到错误未处理的异常类型 IOE 异常

采纳答案by Bhoomika Brahmbhatt

Change your class with below code:

使用以下代码更改您的课程:

remove reset();.

删除reset();.

init well all components:

初始化所有组件:

MediaPlayer mpButtonClick1;
MediaPlayer mpButtonClick2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.prvi);

     mpButtonClick1 = MediaPlayer.create(this, R.raw.spalshm);
     mpButtonClick2 = MediaPlayer.create(this, R.raw.splashs);


    Button dugme = (Button) findViewById(R.id.dugme);
    dugme.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (mpButtonClick1.isPlaying()) {
                mpButtonClick1.stop();
             }
            else {              
                mpButtonClick1.start();
            }
         }   

    });

回答by gian1200

Try to use pauseinstead of stop.

尝试使用pause而不是stop.

Reason: if you pause the MediaPlayer, then you can resume it later. However, if you use stop, almost any other method won't work and you will have to prepare the MediaPlayer again (or create a new one).

原因:如果您暂停MediaPlayer,那么您可以稍后恢复。但是,如果您使用stop,几乎任何其他方法都不起作用,您将不得不再次准备 MediaPlayer(或创建一个新的)。

enter image description here

在此处输入图片说明

More info: hereand here

更多信息:这里这里

PS: don't forget to release the memory when you finish using the resources.

PS:使用完资源不要忘记释放内存。

回答by Shylendra Madda

Try this: You should use only one mediaplayer object

试试这个:你应该只使用一个 mediaplayer 对象

    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 Melquiades

You're calling mpButtonClick1.reset() after mpButtonClick1.stop() - don't do that:

您在 mpButtonClick1.stop() 之后调用 mpButtonClick1.reset() - 不要这样做:

if (mpButtonClick1.isPlaying()) {
    mpButtonClick1.stop();
    mpButtonClick1.reset(); //<--------- calling reset(), remove this line
}

The docs for reset()say:

reset()的文档说:

Resets the MediaPlayer to its uninitialized state. After calling this method, you will have to initialize it again by setting the data source and calling prepare().

将 MediaPlayer 重置为其未初始化状态。调用此方法后,您必须通过设置数据源并调用prepare() 来再次初始化它。

Remove mpButtonClick1.reset() and it should work.

删除 mpButtonClick1.reset() 它应该可以工作。

Keep in mind that MediaPlayer works as a state machine, which means that if you call methods in the wrong order, you'll get problems. Please read about MediaPlayer hereand here.

请记住,MediaPlayer 作为状态机工作,这意味着如果您以错误的顺序调用方法,就会遇到问题。请在此处此处阅读有关 MediaPlayer 的信息

回答by Gogu CelMare

In my experience when I need to play multiple times and I may need to stop one play to start another play, (like in the case of multiple buttons), I just create another player, making sure that I release the resources for the previous one. To stop just use

根据我的经验,当我需要多次播放并且我可能需要停止一个播放以开始另一个播放时(例如在多个按钮的情况下),我只是创建另一个播放器,确保释放前一个播放器的资源. 停止使用

mediaPlayer.stop(); 

But for play use something like this (adapt the logging to your specific needs) to create/recreate your player:

但是对于游戏,使用这样的东西(根据您的特定需求调整日志记录)来创建/重新创建您的播放器:

private boolean createMediaPlayer()
{
    if (mediaPlayer!=null)
    {
        if(mediaPlayer.isPlaying())
        {
            mediaPlayer.stop();
            mediaPlayer.reset();
            mediaPlayer.release();
            mediaPlayer=null;
        }

    }
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setVolume(1f, 1f);
    try
    {
        mediaPlayer.setAudioStreamType(Interop.PRIMARY_STREAM);
        mediaPlayer.setDataSource(m_soundFile);
        mediaPlayer.prepare();
        return true;
        // Interop.logDebug(TAG + "-loadAudio: SUCCESS" + m_soundFile);
    } catch (Exception e)
    {
        Interop.logError(TAG + "-LoadAudio for Clic Sound: audioPlayer prepare failed for current file: " + m_soundFile);
        Interop.logError(TAG + "-Exception: " , e);
        return false;
    }
}

and than use

然后使用

if (createMediaPlayer())
    mediaPlayer.start();

this will ensure proper release of the resources used by the media player.

这将确保正确释放媒体播放器使用的资源。

回答by automaticSoldier

A simple solution is to Use pause instead of stop and the seek to the beginning of the song.

一个简单的解决方案是使用暂停而不是停止并寻找歌曲的开头。

回答by av-sharma

I know that this question is quite old but recently while learning Android, I also got stuck at this point and found a very simple solution which I'd like to share with everyone.

我知道这个问题已经很老了,但最近在学习 Android 时,我也卡在了这一点上,并找到了一个非常简单的解决方案,我想与大家分享。

Instead of trying to stopor resetthe media, you can just seek backto the starting position.

而不是试图阻止重置的媒体,你可以寻求回起始位置

mediaPlayer.seekTo(0);

For reference, I am also posting my code below:

作为参考,我还在下面发布了我的代码:

public class MainActivity extends AppCompatActivity {

    MediaPlayer mp;

    public void play(View view) {
        mp.start();
    }

    public void pause(View view) {
        mp.pause();
    }

    public void stop(View view) {
        // this seeks to the beginning of the file
        mp.seekTo(0);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mp = MediaPlayer.create(this, R.raw.sample_audio);
    }
}

回答by Lalit kumar

Hey please use following

嘿请使用以下

for stop -> media player mp.seekTo(0); mp.pause();

停止 -> 媒体播放器 mp.seekTo(0); mp.pause();

again for start just call mp.start();

再次启动只需调用 mp.start();

回答by Berk KARAAL

I am using this code to play a sound from the beginning while playing or not.

无论是否播放,我都使用此代码从头开始播放声音。

mp.seekTo(0);
mp.start();