从列表视图中单击歌曲后,新活动正在打开,但歌曲未在播放

时间:2019-06-27 10:44:28

标签: java android android-activity android-listview android-mediaplayer

我正在创建一个音乐播放器应用程序。我要从设备中获取歌曲列表,但是当我点击歌曲时,新活动正在打开,但歌曲并未播放,只是打开了活动而已

我多次检查已检查的代码,但未找到任何解决方案 如果我使用不同的方法来获取设备歌曲,则它可以工作,但该方法不能找到所有歌曲,而只能找到几首歌曲。

播放列表活动

public class PlayListActivity extends AppCompatActivity {
    private static final int MY_PERMISSIONS_REQUEST_READ = 7;
    private static final int REQUEST_PERMISSION = 5;
    private static final int MY_PERMISSIONS_REQUEST_READ_MEDIA = 99;
    public static ArrayList<TrackObjects> songsList;
    private ListView songView;
    ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.playlist);
        songView = (ListView) findViewById(R.id.songlist);
        songsList = new ArrayList<TrackObjects>();

        songView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int
                    position, long l) {
                Intent i1 = new Intent(PlayListActivity.this, MainActivity.class);
                i1.putExtra("pos", position);
                i1.putExtra("songs", songsList);
                startActivity(i1);

            }
        });

        int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        Collections.sort(songsList, new Comparator<TrackObjects>() {
            public int compare(TrackObjects a, TrackObjects b) {
                return a.getTitle().compareTo(b.getTitle());
            }
        });
        TracksAdapter songAdt = new TracksAdapter(PlayListActivity.this, songsList);
        songView.setAdapter(songAdt);

        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_MEDIA);
        } else {
            getSongList();
        }

    }

    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);
                songsList.add(new TrackObjects(thisId, thisTitle, thisArtist));
            }
            while (musicCursor.moveToNext());
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_READ_MEDIA:
                if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                    getSongList();
                }
                break;

            default:
                break;
        }

    }
}

MainActivity(歌曲演奏活动):

public class MainActivity extends AppCompatActivity {

    static MediaPlayer mp;
    int position;
    SeekBar sb;
    ArrayList mySongs;
    Thread updateSeekBar;
    ImageButton pause, forward, reverse, next, previous;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pause = (ImageButton) findViewById(R.id.pause);
        forward = (ImageButton) findViewById(R.id.forward);

        previous = (ImageButton) findViewById(R.id.previous);
        next = (ImageButton) findViewById(R.id.next);
        reverse = (ImageButton) findViewById(R.id.reverse);
        sb = (SeekBar) findViewById(R.id.seekBar);
        updateSeekBar = new Thread() {
            @Override
            public void run() {
                int totalDuration = mp.getDuration();
                int currentPosition = 0;
                while (currentPosition < totalDuration) {
                    try {
                        sleep(500);
                        currentPosition = mp.getCurrentPosition();
                        sb.setProgress(currentPosition);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        if (mp != null) {
            mp.stop();
            mp.release();
        }
        Intent i = getIntent();
        Bundle b = i.getExtras();
        assert b != null;
        mySongs = (ArrayList) b.getParcelableArrayList("songs");
        position = b.getInt("pos",0);
            Uri u = Uri.parse(mySongs.get(position).toString());
        if (mp!=null) {

            mp= (MediaPlayer) MediaPlayer.create(MainActivity.this, u);
                mp.start();

                sb.setMax(mp.getDuration());
                updateSeekBar.start();

                sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int i,
                                                  boolean b) {

                    }

                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {
                    }

                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                        mp.seekTo(seekBar.getProgress());
                    }
                });
                pause.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        sb.setMax(mp.getDuration());
                        if (mp.isPlaying()) {
                            pause.setBackgroundResource(R.mipmap.play_button);
                            mp.pause();

                        } else {
                            pause.setBackgroundResource(R.mipmap.pause);
                            mp.start();
                        }
                    }
                });
                forward.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        sb.setMax(mp.getDuration());
                        mp.seekTo(mp.getCurrentPosition() + 5000);
                    }
                });
                reverse.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        sb.setMax(mp.getDuration());
                        mp.seekTo(mp.getCurrentPosition() - 5000);
                    }
                });
                next.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mp.stop();
                        mp.release();
                        position = ((position + 1) % mySongs.size());
                        Uri u = Uri.parse(mySongs.get(position).toString());
                        mp = MediaPlayer.create(getApplicationContext(), u);
                        mp.start();
                    }
                });
                previous.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mp.stop();
                        mp.release();
                        position = ((position - 1) < 0) ? (mySongs.size() - 1) : (position - 1);
                        Uri u = Uri.parse(mySongs.get(
                                position).toString());//%mysongs so that it do not go to invalid position
                        mp = MediaPlayer.create(getApplicationContext(), u);
                        mp.start();
                    }
                });
            }
        }
    }

TracksAdapter(歌曲列表适配器):

public class TracksAdapter extends BaseAdapter {

    private ArrayList<TrackObjects> tracks;
    private LayoutInflater trackInf;

    public TracksAdapter(Context c, ArrayList<TrackObjects> theTracks) {
        tracks = theTracks;
        trackInf = LayoutInflater.from(c);
    }

    @Override
    public int getCount() {
        return tracks.size();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //map to song layout
        @SuppressLint("ViewHolder") LinearLayout songLay = (LinearLayout) trackInf.inflate
                (R.layout.songtracks, parent, false);
        //get title and artist views
        TextView trackView = (TextView) songLay.findViewById(R.id.track_title);
        TextView artistView = (TextView) songLay.findViewById(R.id.track_artist);
        //get song using position
        TrackObjects currSong = tracks.get(position);
        //get title and artist strings
        trackView.setText(currSong.getTitle());

        artistView.setText(currSong.getArtist());
        //set position as tag
        songLay.setTag(position);
        return songLay;
    }

    @Override
    public Object getItem(int position) {

        return null;
    }

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

TrackObjects(对象类):

public class TrackObjects implements Serializable {
    private long id;
    private String title;
    private String artist;

    public TrackObjects(long id, String title, String artist) {
        this.id = id;
        this.title = title;
        this.artist = artist;
    }
    protected TrackObjects(Parcel in) {
        id = in.readLong();
        title = in.readString();
        artist = in.readString();
    }
    public long getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    public String getArtist() {
        return artist;
    }
    {
    }}

1 个答案:

答案 0 :(得分:0)

问题是您没有将URL传递给MainActivity中的媒体播放器。您的代码如下:

mySongs = (ArrayList) b.getParcelableArrayList("songs");
position = b.getInt("pos",0);
Uri u = Uri.parse(mySongs.get(position).toString());

在这里

mySongs.get(position).toString();

它将从列表中返回TrackObjects,使用toString()将返回对象参考数据。因此,最终您不会将任何URL传递给媒体播放器。

解决方案: 在TrackObjects类中添加一个新的字符串变量,例如private String songUrl;,并在下一行而不是上一行

Uri u = Uri.parse(mySongs.get(position).getSongUrl());

希望它能解决您的问题。