安卓:给定的时间经过简单的如何阻止媒体播放器 [英] Android: Simple how to stop mediaplayer after given time

查看:138
本文介绍了安卓:给定的时间经过简单的如何阻止媒体播放器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图播放MP3文件(与onClickListener),2秒后停止。我想下面的code,但它不工作。谁能请帮助?

 最后的MediaPlayer mpsound = MediaPlayer.create(这一点,R.raw.media_player_sound);ImageView的声音=(ImageView的)findViewById(R.id.button);sound.setOnClickListener(新View.OnClickListener(){
            公共无效的onClick(视图v){
                mpsound.start(); {
                    睡眠(2000);
                    mpsound.stop();
                }
            }
        });


解决方案

你为什么要呼吁mpfrog停止()如果你正在播放的音频与mpsound?你需要呼吁mpsound的MediaPlayer的stop()函数。此外,您可能希望将@Override注释添加到您的onClick()方法。

有关覆盖...

  sound.setOnClickListener(新View.OnClickListener(){
            @覆盖
            公共无效的onClick(视图v){
                mpsound.start(); {
                    睡眠(2000);
                    mpsound.stop();
                }
            }
        });

有关定时器.....

 处理程序处理程序=新的处理程序(){
            @覆盖
            公共无效的handleMessage(消息MSG){
                mpsound.stop();
            }
        };//任务时间到期时计时器执行
    类SleepTask扩展的TimerTask {
        @覆盖
        公共无效的run(){
            handler.sendEmptyMessage(0);
        }
    }//然后在其他一些功能...
定时器定时器=新定时器(计时器,真正的);
timer.schedule(新SleepTask(),2000年);

I am trying to play an mp3 file (with an onClickListener) and stop after 2 seconds. I tried the code below but it is not working. Could anyone please help?

final MediaPlayer mpsound = MediaPlayer.create(this, R.raw.media_player_sound);

ImageView sound = (ImageView) findViewById(R.id.button);

sound.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                mpsound.start();{
                    sleep(2000);
                    mpsound.stop();
                }
            }
        });

解决方案

Why are you calling stop() on mpfrog if you are playing audio with mpsound? You need to call the stop() function on the mpsound MediaPlayer. Also, you might want to add the @Override annotation to your onClick() method.

for the override...

sound.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mpsound.start();{
                    sleep(2000);
                    mpsound.stop();
                }
            }
        });

for a timer.....

Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg){
                mpsound.stop();
            }
        };

//Task for timer to execute when time expires
    class SleepTask extends TimerTask {
        @Override
        public void run(){
            handler.sendEmptyMessage(0);
        }
    }

//then in some other function...
Timer timer = new Timer("timer",true);
timer.schedule(new SleepTask(),2000);

这篇关于安卓:给定的时间经过简单的如何阻止媒体播放器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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