简体   繁体   中英

Listview specific songs play when click on item?

I am creating Mp3 player. I am successfully fetch songs name and artist from my device and display it on list view, now my problem is that when any user clicks on specific item songs will play if any songs play before it it will automatically stop and play new song which user is click and i also want get song name and artist name from my listview.

Please help me here my all code

package com.monstertechno.musicplayerappui;
import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.renderscript.Sampler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import com.sothree.slidinguppanel.SlidingUpPanelLayout;
import com.sothree.slidinguppanel.SlidingUpPanelLayout.PanelState;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

    public class MainActivity extends AppCompatActivity {
      MediaPlayer mediaPlayer;
        private ArrayList<Song> songList;
        private ListView songView;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            runtimpermission();
            songView = (ListView) findViewById(R.id.song_list);
            songList = new ArrayList<Song>();
            SongAdapter songAdt = new SongAdapter(this, songList);
            songView.setAdapter(songAdt);
            getSongList();
            Collections.sort(songList, new Comparator<Song>() {
                public int compare(Song a, Song b) {
                    return a.getTitle().compareTo(b.getTitle());
                }
            });

            songView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if(mediaPlayer!=null){
                        mediaPlayer.release();
                    }



                }
            });

        }




        public void  runtimpermission(){

            Dexter.withActivity(this)
                    .withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)

                    .withListener(new PermissionListener() {
                        @Override public void onPermissionGranted(PermissionGrantedResponse response) {
                            Toast.makeText(MainActivity.this, "Permisson Access", Toast.LENGTH_SHORT).show();

                        }
                        @Override public void onPermissionDenied(PermissionDeniedResponse response) {

                            Toast.makeText(MainActivity.this, "Permisson Denied", Toast.LENGTH_SHORT).show();
                         }
                        @Override


                        public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {


                            token.continuePermissionRequest();}
                    }).check();

        }

        public void getSongList() {
            //retrieve song info
            ContentResolver musicResolver = 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());
            }

        }

    }







package com.monstertechno.musicplayerappui;

public class Song {
    private long id;
    private String title;
    private String artist;

    public Song(long songID, String songTitle, String songArtist) {
        id=songID;
        title=songTitle;
        artist=songArtist;
    }

    public long getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    public String getArtist() {
        return artist;
    }
}



package com.monstertechno.musicplayerappui;

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

import java.util.ArrayList;

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() {
        // TODO Auto-generated method stub
        return songs.size();
    }

    @Override
    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public long getItemId(int arg0) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View arg1, ViewGroup parent) {
        LinearLayout songLay = (LinearLayout)songInf.inflate
                (R.layout.musiccustom,parent , false);
        // TODO Auto-generated method stub
        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;


    }
}

The official documentation says: When you call stop(), however, notice that you cannot call start() again until you prepare the MediaPlayer again. https://developer.android.com/guide/topics/media/mediaplayer

So what you need to do is to prepare the MediaPlayer instance (object) again in your onClick() listener of listview.

MediaPlayer mediaPlayer = new 

MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url); //use it when your audio is in a network location
mediaPlayer.prepare(); // might take long! (for buffering, etc)
mediaPlayer.start();

For creating a URI to an audio file present in phone storage:

(Since you already have the base Uri to point to the folder where audio file is, you need to append the file name with it to get the Uri for each file)

Write the following lines (check for spelling) in the onClickListener of the list item and then prepare the media player class

Uri fileUri = Uri.withAppendedPath(musicURI,"the name of audio file");
mediaPlayer.setDataSource(fileUri);
mediaPlayer.prepare(); // 
mediaPlayer.start();

Update: After searching through your code, I found that you are not getting the file path from the cursor.

Currently, you are only getting MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media._ID and MediaStore.Audio.Media.ARTIST .

  • You will also need MediaStore.Audio.Media.DATA to get the path of the audio file. So, simply add another variable in your Song class that will hold this file path from the cursor. Add these lines when you get the cursor-

    int dataColumn = musicCursor.getColumnIndex (android.provider.MediaStore.Audio.Media.DATA); //Now add this to songs list

     String thisDataPath = musicCursor.getString(dataColumn); 

Now, you can easily construct the Uri of each audio file by-

Uri uri= Uri.parse("file:///"+song.getPath());

No need to use the Uri.withAppendPath(). Simply use the line above and then set the data source of music player

 public void getSongList() {
            //retrieve song info
            ContentResolver musicResolver = 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);
                int dataColumn= musicCursor.getColumnIndex
                        (android.provider.MediaStore.Audio.Media.DATA); //This will get you the column index of the file path

                //add songs to list
                do {
                    long thisId = musicCursor.getLong(idColumn);
                    String thisTitle = musicCursor.getString(titleColumn);
                    String thisArtist = musicCursor.getString(artistColumn);
                    String filePath= musicCursor.getString(dataColumn); //Get the file path from the cursor
                    songList.add(new Song(thisId, thisTitle, thisArtist,filePath)); // Make a list of Song objects along with path of each audio file
                }
                while (musicCursor.moveToNext());
            }

        }

Your onClickListener of list will look like-

 songView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if(mediaPlayer!=null){
                        mediaPlayer.release();

                    }
                            Song song=songList.get(position);
                            Toast.makeText(getActivity(),song.getFilePath(),Toast.LENGTH_LONG).show();
                            Uri uri= Uri.parse("file:///"+song.getPath());
                            mediaPlayer.setDataSource(fileUri);
                            mediaPlayer.prepare();
                            mediaPlayer.start();



                }
            });

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