分享

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

 印度阿三17 2019-06-29

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

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

嗨,我正在使用此代码

public class PlayerList extends 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

解决方法:

您可以使用此代码,因为它为我工作:

public class soundTest extends Activity {
  private ListView lv1;
  private String lv_arr[]={"test 1","test 2","test 3","test 4","test 5"};

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    lv1=(ListView)findViewById(R.id.ListView01);
    lv1.setAdapter(new ArrayAdapter<String>(this,R.layout.list_item, lv_arr));

    lv1.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> parent, View view,int position, long id) {

        if (lv1.getItemAtPosition(position)=="test 1") {
          MediaPlayer mp = MediaPlayer.create(getApplicationContext(),R.raw.sound1);
          mp.start();
          mp.setOnCompletionListener(new OnCompletionListener() {
            public void onCompletion(MediaPlayer mp) {
              mp.release();
            }
          });
        }

        if (lv1.getItemAtPosition(position)=="test 2") {
          MediaPlayer mp = MediaPlayer.create(getApplicationContext(),R.raw.sound2);
          mp.start();
          mp.setOnCompletionListener(new OnCompletionListener() {
            public void onCompletion(MediaPlayer mp) {
              mp.release();
            }
          });
        }

        //And the rest of the sounds 3,4,5.

      }
    });
  }
}

全局变量MediaPlayer需要设置为private static.这引起了我好几次.

如果您发现任何问题,请回复.

来源:https://www./content-4-279151.html

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多