2016-10-17 55 views
-2

我打通過URL音樂運作良好,但在時間上得到getDuration只返回0。Android的媒體播放器getDuration只返回0

我的代碼:

String AudioURL = link; 
      mediaplayer = new MediaPlayer(); 
      mediaplayer.setAudioStreamType(AudioManager.STREAM_MUSIC); 





      try { 

       mediaplayer.setDataSource(AudioURL); 
       mediaplayer.prepare(); 


       } catch (IllegalArgumentException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
       } catch (SecurityException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
       } catch (IllegalStateException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
       } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
       } 


       mediaplayer.start(); 


       mediaplayer.setOnPreparedListener(new OnPreparedListener() { 
        @Override 
        public void onPrepared(MediaPlayer mp) { 

         Log.e("error", "total duration: " + mp.getDuration()); 
         musica.progre.setProgress(0); 
         Log.e("MusicPP",""+mp.getDuration()); 
         musica.progre.setMax(mp.getDuration()); 

         Toast toast= Toast.makeText(musica.context, 
           "duration: "+mp.getDuration(), Toast.LENGTH_SHORT); 
           toast.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL, 0, 0); 
           toast.show(); 

          int duration = buscaMusica.mediaplayer.getDuration(); 
          musica.totalTempo.setText(musica.getTimeString(duration)); 


        } 

        }); 

       mediaplayer.setOnBufferingUpdateListener(new OnBufferingUpdateListener() { 

        @Override 
        public void onBufferingUpdate(MediaPlayer mp, int percent) { 
         musica.progre.setSecondaryProgress(mediaplayer.getCurrentPosition()); 

        } 
       }); 

回答

0

設置的URL MediaPlayer下面使用AsyncTask,所以在onPostExecute您將使用getDuration方法獲取時間:

private class Load extends AsyncTask<Void , Void , Void> 
{ 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     helper.show(); 
    } 

    @Override 
    protected Void doInBackground(Void... params) { 

     try { 
      mediaPlayer = MediaPlayer.create(getActivity() , uri); 
     } 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(Void aVoid) { 
     super.onPostExecute(aVoid); 
     helper.hide(); 
     seekBar.setProgress(0); 
     if (mediaPlayer!=null) 
     { 
     seekBar.setMax(mediaPlayer.getDuration()); 
     } 
     else{ 
      getActivity().finish(); 
      Toast.makeText(getActivity(), "Unable to load Announcement, try again later.",Toast.LENGTH_LONG).show(); 
     } 
     seekBar.setOnTouchListener(new View.OnTouchListener() { 
      @Override 
      public boolean onTouch(View v, MotionEvent event) { 
       seekChange(v); 
       return false; 
      } 
     }); 

    } 
}