我正在开发和应用,其中包括其他功能,用于播放音轨。有一个导航抽屉活动,当单击抽屉菜单选项时,它会启动一个片段。有两个片段在“媒体播放器”功能中起作用:
为了播放歌曲,用户选择TracksListFragment中的一首歌曲,然后打开PlayerFragment播放该特定歌曲。
此时我可以播放一首歌,暂停并继续播放。如果我暂停一首歌并尝试播放另一首歌,它也能正常工作。当我正在播放一首歌时,我的设置失败,我尝试播放不同的歌曲:两个曲目同时播放。我建议here
避免使用单例方法到目前为止我尝试过:
MediaPlayer = new MediaPlayer();
切换到MediaPlayer mediaPlayer = MediaPlayer.create(getActivity(), Uri.parse(songPath));
有人可以解释为什么要创建新的MediaPlayer对象,即使我试图摆脱现有对象,我做错了什么?
这是我对PlayerFragment的Fragment类:
public class PlayerFragment extends Fragment {
public String currentTrack;
private TextView currentTrackText;
private MediaPlayer mediaPlayer;
private ImageButton trackButtonPlayPause;
private Integer length;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater
.inflate(R.layout.fragment_player, container, false);
currentTrackText = (TextView) rootView.findViewById(trackTitleText);
trackButtonPlayPause = (ImageButton) rootView.findViewById(R.id.trackButtonPlayPause);
MenuActivity activity = (MenuActivity) getActivity();
String currentTrack = activity.getTrackInfoToBePlayed();
String currentPath = activity.getTrackPathToBePlayed();
currentTrackText.setText(currentTrack);
playSong(currentPath);
// Register Button Click event
trackButtonPlayPause.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if(isPlaybackOn() == true){
Log.e("PLAYER ---> ", "Song playing->pause");
mediaPlayer.pause();
trackButtonPlayPause.setImageResource(R.drawable.icon_track_play);
length=mediaPlayer.getCurrentPosition();
}else{
Log.e("PLAYER ---> ", "Song not playing->resume");
mediaPlayer.seekTo(length);
trackButtonPlayPause.setImageResource(R.drawable.icon_pause);
mediaPlayer.start();
}
}
});
return rootView;
}
public void playSong(String songPath){
try {
if (mediaPlayer != null) {
try {
mediaPlayer.release();
mediaPlayer = null;
} catch (Exception e) {
}
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(songPath);
mediaPlayer.prepare();
mediaPlayer.start();
}else{
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(songPath);
mediaPlayer.prepare();
mediaPlayer.start();
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public boolean isPlaybackOn(){
AudioManager manager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
if(manager.isMusicActive())
{
return true;
}else{
return false;
}
}
public void stopSong(){
// to be implemented
}
}
TracksListFragment:
public class TracksListFragment extends Fragment {
private int lastExpandedPosition = -1;
private ArrayList<Song> songList;
private ExpandableListView songView;
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater
.inflate(R.layout.fragment_moja_muzyka, container, false);
// get the listview
expListView = (ExpandableListView) rootView.findViewById(R.id.tracks);
// query songs
songView = (ExpandableListView)rootView.findViewById(R.id.tracks);
songList = new ArrayList<Song>();
getSongList();
SongAdapter songAdt = new SongAdapter(rootView.getContext(), songList,listDataHeader,listDataChild);
songView.setAdapter(songAdt);
// Listview Group click listener
songView.setOnGroupClickListener(new OnGroupClickListener() {
@Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
Toast.makeText(getActivity().getApplicationContext(),
"Group Clicked " + listDataHeader.get(groupPosition),
Toast.LENGTH_SHORT).show();
return false;
}
});
// Listview Group expanded listener
songView.setOnGroupExpandListener(new OnGroupExpandListener() {
@Override
public void onGroupExpand(int groupPosition) {
// hide all groups but clicked
if (lastExpandedPosition != -1 && groupPosition != lastExpandedPosition) {
expListView.collapseGroup(lastExpandedPosition);
}
lastExpandedPosition = groupPosition;
}
});
// Listview Group collasped listener
songView.setOnGroupCollapseListener(new OnGroupCollapseListener() {
@Override
public void onGroupCollapse(int groupPosition) {
}
});
// Listview on child click listener
songView.setOnChildClickListener(new OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
return false;
}
});
return rootView;
}
public void getSongList() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
Integer audioCounter = -1;
ContentResolver musicResolver = getActivity().getContentResolver();
String fileExtension = MimeTypeMap.getSingleton().getMimeTypeFromExtension("mp3");
String sel = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
String[] selExtARGS = new String[]{fileExtension};
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor songCursor = musicResolver.query(musicUri, null, sel, selExtARGS, null);
if(songCursor!=null && songCursor.moveToFirst()){
//get columns
int titleColumn = songCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = songCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media._ID);
int artistColumn = songCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.ARTIST);
int albumColumn = songCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.ALBUM);
int mimeColumn = songCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.MIME_TYPE);
int fullpathColumn = songCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.DATA);
//add songs to list
do {
audioCounter++;
long thisId = songCursor.getLong(idColumn);
String thisTitle = songCursor.getString(titleColumn);
String thisArtist = songCursor.getString(artistColumn) ;
String thisAlbum = songCursor.getString(albumColumn);
String thisPath = songCursor.getString(fullpathColumn);
if(thisArtist.toLowerCase().contains("unknown")){
thisArtist = getResources().getString(R.string.textSongNoArtistAvailable);
}
if(thisAlbum.toLowerCase().contains("music")){
thisAlbum = getResources().getString(R.string.textSongNoAlbumAvailable);
}
String thisMime = songCursor.getString(mimeColumn);
listDataHeader.add(thisTitle);
List<String> songDetails = new ArrayList<String>();
songDetails.add(thisTitle);
listDataChild.put(listDataHeader.get(audioCounter), songDetails);
songList.add(new Song(thisPath,thisId, thisTitle, thisArtist, thisAlbum));
}
while (songCursor.moveToNext());
}
}
}