Android按钮单击以播放音乐,再次单击以停止播放声音 [英] Android button click to play music, click again to stop sound

查看:219
本文介绍了Android按钮单击以播放音乐,再次单击以停止播放声音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个按钮,当我单击它播放音乐时,如何做,当我第二次单击时,停止播放音乐?

I have a button, when I click it plays music, how to do it, when I click second time, to stop the music?

 Button two = (Button)this.findViewById(R.id.button2);
            final MediaPlayer mp2 = MediaPlayer.create(this, R.raw.two);
            two.setOnClickListener(new OnClickListener(){

                public void onClick(View v) {
                    mp2.start();
                }
            });  

好的,这一项有效:

Button one = (Button)this.findViewById(R.id.button1);
    final MediaPlayer mp1 = MediaPlayer.create(this, R.raw.n);
    one.setOnClickListener(new OnClickListener(){

        @Override
            public void onClick(View v) {
            if (mp1.isPlaying()) {
                mp2.pause();
                } 
                else {
                mp2.start();
            }
        ;
    }});

上面带有暂停"的按钮可以使用,但是如果我想停止播放音乐,则无法使用. 以下内容无效:

The one with Pause above it works, but If I want to stop the music, it does not work. Following not working:

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

我收到错误:以状态0开始调用
错误(-38,0)

I get error: start called in state 0
error (-38, 0)

推荐答案

根据 http://developer.android.com/reference/android/media/MediaPlayer.html ,我想您可以执行以下操作:

According to http://developer.android.com/reference/android/media/MediaPlayer.html, I suppose you could do something like this:

 Button two = (Button)this.findViewById(R.id.button2);
            final MediaPlayer mp2 = MediaPlayer.create(this, R.raw.two);
            two.setOnClickListener(new OnClickListener(){

                public void onClick(View v) {

                    // If the music is playing
                    if(mp2.isPlaying() == true)
                        // Pause the music player
                        mp2.pause();
                    // If it's not playing
                    else
                        // Resume the music player
                        mp2.start();
                }
            });

您实际上可以只写

 if(mp2.isPlaying())

代替

 if(mp2.isPlaying() == true)

这只是为了了解正在发生的事情.

It's just for the sake of understanding what is going on.

这篇关于Android按钮单击以播放音乐,再次单击以停止播放声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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