Android:从listview一次播放一个媒体文件

时间:2015-12-06 14:39:14

标签: android listview media

我创建了一个列表视图,其中包含4个要播放的媒体文件。如果我选​​择要播放的第一首歌曲,它正在播放但是如果我在列表视图中选择社交歌曲进行播放,那么两者都在播放,所以我希望如果第二个将是选择播放然后首先需要停止,只需要播放第二首歌。请帮我解决这个问题......提前谢谢。 以下是我的代码。 主要活动

public class MainActivity extends Activity implements AdapterView.OnItemClickListener {

private ArrayList<String> audioList;
private File file;
private ListView lvAudio;
private Context context;
private Adapter Adaptr;

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

    audioList = new ArrayList<String>();

    String root_sd = Environment.getExternalStorageDirectory().toString();
    file = new File( root_sd + "/EmoticApp/AudioFile/" ) ;
    File list[] = file.listFiles();

    for( int i=0; i< list.length; i++)
    {
        audioList.add( list[i].getName() );
    }

    getid();
    setListner();

    Adaptr = new Adapter(MainActivity.this,audioList);
    lvAudio.setAdapter(Adaptr);
}

private void setListner() {

    lvAudio.setOnItemClickListener(this);
}

private void getid() {

    lvAudio =(ListView)findViewById(R.id.lvAudio);
}

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


}

}

适配器代码:

public class Adapter extends BaseAdapter {


ArrayList<String> audioList;
Context context;
private static LayoutInflater inflater = null;
public boolean flag =false;

public Adapter(MainActivity mainActivity, ArrayList<String> audioList) {

    this.context = mainActivity;
    this.audioList = audioList;
}

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

@Override
public Object getItem(int position) {
    return position;
}

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

public class Holder {
    private ImageView imgIcon, imgPlay, imgPause, imgStop;
    private MediaPlayer mediaPlayer;
    private SeekBar seekbar;
    private TextView tvTotalTime,duration;
    private double timeElapsed = 0, finalTime = 0;
    private int forwardTime = 2000, backwardTime = 2000;
    private Handler durationHandler = new Handler();

    //handler to change seekBarTime
    private Runnable updateSeekBarTime = new Runnable() {
        public void run() {
            //get current position
            timeElapsed = mediaPlayer.getCurrentPosition();
            //set seekbar progress
            seekbar.setProgress((int) timeElapsed);

            tvTotalTime.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) finalTime), TimeUnit.MILLISECONDS.toSeconds((long) finalTime)));

            //set time remaing
            double timeRemaining = finalTime - timeElapsed;
            duration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining), TimeUnit.MILLISECONDS.toSeconds((long) timeRemaining) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining))));

            //repeat yourself that again in 100 miliseconds
            durationHandler.postDelayed(this, 100);
        }
    };
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

    View myView = convertView;
    final Holder holder;

    if (myView == null) {
        LayoutInflater inflater = LayoutInflater.from(context);
        myView = inflater.inflate(R.layout.video_adapter, null);

        holder = new Holder();
        holder.imgPlay = (ImageView) myView.findViewById(R.id.imgPlay);
        holder.imgPause = (ImageView) myView.findViewById(R.id.imgPause);
        holder.imgStop = (ImageView) myView.findViewById(R.id.imgStop);
        holder.seekbar =(SeekBar)myView.findViewById(R.id.seekbar);
        holder.tvTotalTime =(TextView)myView.findViewById(R.id.tvTotalTime);
        holder.duration =(TextView)myView.findViewById(R.id.duration);

        holder.seekbar.setClickable(true);

        holder.seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

                if (fromUser) {
                    holder.mediaPlayer.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        String fileName = audioList.get(position);
        String path="/EmoticApp/AudioFile/";
        Log.e("Checking File:", "Checking=======:" + fileName);

        flag =true;

        holder.mediaPlayer = MediaPlayer.create(context, Uri.parse(Environment.getExternalStorageDirectory().getPath()+path + fileName));

        holder.imgPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (flag == true) {

                    holder.mediaPlayer.start();
                    if (holder.mediaPlayer.isPlaying()) {
                        Toast.makeText(context, "Playing", Toast.LENGTH_LONG).show();
                        holder.imgPlay.setVisibility(View.INVISIBLE);
                        holder.imgPause.setVisibility(View.VISIBLE);
                        holder.timeElapsed = holder.mediaPlayer.getCurrentPosition();
                        holder.seekbar.setProgress((int) holder.timeElapsed);
                        holder.durationHandler.postDelayed(holder.updateSeekBarTime, 100);
                        holder.finalTime = holder.mediaPlayer.getDuration();
                        holder.seekbar.setMax((int) holder.finalTime);

                        Toast.makeText(context,"Playing",Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

        holder.imgPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                holder.mediaPlayer.pause();
                holder.imgPause.setVisibility(View.INVISIBLE);
                holder.imgPlay.setVisibility(View.VISIBLE);
            }
        });

        holder.mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {

                holder.imgPause.setVisibility(View.INVISIBLE);
                holder.imgPlay.setVisibility(View.VISIBLE);
            }
        });

        myView.setTag(holder);

        return myView;
    }

    return myView;
}

}

3 个答案:

答案 0 :(得分:1)

使用以下代码行:

 MediaPlayer        mp = new MediaPlayer();

    playMySong(String songPath)
    {
        mp.reset();
        mp.setDataSource(songPath);
        mp.prepare();
        mp.start();
    }

答案 1 :(得分:1)

不要为单个行列表创建MediaPlayer实例。让它成为Adapter的属性,因为这将帮助我们检测此媒体播放器当前是否正在播放某首歌

这样做

    public class MyAdapter{
        private MediaPlayer mediaPlayer=new MediaPlayer();// I am ignoring exact constructor

        //now in your getView method do like this

    @Override
public View getView(final int position, View convertView, ViewGroup parent) {

       //.............prev code
        holder.imgPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    if (mediaPlayer.isPlaying()) {
                        mediaPlayer.pause();
                        holder.imgPause.setVisibility(View.INVISIBLE);
                        holder.imgPlay.setVisibility(View.VISIBLE);
                    }else{
                           mp.reset();
                           mp.setDataSource(Uri.parse(Environment.getExternalStorageDirectory().getPath()+path + fileName));
                           mp.prepare();
                           mp.start();
                         //set other things   
                    }
            }
        });
        //......some code below
      }
} 

希望这会对你有所帮助!!!!

答案 2 :(得分:0)

当你在你的应用程序中取得进展时,你会发现会有其他活动或片段可能会尝试播放某些音乐而你会陷入相同的情况,否则你可能会认为你只想停止音乐从列表活动中走出来。

而不是通过管理MediaPlayer实例的喧嚣,只需在应用程序中将其设置为一个类,该类将处理您的业务以播放音乐,在您当前的情况下发生的事情是{ {1}} android的API不断获取播放音乐的请求,绝不是这些API无法处理多个请求,因此他们会在您命令时继续播放,

在您的自定义课程中,您必须检查您的MediaPlayer实例是否仍在播放或不是这样...

MediaPlayer

如果正在播放而不是停止,就像这样

player.isPlaying()

并为其提供一些您想要播放的新数据。