如何在所有活动和片段中使用MediaPlayer的单个实例?

时间:2017-10-29 12:23:34

标签: android singleton android-mediaplayer audio-player android-music-player

我有几个活动和片段显示来自SD卡的歌曲,当我点击其中任何一个时,它会播放。问题是我必须在每个活动和片段中创建一个新的媒体播放器实例。因此,如果我在一个活动中播放一首歌并在另一个活动中播放另一个活动,则两首歌都会同时播放。我阅读了关于单身类和使媒体播放器静态但我需要更多信息。以下是我的代码。

public class ArtistSongAlbumSong extends AppCompatActivity {

ArrayList<SongInfoModel> ArtistSongAlbumSongList = new ArrayList<>();

RecyclerView recyclerView_artistalbumsongs;

ArtistSongAlbumSongAdapter artistSongAlbumSongAdapter;

private static MediaPlayer player = new  MediaPlayer();

Context isContext;

private int currentIndex;


@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_artistsongallsong);

    recyclerView_artistalbumsongs = findViewById(R.id.recyclerView_artistSongAllSong);

    isContext = ArtistSongAlbumSong.this;

    Long albumid = getIntent().getExtras().getLong("album_id");

    LinearLayoutManager aslinearLayoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerView_artistalbumsongs.setLayoutManager(aslinearLayoutManager);


    Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

    String selection = MediaStore.Audio.Media.IS_MUSIC + "!=0";
    Cursor cursor = getApplicationContext().getContentResolver().query(uri, null, selection, null, null);
    if (cursor != null) {
        if (cursor.moveToFirst()) {
            do {
                String name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
                String nameArtist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
                Long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
                Long newAlbumId = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
                Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
                Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, albumid);

                if (newAlbumId.equals(albumid)) {

                    SongInfoModel s6 = new SongInfoModel(name, nameArtist, duration, data, albumArtUri);
                    ArtistSongAlbumSongList.add(s6);
                }

            } while (cursor.moveToNext());
        }


        cursor.close();

        Collections.sort(ArtistSongAlbumSongList, new Comparator<SongInfoModel>() {
            @Override
            public int compare(SongInfoModel lhs, SongInfoModel rhs) {
                return lhs.getSongName().compareTo(rhs.getSongName());
            }
        });


    }





    artistSongAlbumSongAdapter = new ArtistSongAlbumSongAdapter(getApplicationContext(), ArtistSongAlbumSongList);

    artistSongAlbumSongAdapter.onItemClickListener(new ArtistSongAlbumSongAdapter.ArtistSongAlbumSongListener() {
        @Override
        public void onClickListener(SongInfoModel songInfoModel, int position, RelativeLayout relativeLayout, View view) {
            MainActivity.setsongText(songInfoModel);
            MainActivity.ButtonPlay();
            MainActivity.PauseImage();

            changeSelectedSong(position);
            prepareSong(songInfoModel);

        }

        @Override
        public void onLongClickListener(SongInfoModel songInfoModel, int position, RelativeLayout relativeLayout, View view) {

        }
    });

    recyclerView_artistalbumsongs.setAdapter(artistSongAlbumSongAdapter);


    player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mediaPlayer) {

            togglePlay(mediaPlayer);

        }
    });

    player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            onSongCompletion1(mediaPlayer);
        }
    });




}



public void prepareSong(SongInfoModel song) {

    player.reset();


    try {
        player.setDataSource(song.getData());
        player.prepareAsync();
    } catch (IOException e) {
        e.printStackTrace();
    }

}


private void togglePlay(MediaPlayer mp) {

    if (mp.isPlaying()) {
        mp.stop();
        mp.reset();

    } else {

        mp.start();


        MainActivity.Handler(mp);


    }


}

private void changeSelectedSong(int index){
  //  artistSongAlbumSongAdapter.notifyItemChanged(artistSongAlbumSongAdapter.getSelectedPosition());
    currentIndex = index;
    artistSongAlbumSongAdapter.setSelectedPosition(currentIndex);
  //  artistSongAlbumSongAdapter.notifyItemChanged(currentIndex);

}




private void onSongCompletion1(MediaPlayer mediaPlayer) {


    if(currentIndex + 1 < ArtistSongAlbumSongList.size()){
        SongInfoModel next  = ArtistSongAlbumSongList.get(currentIndex +1);
        changeSelectedSong(currentIndex + 1);
        prepareSong(next);
        MainActivity.setsongText(next);
    }else{

        SongInfoModel next1  = ArtistSongAlbumSongList.get(0);
        changeSelectedSong(0);
        prepareSong(ArtistSongAlbumSongList.get(0));
        MainActivity.setsongText(next1);
    }

}

Singleton类:

public class MyMediaPlayer extends MediaPlayer  {

private static MyMediaPlayer mpclass ;




private MyMediaPlayer() {

}

public static MyMediaPlayer getInstance() {
    if (mpclass == null) {
        synchronized (MyMediaPlayer.class) {
            if (mpclass == null) {
                mpclass = new MyMediaPlayer();
            }
        }
    }

    return mpclass;
}

1 个答案:

答案 0 :(得分:0)

您需要按照以下步骤

1)创建一个服务来播放音频并在此处创建Media Player实例 2)将其绑定在活动中(可以是您的基础活动) 3)在活动中使用服务重新引用来获取媒体播放器实例并完成。在所有片段

中的活动中使用此实例