2016-07-08 401 views
2

我對於noobish問題表示歉意,但我在android studio中構建音樂播放器,並且遇到播放列表之類的歌曲出現問題。歌曲只能手工拾取,歌曲完成後纔會停止,直到用戶點擊另一首歌曲。我寫了兩段代碼,我懷疑會解決這個問題,但我不確定如何實現它們,或者如果它們最終將有任何用處。我真的很感謝一些幫助,真的可以真正使用它。任何建議或建設性的批評總是歡迎,事先感謝。這裏的片段:Android Studio音樂播放器列表視圖播放列表

//------------> to get the next song <--------------- 
int itemsInList=list.getAdapter().getCount(); 
for(int i=1;i<itemsInList;i++){ 
    list.setSelection(i); 
} 
//--------------> to play the song on list item click <------------------- 
@Override 
protected void onListItemClick(ListView list, View view, int position, 
long id) { 
    super.onListItemClick(list, view, position, id); 
    currentFile = (String) view.getTag(); 
    startPlay(currentFile); 
} 

而且僅作參考,這裏是我主要的Java文件:

public class MainActivity extends ListActivity { 

private static final int UPDATE_FREQUENCY = 500; 
private static final int STEP_VALUE = 4000; 

private MediaCursorAdapter mediaAdapter = null; 
private TextView selectedFile = null; 
private SeekBar seekbar = null; 
private MediaPlayer player = null; 
private ListView list = null; 
private ImageButton playButton = null; 
private ImageButton prevButton = null; 
private ImageButton nextButton = null; 
private ImageButton btNext = null; 
private ImageButton btPrev = null; 

private boolean isStarted = true; 
private String currentFile = ""; 
private boolean isMovingSeekBar = false; 

private final Handler handler = new Handler(); 

private final Runnable updatePositionRunnable = new Runnable() { 
    public void run() { 
     updatePosition(); 
    } 
}; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    selectedFile = (TextView) findViewById(R.id.selectedfile); 
    seekbar = (SeekBar) findViewById(R.id.seekbar); 
    playButton = (ImageButton) findViewById(R.id.play); 
    prevButton = (ImageButton) findViewById(R.id.prev); 
    nextButton = (ImageButton) findViewById(R.id.next); 
    btNext = (ImageButton) findViewById(R.id.btNxt); 
    btPrev = (ImageButton) findViewById(R.id.btPrev); 

    player = new MediaPlayer(); 

    player.setOnCompletionListener(onCompletion); 
    player.setOnErrorListener(onError); 
    seekbar.setOnSeekBarChangeListener(seekBarChanged); 

    Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null); 

    if (null != cursor) { 
     cursor.moveToFirst(); 

     mediaAdapter = new MediaCursorAdapter(this, R.layout.list_item, cursor); 

     setListAdapter(mediaAdapter); 

     playButton.setOnClickListener(onButtonClick); 
     nextButton.setOnClickListener(onButtonClick); 
     prevButton.setOnClickListener(onButtonClick); 
     btNext.setOnClickListener(onButtonClick); 
     btPrev.setOnClickListener(onButtonClick); 

    } 
} 

//----------- ??? ---------------------------------------------------------------- 
int itemsInList=list.getAdapter().getCount(); 
for(int i=1;i<itemsInList;i++){ 
    list.setSelection(i); 
} 

@Override 
protected void onListItemClick(ListView list, View view, int position, long id) { 
    super.onListItemClick(list, view, position, id); 
    currentFile = (String) view.getTag(); 
    startPlay(currentFile); 
} 
// -------------------------------------------------------------------------------- 

@Override 
protected void onDestroy() { 
    super.onDestroy(); 

    handler.removeCallbacks(updatePositionRunnable); 
    player.stop(); 
    player.reset(); 
    player.release(); 

    player = null; 
} 

private void startPlay(String file) { 
    Log.i("Selected: ", file); 

    selectedFile.setText(file); 
    seekbar.setProgress(0); 

    player.stop(); 
    player.reset(); 

    try { 
     player.setDataSource(file); 
     player.prepare(); 
     player.start(); 
    } catch (IllegalArgumentException e) { 
     e.printStackTrace(); 
    } catch (IllegalStateException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    seekbar.setMax(player.getDuration()); 
    playButton.setImageResource(android.R.drawable.ic_media_pause); 

    updatePosition(); 

    isStarted = true; 
} 

private void stopPlay() { 
    player.stop(); 
    player.reset(); 
    playButton.setImageResource(android.R.drawable.ic_media_play); 
    handler.removeCallbacks(updatePositionRunnable); 
    seekbar.setProgress(0); 

    isStarted = false; 
} 

private void updatePosition() { 
    handler.removeCallbacks(updatePositionRunnable); 

    seekbar.setProgress(player.getCurrentPosition()); 

    handler.postDelayed(updatePositionRunnable, UPDATE_FREQUENCY); 
} 

private class MediaCursorAdapter extends SimpleCursorAdapter { 

    public MediaCursorAdapter(Context context, int layout, Cursor c) { 
     super(context, layout, c, 
       new String[]{MediaStore.MediaColumns.DISPLAY_NAME, MediaStore.MediaColumns.TITLE, MediaStore.Audio.AudioColumns.DURATION}, 
       new int[]{R.id.displayname, R.id.title, R.id.duration}); 
    } 

    @Override 
    public void bindView(View view, Context context, Cursor cursor) { 
     TextView title = (TextView) view.findViewById(R.id.title); 
     TextView name = (TextView) view.findViewById(R.id.displayname); 
     TextView duration = (TextView) view.findViewById(R.id.duration); 

     name.setText(cursor.getString(
       cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME))); 

     title.setText(cursor.getString(
       cursor.getColumnIndex(MediaStore.MediaColumns.TITLE))); 

     long durationInMs = Long.parseLong(cursor.getString(
       cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION))); 

     double durationInMin = ((double) durationInMs/1000.0)/60.0; 

     durationInMin = new BigDecimal(Double.toString(durationInMin)).setScale(2, BigDecimal.ROUND_UP).doubleValue(); 

     duration.setText("" + durationInMin); 

     view.setTag(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA))); 
    } 

    @Override 
    public View newView(Context context, Cursor cursor, ViewGroup parent) { 
     LayoutInflater inflater = LayoutInflater.from(context); 
     View v = inflater.inflate(R.layout.list_item, parent, false); 

     bindView(v, context, cursor); 

     return v; 
    } 
} 

private View.OnClickListener onButtonClick = new View.OnClickListener() { 

    @Override 
    public void onClick(View v) { 
     switch (v.getId()) { 
      case R.id.play: { 
       if (player.isPlaying()) { 
        handler.removeCallbacks(updatePositionRunnable); 
        player.pause(); 
        playButton.setImageResource(android.R.drawable.ic_media_play); 
       } else { 
        if (isStarted) { 
         player.start(); 
         playButton.setImageResource(android.R.drawable.ic_media_pause); 

         updatePosition(); 
        } else { 
         startPlay(currentFile); 
        } 
       } 

       break; 
      } 
      case R.id.next: { 
       int seekto = player.getCurrentPosition() + STEP_VALUE; 

       if (seekto > player.getDuration()) 
        seekto = player.getDuration(); 

       player.pause(); 
       player.seekTo(seekto); 
       player.start(); 

       break; 
      } 
      case R.id.prev: { 
       int seekto = player.getCurrentPosition() - STEP_VALUE; 

       if (seekto < 0) 
        seekto = 0; 

       player.pause(); 
       player.seekTo(seekto); 
       player.start(); 

       break; 
      } 
      case R.id.btNxt: { 
      //TO DO 
      } 
      case R.id.btPrev: { 
      //TO DO 
      } 
     } 
    } 
}; 

private MediaPlayer.OnCompletionListener onCompletion = new MediaPlayer.OnCompletionListener() { 

    @Override 
    public void onCompletion(MediaPlayer mp) { 
     stopPlay(); 
    } 
}; 

private MediaPlayer.OnErrorListener onError = new MediaPlayer.OnErrorListener() { 

    @Override 
    public boolean onError(MediaPlayer mp, int what, int extra) { 

     return false; 
    } 
}; 

private SeekBar.OnSeekBarChangeListener seekBarChanged = new SeekBar.OnSeekBarChangeListener() { 
    @Override 
    public void onStopTrackingTouch(SeekBar seekBar) { 
     isMovingSeekBar = false; 
    } 

    @Override 
    public void onStartTrackingTouch(SeekBar seekBar) { 
     isMovingSeekBar = true; 
    } 

    @Override 
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { 
     if (isMovingSeekBar) { 
      player.seekTo(progress); 

      Log.i("OnSeekBarChangeListener", "onProgressChanged"); 
     } 
    } 
}; 

}

+0

你是否能夠在服務中播放歌曲如果是的話你是如何改變立場的? – SAVVY

回答

3

你可以看一下我的方法,下面播放下一首歌曲。希望能幫助到你。

public static void nextSong() { 
     int numOfSong = songList.size(); 

     if (!isShuffle) { // Shuffle mode is off 
      if (currentPosition < numOfSong - 1) { 
       currentPosition++; 
       currentSong = songList.get(currentPosition); 
       Log.d("my_log", "position = "+currentPosition); 
       playBackMusic(); 
      } else { 
       currentPosition = 0; 
       currentSong = songList.get(currentPosition); 
       Log.d("my_log", "position = "+currentPosition); 
       playBackMusic(); 
      } 
     } else { // Shuffle mode is on 
      Random rand = new Random(); 
      currentPosition = rand.nextInt(numOfSong); 
      currentSong = songList.get(currentPosition); 
      Log.d("my_log", "position = "+currentPosition); 
      playBackMusic(); 
     } 
    } 

這是播放歌曲playBackMusic()方法:

public static void playBackMusic() { 
     try { 
      mediaPlayer.release(); 

      mediaPlayer = new MediaPlayer(); 
      mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); 
      mediaPlayer.setDataSource(currentSong.getPath()); 
      mediaPlayer.prepare(); 

      mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { 
       @Override 
       public void onCompletion(MediaPlayer mp) { 
        endOfTheSong(); 
       } 
      }); 

      isPlaying = true; 
      mediaPlayer.start(); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

方法endOfTheSong()來處理播放當前歌曲後做什麼。

public static void endOfTheSong() { 
     if (isRepeat == 1) { // currently repeat one song 
      mediaPlayer.seekTo(0); 
      mediaPlayer.start(); 
     } else if (isRepeat == 2) { // currently repeat all songs 
      nextSong(); 
     } else { // currently no repeat 

      if (currentPosition != songList.size() - 1) nextSong(); 

     } 
    } 
+0

看起來很有希望,但請您詳細說明endOfTheSong()從哪裏來的? – Konrad

+0

檢查編輯後的答案:) –