简体   繁体   English

单击项目时播放Listview特定歌曲?

[英]Listview specific songs play when click on item?

I am creating Mp3 player. 我正在创建Mp3播放器。 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. 官方文档说:但是,当您调用stop()时,请注意,直到您再次准备MediaPlayer才能再次调用start()。 https://developer.android.com/guide/topics/media/mediaplayer 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. 因此,您需要做的是在listview的onClick()侦听器中再次准备MediaPlayer实例(对象)。

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: 为手机存储中存在的音频文件创建URI:

(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) (由于您已经有基本的Uri指向音频文件所在的文件夹,因此您需要在文件名后附加文件名以获取每个文件的Uri)

Write the following lines (check for spelling) in the onClickListener of the list item and then prepare the media player class 在列表项的onClickListener中编写以下几行(检查拼写),然后准备媒体播放器类

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 . 当前,您只获得MediaStore.Audio.Media.TITLE,MediaStore.Audio.Media._IDMediaStore.Audio.Media.ARTIST

  • You will also need MediaStore.Audio.Media.DATA to get the path of the audio file. 您还将需要MediaStore.Audio.Media.DATA来获取音频文件的路径。 So, simply add another variable in your Song class that will hold this file path from the cursor. 因此,只需在Song类中添加另一个变量,该变量将保存光标所在的文件路径。 Add these lines when you get the cursor- 当您获得光标时添加以下行:

    int dataColumn = musicCursor.getColumnIndex (android.provider.MediaStore.Audio.Media.DATA); 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= Uri.parse("file:///"+song.getPath());

No need to use the Uri.withAppendPath(). 无需使用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- 您的列表的onClickListener看起来像-

 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();



                }
            });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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