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

时间:2019-02-07 14:19:11

标签: android

我正在创建Mp3播放器。我已成功从设备中获取歌曲名称和艺术家并显示在列表视图中,现在的问题是,如果任何用户单击特定项目的歌曲,则在播放之前会播放任何歌曲,它将自动停止并播放新用户单击,我也想从我的列表视图中获取歌曲名称和歌手姓名。

请在这里为我提供所有代码

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;


    }
}

2 个答案:

答案 0 :(得分:0)

官方文档说:但是,当您调用stop()时,请注意,直到您再次准备MediaPlayer才能再次调用start()。 https://developer.android.com/guide/topics/media/mediaplayer

因此,您需要做的是在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();

用于为手机存储中存在的音频文件创建URI:

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

在列表项的onClickListener中写以下几行(检查拼写),然后准备媒体播放器类

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

更新: 搜索完代码后,我发现您没有从游标获取文件路径。

当前,您只获得 MediaStore.Audio.Media.TITLE,MediaStore.Audio.Media._ID MediaStore.Audio.Media.ARTIST

  • 您还将需要 MediaStore.Audio.Media.DATA 来获取音频文件的路径。因此,只需在Song类中添加另一个变量,该变量将保存光标所在的文件路径。 当您获得光标时添加这些行-

    int dataColumn = musicCursor.getColumnIndex                                 (android.provider.MediaStore.Audio.Media.DATA); //现在将其添加到歌曲列表中

    String thisDataPath = musicCursor.getString(dataColumn);
    

现在,您可以通过-

轻松构造每个音频文件的Uri。
Uri uri= Uri.parse("file:///"+song.getPath());

无需使用Uri.withAppendPath()。只需使用上面的行,然后设置音乐播放器的数据源

答案 1 :(得分:0)

TypeApplications

您列表的onClickListener看起来像-

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

        }