3

MediaPlayerローカル オーディオ ファイルを再生するオブジェクトがあります。を使用してTimerTask、オーディオの再生中に TextView の SeekBar とテキストの位置を更新しています。

ボタンは1つです。ユーザーがボタンを押すと、オーディオが開始されます。もう一度押すと、音声が停止します。もう一度再生を開始するために 3 回押すと、アプリがエラーでクラッシュします。

'causedby: TimerTask is scheduled already and InvocationTargetException'.

これが私のコードです:

    public void onAudioClicked(View v) {
    if (mainPlayer == null) {
        mainPlayer = MediaPlayer.create(this, R.raw.session1);
        // Get audio duration and set textview
        int d = mainPlayer.getDuration();
        TextView t = (TextView)findViewById(R.id.totalTime);
        t.setText(String.format("%d:%d", 
                TimeUnit.MILLISECONDS.toMinutes(d),
                TimeUnit.MILLISECONDS.toSeconds(d) - 
                TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(d))));

        sb.setProgress(0);
        sb.setMax(mainPlayer.getDuration());
        mainPlayer.start();
        timer = new Timer();
        timer.schedule(task, 1000);
    } else {
        mainPlayer.stop();
        mainPlayer.release();
        mainPlayer = null;
        timer.cancel();
        task.cancel();
        timer = null;
    }
}

    TimerTask task = new TimerTask(){
    public void run(){
        int currentPosition = 0;
        int total = mainPlayer.getDuration();
        sb.setMax(total);
        while (mainPlayer != null && currentPosition < total) {
            try {
                Thread.sleep(1000);
                currentPosition = mainPlayer.getCurrentPosition();
                runOnUiThread(updateControlsRunnable);
            } catch (InterruptedException e) {
                return;
            } catch (Exception e) {
                return;
            }
            sb.setProgress(currentPosition);
        }

    }
};

final Runnable updateControlsRunnable = new Runnable () {
    public void run(){
        int d = mainPlayer.getCurrentPosition();
        TextView t = (TextView)findViewById(R.id.currentTime);
        t.setText(String.format("%d:%d", 
                TimeUnit.MILLISECONDS.toMinutes(d),
                TimeUnit.MILLISECONDS.toSeconds(d) - 
                TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(d))));
        }
};
4

1 に答える 1

8

このコードブロックを試してください:

sb.setProgress(0);
sb.setMax(mainPlayer.getDuration());
mainPlayer.start();
timer = new Timer();
MyTask task=new MyTask();
timer.schedule(task,0, 1000);

private class MyTask extends TimerTask {
    public void run() {
        //Your code...
    }
}
于 2013-05-12T16:53:31.397 に答える