简体   繁体   中英

Android Music Player

I am making an Music Player App.I have two different Fragments for SongsList (SongList.java) and Mediaplayer Controls(ie Mediaplayer.java that includes play, pause buttons). Now, i want to connect my SongsList.java with Mediaplayer.java. I want to select a song from SongsList.java which gets played in Mediaplayer.java. How do I do ? PLEASE HELP !!!

SongList.java

 import android.app.Fragment;
 import android.content.ContentResolver;
 import android.database.Cursor;
 import android.net.Uri;
 import android.os.Bundle;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.ListView;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Comparator;

 public class Songlist extends Fragment {
 private ArrayList<Song> songList;
 private ListView songView;


 @Override
 public View onCreateView(LayoutInflater inflater,
                     ViewGroup container, Bundle savedInstanceState) {

//Inflate the layout for this fragment
View view=inflater.inflate(
        R.layout.songs, container, false);
songView = (ListView)view.findViewById(R.id.song_list);

songList = new ArrayList<Song>();
getSongList();
Collections.sort(songList, new Comparator<Song>() {
    public int compare(Song a, Song b) {
        return a.getTitle().compareTo(b.getTitle());
    }
});
SongAdapter songAdt = new SongAdapter(getActivity(), songList);
songView.setAdapter(songAdt);

songView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            ///////////////////WHAT TO DO HERE!//////////////////
        }
    });

return view;
}

public void getSongList() {
//retrieve song info
ContentResolver musicResolver = getActivity().getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
if(musicCursor!=null && musicCursor.moveToFirst()){
    //get columns
    int titleColumn = musicCursor.getColumnIndex
            (android.provider.MediaStore.Audio.Media.TITLE);
    int idColumn = musicCursor.getColumnIndex
            (android.provider.MediaStore.Audio.Media._ID);
    int artistColumn = musicCursor.getColumnIndex
            (android.provider.MediaStore.Audio.Media.ARTIST);
    //add songs to list
    do {
        long thisId = musicCursor.getLong(idColumn);
        String thisTitle = musicCursor.getString(titleColumn);
        String thisArtist = musicCursor.getString(artistColumn);
        songList.add(new Song(thisId, thisTitle, thisArtist));
    }
    while (musicCursor.moveToNext());
}
}
}

MediaPlayer.java (Some buttons not implemented yet)

import android.app.Fragment;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle; 
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;

 import java.util.concurrent.TimeUnit;


 public class Mediaplayer  extends Fragment{

 Drawable shuffle1,back1,play1,next1,repeat1;

 ImageButton shuffle,back,play,next,repeat;
 TextView start,end,artist,song;
 SeekBar songprogress;
 private MediaPlayer mediaPlayer;
 private double startTime = 0;
 private double finalTime = 0;
 private Handler myHandler = new Handler();;



    @Override
   public View onCreateView(LayoutInflater inflater,
                     ViewGroup container, Bundle savedInstanceState) {

//Inflate the layout for this fragment
View view=inflater.inflate(
        R.layout.content_main, container, false);
start=(TextView)view.findViewById(R.id.songCurrentDurationLabel);
end=(TextView)view.findViewById(R.id.songTotalDurationLabel);
song=(TextView)view.findViewById(R.id.song_title);
artist=(TextView)view.findViewById(R.id.songArtist);


shuffle=(ImageButton)view.findViewById(R.id.shuffle);
back=(ImageButton)view.findViewById(R.id.back);
play=(ImageButton)view.findViewById(R.id.play);
next=(ImageButton)view.findViewById(R.id.next);
repeat=(ImageButton)view.findViewById(R.id.repeat);
songprogress = (SeekBar) view.findViewById(R.id.songProgressBar);

  mediaPlayer = MediaPlayer.create(getActivity(),R.raw.song);
  mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()      {
  @Override
   public void onCompletion(MediaPlayer mp) {
   play1 =
        getResources().getDrawable(R.drawable.play);
  play.setImageDrawable(play1);

  songprogress.setProgress(0);

  }
  });
   play.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        songprogress.setClickable(true);

        if(!mediaPlayer.isPlaying()) {

            mediaPlayer.start();
            finalTime = mediaPlayer.getDuration();
            startTime = mediaPlayer.getCurrentPosition();

            play1 =
                    getResources().getDrawable(R.drawable.pause);
            play.setImageDrawable(play1);


            songprogress.setMax((int) finalTime);

            end.setText(String.format("%d.%d",
                            TimeUnit.MILLISECONDS.toMinutes((long) finalTime),
                            TimeUnit.MILLISECONDS.toSeconds((long) finalTime) -
                                    TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) finalTime)))
            );

            start.setText(String.format("%d.%d",
                            TimeUnit.MILLISECONDS.toMinutes((long) startTime),
                            TimeUnit.MILLISECONDS.toSeconds((long) startTime) -
                                    TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) startTime)))
            );

            songprogress.setProgress((int) startTime);
            myHandler.postDelayed(UpdateSongTime, 100);



        }else{
            mediaPlayer.pause();
            play1 =
                    getResources().getDrawable(R.drawable.play);
            play.setImageDrawable(play1);
        }
    }
   });
   songprogress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if(mediaPlayer != null && fromUser){
            mediaPlayer.seekTo(progress);
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }
});

return view;
}
private Runnable UpdateSongTime = new Runnable() {
public void run() {
    startTime = mediaPlayer.getCurrentPosition();
    start.setText(String.format("%d.%d",

                    TimeUnit.MILLISECONDS.toMinutes((long) startTime),
                    TimeUnit.MILLISECONDS.toSeconds((long) startTime) -
                            TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.
                                    toMinutes((long) startTime)))
    );
    songprogress.setProgress((int)startTime);
    myHandler.postDelayed(this, 100);
}
};
}

SongAdapter.java

 import android.view.View; 
 import android.view.ViewGroup;
 import android.widget.BaseAdapter;
 import java.util.ArrayList;
 import android.content.Context;
 import android.view.LayoutInflater;
 import android.widget.LinearLayout;
 import android.widget.TextView;


public class SongAdapter extends BaseAdapter {
 private ArrayList<Song> songs;
private LayoutInflater songInf;
public SongAdapter(Context c, ArrayList<Song> theSongs){
    songs=theSongs;
    songInf=LayoutInflater.from(c);
}
@Override
public int getCount() {
    return songs.size();
}

@Override
public Object getItem(int position) {
    return null;
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    //map to song layout
    LinearLayout songLay = (LinearLayout)songInf.inflate
            (R.layout.songlistitem, parent, false);
    //get title and artist views
    TextView songView = (TextView)songLay.findViewById(R.id.song_title);
    TextView artistView = (TextView)songLay.findViewById(R.id.song_artist);
    //get song using position
    Song currSong = songs.get(position);
    //get title and artist strings
    songView.setText(currSong.getTitle());
    artistView.setText(currSong.getArtist());
    //set position as tag
    songLay.setTag(position);
    return songLay;
}
}

To get the details of selected song, you can get by the adapter in the method onItemClick() like this:

@Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Toast.makeText(MainActivity.this,
                "" + mAdapter.getItem(position), Toast.LENGTH_SHORT).show();
    }

Add Event Listener to ListView:

mWordListLV.setOnItemClickListener(this);

You can simply use Songig MusicPlayer library for android. Songig handle all your music playlist and let you to manage your list with many callbacks. you can bind many ui to songig for change them when needed. for example you can bind 2 seekbars to songig and songig will change progress of them in every update.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM