【问题标题】:Android: Simple how to stop mediaplayer after given timeAndroid:简单的如何在给定时间后停止媒体播放器
【发布时间】:2012-07-18 01:03:52
【问题描述】:

我正在尝试播放 mp3 文件(使用 onClickListener)并在 2 秒后停止。我尝试了下面的代码,但它不起作用。有人可以帮忙吗?

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();
                }
            }
        });

【问题讨论】:

  • mpsound.start()...mpfrog.stop() ???试试mpsound.stop() 吧?

标签: android media-player


【解决方案1】:

如果您正在使用 mpsound 播放音频,为什么要在 mpfrog 上调用 stop()?您需要调用 mpsound MediaPlayer 上的 stop() 函数。此外,您可能希望将 @Override 注释添加到您的 onClick() 方法中。

对于覆盖...

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

用于计时器.....

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);

【讨论】:

  • 对不起,我把名字弄乱了,但现在已经更正了。我是 Android 新手,所以我不确定在哪里放置 @Override 注释。它会在“sound.setOnClickListener(new View.OnClickListener()”这一行的正上方吗?
  • 不,它会直接在您要覆盖的函数之上,在这种情况下是 onClick()... 查看编辑^
  • UI 线程中的 sleep(2000) 会冻结整个设备,我说得对吗?
  • 它将在您的应用程序的主线程上调用睡眠,在这种情况下,主线程是 UI 所在的线程......所以,如果您这样做,UI 将在两秒钟内变得无用就这样
  • 所以我认为在等待时冻结 UI 不是一个好(甚至非常糟糕)的主意 =)
【解决方案2】:

您必须在不同的线程中等待 2 秒,在这种情况下,使用您自己创建的 thread 并在那里等待并停止播放器,或者您可以使用 CountDownTimer - 非常简单的解决方案。

您可以找到汇总here 和here 的相同问题

在 Eclipse 中,您可以使用自动完成(默认为 ctrl + 空格)来自动填充所有已实现的方法,并且 @Overrides 已经存在。

【讨论】:

  • 我是 Android 和 Java 新手,请您解释一下 CountDownTimer 的确切放置位置?我尝试了以下方法,但没有奏效:
  • sound.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mpsound.start(); new CountDownTimer(30000, 1000) { public void onTick(long millisUntilFinished) { } public void onFinish() { mpsound.stop(); } }.start(); } });
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-06
  • 1970-01-01
  • 2016-09-17
  • 1970-01-01
  • 1970-01-01
  • 2013-10-03
  • 1970-01-01
相关资源
最近更新 更多