2013-09-02 4 views
1

в моем музыкальном проигрывателе, как я могу позволить моему поисковому бару вернуться к отправной точке после того, как я нажал кнопку остановки? и установить текстовое поле общей продолжительности и текущей позиции на нуль? Проблема происходит, когда я нажимаю остановить, а затем нажмите кнопку воспроизведения? в моем журнале кошки ошибка «Попытка вызвать getDuration без действительного медиаплеера»андроид, контроллер песен и панель поиска в медиаплеере

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    setVolumeControlStream(AudioManager.STREAM_MUSIC); 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    ImageButton play_btn= (ImageButton) findViewById(R.id.iv_play); 
    ImageButton backward_btn=(ImageButton)findViewById(R.id.imageView_backward); 
    ImageButton forward_btn= (ImageButton) findViewById(R.id.imageView_forward); 
    ImageButton stop_btn= (ImageButton) findViewById(R.id.imageView_stop); 
    ImageButton pause_btn= (ImageButton)findViewById(R.id.imageView_pause); 
    ImageButton shuffle_btn = (ImageButton) findViewById(R.id.imageView_shuffle);   
    song = MediaPlayer.create(getApplicationContext() ,R.raw.adele); 
    songProgressBar= (SeekBar) findViewById(R.id.seekBar1); 

    songProgressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { 

     @Override 
     public void onStopTrackingTouch(SeekBar seekBar) { 
      // TODO Auto-generated method stub 
      mHandler.removeCallbacks(mUpdateTimeTask); 
       int totalDuration = song.getDuration(); 
       int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration); 
       song.seekTo(currentPosition); 
       UpdateProgressBar(); 

     } 

     @Override 
     public void onStartTrackingTouch(SeekBar seekBar) { 
      // TODO Auto-generated method stub 

     } 

     @Override 
     public void onProgressChanged(SeekBar seekBar, int progress, 
       boolean fromUser) { 
      // TODO Auto-generated method stub 


     } 
    }); 
    pause_btn.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      PauseSong();   } 
     private void PauseSong() { 
      // TODO Auto-generated method stub 
      song.pause();    
     } 
    }); 
    stop_btn.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      StopSong(); 
     } 
     private void StopSong() { 
      // TODO Auto-generated method stub 
      song.stop(); 

     } 
    }); 

    play_btn.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      PlaySong(); 
     } 
     private void PlaySong() { 
      // TODO Auto-generated method stub 
      song.start(); 
      songProgressBar.setProgress(0); 
      songProgressBar.setMax(100); 
      UpdateProgressBar(); 

     } 
     }); 
} 
private void UpdateProgressBar() { 

    // TODO Auto-generated method stub 
    mHandler.postDelayed(mUpdateTimeTask, 100); 
} 

Runnable mUpdateTimeTask = new Runnable() { 


     @Override 
     public void run() { 
      // TODO Auto-generated method stub 
      totalDuration = song.getDuration(); 
       currentDuration = song.getCurrentPosition(); 
       // Displaying Total Duration time 
       songTotalDurationLabel = (TextView)findViewById(R.id.songTotalDurationLabel); 
       songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration)); 
       // Displaying time completed playing 
       songCurrentDurationLabel = (TextView)findViewById(R.id.songCurrentDurationLabel); 
       songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration)); 

       // Updating progress bar 
       int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration)); 
       Log.d("Progress", ""+progress); 
       songProgressBar.setProgress(progress); 

       // Running this thread after 100 milliseconds 
       mHandler.postDelayed(this, 100); 
     } 
    }; 
    protected void onPause() {finish();} 

    @Override 
    protected void onDestroy() { 
     // TODO Auto-generated method stub 
     super.onDestroy(); 
     finish(); 
    } 
@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
} 

}

ответ

0

Получить длительность от onPrepared обратного вызова. ..это будет гарантировать, что музыка (аудио) будет правильно загружена, прежде чем вы попытаетесь получить ее продолжительность.

song.setOnPreparedListener(new OnPreparedListener() { 
    public void onPrepared(MediaPlayer song) { 
     int duration = song.getDuration(); 
     song.start(); 
     controller.show(); 
    } 
}); 

StopSong():

private void StopSong() { 
    if (song != null) { 
     song.stop(); 
     song.release(); 
    } 
} 

для продолжительности текстового поля, то я использовал глобальную переменную для доступа всех функций.

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    int totalDuration 0; 
    . 
    . 
    . 
     @Override 
     public void onStopTrackingTouch(SeekBar seekBar) { 
      // TODO Auto-generated method stub 
      mHandler.removeCallbacks(mUpdateTimeTask); 
      totalDuration = song.getDuration(); // here 
    . 
    . 
    . 

     private void StopSong() { 
      if (song!=null) { 
       song.stop(); 
       song.release(); 
       totalDuration = 0; // here 
     } 

Надеюсь, это поможет!

+0

спасибо за ваш совет, я обновил свой вопрос, и ваша ссылка поможет мне решить мою проблему. – tasneem

 Смежные вопросы

  • Нет связанных вопросов^_^