在android中实现listview中的音频播放器

问题描述 投票:0回答:1

我有列表视图,其中包含带有播放按钮和搜索栏的音频文件列表。我使用基本适配器显示列表视图。

当我单击列表视图的播放按钮时,我想播放音频文件。我成功地实现了这一点,但是当我单击列表中的另一个播放按钮时,两个音频文件正在连续播放,它将继续播放按钮的所有单击。如何限制媒体播放器在一个位置播放,如果我单击另一个图标,它必须停止旧媒体播放器并开始播放新媒体播放器。谁能告诉我如何实现这个?

嗨,我正在使用此代码

公共类 PlayerList 扩展 Activity {

private static final String TAG = "log";

ListView listV;

ArrayList<HashMap<String, String>> arrList = new ArrayList<HashMap<String,String>>();;

String[] strArray = { "/mnt/sdcard/Nal.mp3", "/mnt/sdcard/Nal2.mp3",
        "/mnt/sdcard/Nal3.mp3", "/mnt/sdcard/sample1.mp3", };

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.homepage);

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
    StrictMode.setThreadPolicy(policy);

    listV = (ListView) findViewById(R.id.HomePagelistView1);

    for (int i = 0; i < strArray.length; i++) {

        HashMap<String, String> hmap = new HashMap<String, String>();

        hmap.put("title", "File Name");
        hmap.put("description", "File description");
        hmap.put("url", strArray[i]);

        arrList.add(hmap);

    }

    FileListAdapter sAdapter = new FileListAdapter(arrList, PlayerList.this);

    listV.setAdapter(sAdapter);

}

}

下面给出了FileListAdapter文件

    public class FileListAdapter extends BaseAdapter implements
        OnCompletionListener, OnSeekBarChangeListener {

    private MediaPlayer mp;

    private Handler mHandler = new Handler();;

    private Utilities utils;

    SeekBar seekBar;// = (SeekBar) findViewById(R.id.homeList_seekBar1);

    String songPath = "";

    // ImageView imageVPlay;

    private ArrayList<HashMap<String, String>> data;
    private LayoutInflater inflater = null;



    public FileListAdapter(ArrayList<HashMap<String, String>> data,
            Context context) {
        this.data = data;
        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public int getCount() {
        return data.size();
    }

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

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

    public View getView(final int position, View convertView,
            ViewGroup parent) {
        View vi = convertView;
        if (convertView == null)

            vi = inflater.inflate(R.layout.homelist, parent, false);

        final ImageView imageVDownload = (ImageView) vi
                .findViewById(R.id.homeListimageDownload); // download

        final ImageView imageVPlay = (ImageView) vi
                .findViewById(R.id.homeListimagePlay); // play
        final TextView textVTitle = (TextView) vi
                .findViewById(R.id.homeListTextTitle); // email ID

        final TextView textVDescription = (TextView) vi
                .findViewById(R.id.homeListTextDesc); // email ID

        seekBar = (SeekBar) vi.findViewById(R.id.homeList_seekBar1);

        textVTitle.setText(data.get(position).get("title"));

        textVDescription.setText(data.get(position).get("description"));

        // /////////////////////////////////// set image tick and download

        String loadFilePath = data.get(position).get("url");
        // String loadFileName = data.get(position).get("title");

        File ffPath = new File(loadFilePath);

        String loadfileNameWithExt = ffPath.getName();
        Log.i(TAG, "load file and name path " + " " + loadfileNameWithExt
                + " " + loadFilePath);

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

                String selectFilePath = data.get(position).get("url");

                String selectFileName = data.get(position).get("title");

                Log.i(TAG, "selected file and name path " + selectFileName
                        + " " + selectFilePath);

                songPath = selectFilePath;

                mediaplayerMethod(selectFilePath);

                imageVPlay.setImageResource(R.drawable.list_pause);

                textVTitle.setVisibility(View.INVISIBLE);
                textVDescription.setVisibility(View.INVISIBLE);
                seekBar.setVisibility(View.VISIBLE);





            }
        });

        return vi;
    }

    protected void mediaplayerMethod(String filepath) {

        Log.d(TAG, "mediaplayerMethod audio file path " + filepath);

        mp = new MediaPlayer();

        mp.setOnCompletionListener(FileListAdapter.this); // Important

        seekBar.setOnSeekBarChangeListener(FileListAdapter.this);

        utils = new Utilities();

        playSong(filepath);

    }

    private void playSong(final String fileptath) {

        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message message) {
                String xmlString = (String) message.obj;

                Log.d(TAG, "handleMessage ");

                try {
                    // mp.prepare();
                    mp.start();



                    seekBar.setProgress(0);
                    seekBar.setMax(100);


                    updateProgressBar();

                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                }

            }
        };

        Thread thread = new Thread() {
            @Override
            public void run() {

                Log.d(TAG, "run ");

                try {
                    mp.reset();


                        mp.setDataSource(fileptath);

                        Log.i(TAG, "internal file");


                    mp.prepare();

                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                Message message = handler.obtainMessage(1, "");
                handler.sendMessage(message);
            }
        };
        thread.start();

    }


    public void updateProgressBar() {
        mHandler.postDelayed(mUpdateTimeTask, 100);
    }

    private Runnable mUpdateTimeTask = new Runnable() {
        public void run() {
            try {

                long totalDuration = mp.getDuration();
                long currentDuration = mp.getCurrentPosition();


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


                seekBar.setProgress(progress);

                try {

                    double progVal = (progress / 100.0) * (360.0);

                    int progInt = (int) Math.ceil(progVal);

                } catch (NumberFormatException e) {

                    Log.e(TAG, "NumberFormatException " + e);
                }

                // Running this thread after 100 milliseconds
                mHandler.postDelayed(this, 100);

            } catch (IllegalStateException e) {
                Log.e(TAG, "IllegalStateException " + e);
            }

        }
    };

    @Override
    public void onCompletion(MediaPlayer mp) {


        mp.stop(); 
        mp.release(); 


    }

    @Override
    public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStartTrackingTouch(SeekBar arg0) {
        // TODO Auto-generated method stub
        mHandler.removeCallbacks(mUpdateTimeTask);

    }

    @Override
    public void onStopTrackingTouch(SeekBar arg0) {
        // TODO Auto-generated method stub
        mHandler.removeCallbacks(mUpdateTimeTask);
        int totalDuration = mp.getDuration();
        int currentPosition = utils.progressToTimer(seekBar.getProgress(),
                totalDuration);

        // forward or backward to certain seconds
        mp.seekTo(currentPosition);


        updateProgressBar();
    }

}// FileListAdapter
android listview media-player
1个回答
0
投票

当您要启动新实例时,释放旧的 MediaPlayer。例如:

protected void mediaplayerMethod(String filepath) {

    Log.d(TAG, "mediaplayerMethod audio file path " + filepath);

    if(mp != null){
        mp.release();
    }
    mp = null;

    mp = new MediaPlayer();

    mp.setOnCompletionListener(FileListAdapter.this); // Important

    seekBar.setOnSeekBarChangeListener(FileListAdapter.this);

    utils = new Utilities();

    playSong(filepath);

}
© www.soinside.com 2019 - 2024. All rights reserved.