MediaPlayer reset()方法不起作用

时间:2015-05-10 12:28:28

标签: android android-mediaplayer

我有一个listlist,其中包含歌曲列表。点击每个项目时,会启动一个新意图,加载另一个播放该歌曲的活动。

//code used in listItemListener

    int songIndex = position;
    Intent n = new Intent(getApplicationContext(), NowPlaying.class);
    n.putExtra("SongIndex", songIndex);
    startActivity(n);

Here NowPlaying class播放这首歌。但问题是 当一首歌正在播放时,我从列表中选择了另一首歌,另一首歌也开始播放而第一首歌没有被停止。我怎么能防止这种情况?我尝试使用reset()方法,但它不起作用。

以下是NowPlaying类的代码。

//code portion of onCreate method
//other necessary things already initialized here

 Intent intent = getIntent();
 int songIndex = intent.getIntExtra("SongIndex", 0);

 currentSongId = songIndex;
 MediaPlayer mediaPlayer = new MediaPlayer();

initMusic();

initMusic()为layout设置其他值,将playerStatus变量设置为true并调用playMusic();

 public void playMusic(String path) {

    if (playerStatus == true) {
        try {
            mediaPlayer.reset();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setDataSource(path);
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        //
    }
}

这是适配器代码

//other method overhere
  public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder;
        LayoutInflater inflater = context.getLayoutInflater();

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.list_item, null);
            holder = new ViewHolder();
            holder.t1 = (TextView) convertView.findViewById(R.id.listTitle);
            holder.t2 = (TextView) convertView.findViewById(R.id.listSubtitle);
            convertView.setTag(holder);

        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.t1.setText(list.get(position).get(0));
        holder.t2.setText(list.get(position).get(2));

        return convertView;
    }

    public class ViewHolder {
        TextView t1;
        TextView t2;

    }

一切正常,歌曲正在播放,但问题是它们正在重叠。每当我从列表中选择另一首歌曲时,它就会重叠并与之前的歌曲一起播放。是由于为每首歌创作的单独活动?

1 个答案:

答案 0 :(得分:0)

在我的mp3播放应用中对我有用的是重复使用相同的mediaPlayer并从mediaPlayer获得播放器,然后stop()播放器和close()播放器。像这样:

mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(datasource);
mediaPlayer.setPlaybackLoop(false);
player = mediaPlayer.getPlayer();
player.start():

...

// you may need 
// player.stop():
player.close();