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

Posted

技术标签:

【中文标题】在android的listview中实现音频播放器【英文标题】:Implementing audio player in listview in android 【发布时间】:2014-03-13 13:33:27 【问题描述】:

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

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

您好,我正在使用此代码

公共类 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

【问题讨论】:

请提供您的代码。 我提供了代码,请通过它 【参考方案1】:

当您要启动一个新实例时释放您的旧 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);


【讨论】:

如何为每个列表实现搜索栏

以上是关于在android的listview中实现音频播放器的主要内容,如果未能解决你的问题,请参考以下文章

在滚动列表中实现视频的播放(ListView & RecyclerView)

如何在 HTML5 中实现一个简单的音频播放列表

在 Android 中实现自定义 ListView

如何在Android listview中实现分页

如何在 ListView 中实现 Android 4.0 之类的滑动以关闭功能?

YouTube 视频在 WebView Android 中仅在屏幕旋转时播放音频