如何在Android中播放新歌时停止播放旧歌?

时间:2016-09-15 08:58:17

标签: android

我是Android开发的新手,目前我正在开发一个简单的媒体播放器应用程序。

根据我的项目,我定义了三个片段。第一个片段是播放器片段,它显示媒体播放器控件并播放歌曲。第二个片段是包含歌曲列表的播放列表。第三个片段是最近的播放列表,其中包含最近播放的歌曲。

我的问题是如何从播放列表片段中选择新歌时停止播放旧歌?

PLAYER FRAGMENT。

public class Player extends Fragment implements SeekBar.OnSeekBarChangeListener{

private ImageButton btnPlay;
private ImageButton btnForward;
private ImageButton btnBackward;
private ImageButton btnNext;
private ImageButton btnPrevious;
private ImageButton btnRepeat;
private ImageButton btnShuffle;
private SeekBar songProgressBar;
private TextView songTitleLabel;
private TextView songCurrentDurationLabel;
private TextView songTotalDurationLabel;
// Media Player
public static MediaPlayer mp,mp2;
VisualizerView mVisualizerView;
SliderView sl;
private Visualizer mVisualizer;
// Handler to update UI timer, progress bar etc,.
private Handler mHandler = new Handler();;
private SongsManager songManager;
private Utilities utils;
private int seekForwardTime = 5000; // 5000 milliseconds
private int seekBackwardTime = 5000; // 5000 milliseconds
private int currentSongIndex = 0;
private boolean isShuffle = false;
private boolean isRepeat = false;
private ArrayList<SongModel> songsList = new ArrayList<SongModel>();
int songIndex;
SongAdapter songAdapter;

public Player(int position) {
    songIndex = position;
}

public Player() {

}


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View android = inflater.inflate(R.layout.player, container, false);
        /*ClickWheel wheel = (ClickWheel) android.findViewById(R.id.wheel);
        wheel.getModel().addListener(this);*/
        // variable initialization for button
        return android;
    }
@Override
public void onViewCreated(View v, Bundle savedInstanceState) {
    super.onViewCreated(v, savedInstanceState);

    btnPlay = (ImageButton)getView().findViewById(R.id.btnPlay);
    btnForward = (ImageButton) getView().findViewById(R.id.btnForward);
    btnBackward = (ImageButton) getView().findViewById(R.id.btnBackward);
    btnNext = (ImageButton) getView().findViewById(R.id.btnNext);
    btnPrevious = (ImageButton) getView().findViewById(R.id.btnPrevious);
    btnRepeat = (ImageButton) getView().findViewById(R.id.btnRepeat);
    btnShuffle = (ImageButton) getView().findViewById(R.id.btnShuffle);
    songProgressBar = (SeekBar) getView().findViewById(R.id.songProgressBar);
    songTitleLabel = (TextView) getView().findViewById(R.id.songTitle);
    songTitleLabel.setSelected(true);
    songTitleLabel.setEllipsize(TextUtils.TruncateAt.MARQUEE);
    songTitleLabel.setSingleLine(true);
    songCurrentDurationLabel = (TextView) getView().findViewById(R.id.songCurrentDurationLabel);
    songTotalDurationLabel = (TextView) getView().findViewById(R.id.songTotalDurationLabel);

    mp = new MediaPlayer();

    songManager = new SongsManager();
    utils = new Utilities();

    songProgressBar.setOnSeekBarChangeListener(this);
    songsList = songManager.getPlayList();

    if (songIndex == 0) {
        playSong(0);
    } else {
        playSong(songIndex);
    }
    btnPlay.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // check for already playing
            if (mp.isPlaying()) {
                if (mp != null) {
                    mp.pause();
                    btnPlay.setImageResource(R.drawable.btn_play);
                }
            } else {
                // Resume song
                if (mp != null) {
                    mp.start();
                    btnPlay.setImageResource(R.drawable.btn_pause);
                }
            }

        }
    });
    btnForward.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            int currentPosition = mp.getCurrentPosition();
            if(currentPosition + seekForwardTime <= mp.getDuration()){
                mp.seekTo(currentPosition + seekForwardTime);
            }else{
                mp.seekTo(mp.getDuration());
            }
        }
    });
    btnBackward.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            int currentPosition = mp.getCurrentPosition();
            if(currentPosition - seekBackwardTime >= 0){
                mp.seekTo(currentPosition - seekBackwardTime);
            }else{
                mp.seekTo(0);
            }

        }
    });
    btnNext.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if(currentSongIndex < (songsList.size() - 1)){
                playSong(currentSongIndex + 1);
                currentSongIndex = currentSongIndex + 1;
            }else{
                playSong(0);
                currentSongIndex = 0;
            }

        }
    });
    btnPrevious.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if(currentSongIndex > 0){
                playSong(currentSongIndex - 1);
                currentSongIndex = currentSongIndex - 1;
            }else{
                playSong(songsList.size() - 1);
                currentSongIndex = songsList.size() - 1;
            }

        }
    });
    btnRepeat.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if(isRepeat){
                isRepeat = false;
                Toast.makeText(getActivity().getApplicationContext(), "Repeat is OFF", Toast.LENGTH_SHORT).show();
                btnRepeat.setImageResource(R.drawable.btn_repeat);
            }else{
                isRepeat = true;
                Toast.makeText(getActivity().getApplicationContext(), "Repeat is ON", Toast.LENGTH_SHORT).show();
                isShuffle = false;
                btnRepeat.setImageResource(R.drawable.btn_repeat_focused);
                btnShuffle.setImageResource(R.drawable.btn_shuffle);
            }
        }
    });
    btnShuffle.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if(isShuffle){
                isShuffle = false;
                Toast.makeText(getActivity().getApplicationContext(), "Shuffle is OFF", Toast.LENGTH_SHORT).show();
                btnShuffle.setImageResource(R.drawable.btn_shuffle);
            }else{
                isShuffle= true;
                Toast.makeText(getActivity().getApplicationContext(), "Shuffle is ON", Toast.LENGTH_SHORT).show();
                isRepeat = false;
                btnShuffle.setImageResource(R.drawable.btn_shuffle_focused);
                btnRepeat.setImageResource(R.drawable.btn_repeat);
            }
        }
    });

}
public void playSong(int songIndex) {
    try {
        Log.e("playSong()...", "....is called");
        mp.reset();
        mp.setDataSource(songsList.get(songIndex).getSongPath());
        mp.prepare();
        songProgressBar.setProgress(0);
        songProgressBar.setMax(100);
        String songTitle = songsList.get(songIndex).getSongTitle();
        songTitleLabel.setText(songTitle);
        btnPlay.setImageResource(R.drawable.btn_pause);
        mp.start();
        updateProgressBar();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
private Runnable mUpdateTimeTask = new Runnable() {
    public void run() {
        long totalDuration = mp.getDuration();
        long currentDuration = mp.getCurrentPosition();

        songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));

        songCurrentDurationLabel.setText("" + utils.milliSecondsToTimer(currentDuration));

        int progress =(int)(utils.getProgressPercentage(currentDuration, totalDuration));

        songProgressBar.setProgress(progress);

        mHandler.postDelayed(this, 100);
    }
};
private void updateProgressBar() {
    mHandler.postDelayed(mUpdateTimeTask, 100);
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

}
public void onStartTrackingTouch(SeekBar seekBar) {
    mHandler.removeCallbacks(mUpdateTimeTask);
}
public void onStopTrackingTouch(SeekBar seekBar) {
    mHandler.removeCallbacks(mUpdateTimeTask);
    int totalDuration = mp.getDuration();
    int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);
    mp.seekTo(currentPosition);
    updateProgressBar();
}}

PLAYLIST FRAGMENT

public class Playlists extends ListFragment {


EditText edtSearch;
SongAdapter songAdapter;
ArrayList<SongModel> songList = new ArrayList<SongModel>();
SongsManager songsManager = new SongsManager();

// Songs list
public ArrayList<SongModel> songsList = new ArrayList<>();
 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
     View windows = inflater.inflate(R.layout.playlist, container, false);
     return windows;
}

@Override
public void onViewCreated(View v, Bundle savedInstanceState) {
    super.onViewCreated(v, savedInstanceState);

    getListView().setFastScrollEnabled(true);
    //ListView animation
    LayoutAnimationController controller
            = AnimationUtils.loadLayoutAnimation(
            getActivity(), R.anim.list_layout_controller);
    getListView().setLayoutAnimation(controller);
    edtSearch = (EditText)getView().findViewById(R.id.search);
    final ArrayList<SongModel> songsListData = songsManager.songList;
    Log.i("songsListData...",""+songsListData.size());
    SongsManager plm = new SongsManager();

    // get all songs from sdcard
    this.songsList = plm.getPlayList();
    // looping through playlist
    for (int i = 0; i < songsListData.size(); i++) {
        // creating new HashMap
        SongModel song = songsListData.get(i);
        // adding HashList to ArrayList
        songsListData.add(song);
    }

    songAdapter = new SongAdapter(getActivity(),songsList);
    setListAdapter(songAdapter);
    // selecting single ListView item
    ListView lv = getListView();

    // listening to single listitem click
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View arg0,
                                int position, long id) {

            Log.i("Index", "..." + position);
            songAdapter.setSelectedIndex(position);
            Intent i = new Intent(getActivity().getApplicationContext(),Main.class);
            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
            SongModel songModel = (SongModel) songAdapter.getItem(position);
            int indexOfSong = songAdapter.songsList.indexOf(songModel);

            // Sending songIndex to PlayerActivity
            i.putExtra("songIndex", indexOfSong);
            getActivity().setResult(100, i);
            startActivityForResult(i, 100);
            /*Player.mp.stop();
            Player.mp.release();*/

            //putting song in recentSongList arraylist
            SongModel model = (SongModel) songAdapter.getItem(position);
            model.setSongTitle(songModel.getSongTitle());
            model.setSongPath(songModel.getSongPath());
            Constant.recentSongList.add(model);
            Log.i("recentSongList...","..."+Constant.recentSongList.size());
            getActivity().finish();
        }
    });
    lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

            removeItemFromList(position);
            return true;
        }

        private void removeItemFromList(int position) {

            final int deletePosition = position;

            AlertDialog.Builder alert = new AlertDialog.Builder(
                    getActivity());

            alert.setTitle("Delete");
            alert.setMessage("Do you want delete this song?");
            alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TOD O Auto-generated method stub

                    // main code on after clicking yes
                    songsList.remove(deletePosition);
                    songAdapter.notifyDataSetChanged();
                    songAdapter.notifyDataSetInvalidated();

                }
            });
            alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    dialog.dismiss();
                }
            });

            alert.show();
        }
    });
    edtSearch.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence cs, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String text = edtSearch.getText().toString().toLowerCase(Locale.getDefault());
            songAdapter.filter(text);
        }
    });
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);

    if (this.isVisible()) {
        // If we are becoming invisible, then...
        Log.d("setUserVisibleHint()...", "PlayList...Visible");
        if (!isVisibleToUser) {
            Log.d("setUserVisibleHint()...", "PlayList...notVisible");
            // TODO stop audio playback
        }
    }
}

如果有人知道该怎么做,请帮助我。

1 个答案:

答案 0 :(得分:1)

在播放列表片段中删除此Player.mp.release();

像这样编辑你的Listview onItemCLickListner

        @Override
        public void onItemClick(AdapterView<?> parent, View arg0,
                                int position, long id) {

            Log.i("Index", "..." + position);
            songAdapter.setSelectedIndex(position);
            Intent i = new Intent(getActivity().getApplicationContext(),Main.class);
            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
            SongModel songModel = (SongModel) songAdapter.getItem(position);
            int indexOfSong = songAdapter.songsList.indexOf(songModel);

            // Sending songIndex to PlayerActivity
            i.putExtra("songIndex", indexOfSong);
            getActivity().setResult(100, i);
            startActivityForResult(i, 100);
            Player.mp.stop();

            //putting song in recentSongList arraylist
            SongModel model = (SongModel) songAdapter.getItem(position);
            model.setSongTitle(songModel.getSongTitle());
            model.setSongPath(songModel.getSongPath());
            Constant.recentSongList.add(model);
            Log.i("recentSongList...","..."+Constant.recentSongList.size());
            getActivity().finish();
        }
    });

我希望这项工作......