MediaPlayer slowing down listview

时间:2017-07-10 15:20:23

标签: android listview android-mediaplayer

I have a ListView which lists audio recordings. When I click on one to play, it goes out the the internet and retrieves the audio and plays it. When it plays the scrolling locks up.

Once the MediaPlayerhas stopped I can scroll like normal. This isn't a thread issue because the MediaPlayer is playing on another thread.

This is the MediaPlayer AsyncTask:

private class PlayAudio extends AsyncTask<String, Integer, String> {
    @Override
    protected String doInBackground(String... params) {
        nowPlaying = true;

        player.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {

                if(isAdded()) {
                    stopAudio();
                }

                PvmUtils.longToast(context, getString(R.string.error_load_msg));
                return false;
            }
        });

        player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                setButtonColors(2);
            }
        });

        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                stopAudio();

                sendPostMessageRead(new Callbacks.SendPostMessageReadCallback() {
                    @Override
                    public void sendPostMessageReadCallback(boolean gotMessageReadResponse) {
                        if (gotMessageReadResponse) {
                            MessageLog message = log.get(listPosition);
                            message.setMessageStatus("read");

                            if (message.isReply()) {
                                currentMetaTextView.setText("");
                                MyFcmListenerService.newMessages--;
                                ShortcutBadger.applyCount(context, MyFcmListenerService.newMessages);
                            }

                        } else {
                            Log.d(LOG_TAG, "sendPostMessageReadCallback returned false, error may have occurred");
                        }
                    }
                });
            }
        });

        player.setAudioStreamType(AudioManager.STREAM_MUSIC);


        try {
            //Uri uri = Uri.parse(Keys.getpvmURL() + "android/retrieveMessage?messageId=" + params[0]);
            //player.setDataSource(params[0].replaceFirst("https","http"));
            Uri uri = Uri.parse(params[0]);
            Map<String, String> headers = new HashMap<>();
            headers.put("authorisation", encryption.getID().toString());
            player.setDataSource(context, uri, headers);

        } catch (IOException e) {
            e.printStackTrace();
            stopAudio();
        } try {
            player.prepare();
        } catch (IOException e) {
            e.printStackTrace();
            stopAudio();
        }

        player.start();
        return null;
    }
}

This is the clicklistener for the list item:

    ListAdapter newAdapter = new ListAdapter(getActivity());

    if (this.log == null) {
        list.setAdapter(populateAdapter(newAdapter,new ArrayList<MessageLog>()));
    } else {
        list.setAdapter(populateAdapter(newAdapter,log));
    }


    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Log.d(LOG_TAG, Integer.toString(position));

            if (log != null && position < log.size()) {
                if (!nowPlaying && log.get(position).getUrl() != null) {
                    try {
                        stopAudio();
                        setButtonColors(0, currentPlaying);

                        // Show the play controls.
                        currentPlaying = position;
                        nowPlaying = true;
                        player = new MediaPlayer();
                        player.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
                        listPosition = position;
                        currentButton = view;
                        Log.d(LOG_TAG, log.get(position).getUrl());
                        /*
                        MessagePlaybackDialogFragment playFrag = MessagePlaybackDialogFragment.newInstance(log.get(listPosition),
                                new Callbacks.OnPlaybackFinishedListener() {
                            @Override
                            public void onPlaybackDone() {
                                // TODO set as not new
                            }
                        });
                        playFrag.show(getFragmentManager(), "playFrag");*/

//                            MessagePlaybackDialogFragment playFrag = MessagePlaybackDialogFragment.newInstance(log.get(listPosition));
//                            playFrag.show(getFragmentManager(), "playFrag");

                        currentMetaTextView = (TextView) view.findViewById(R.id.voiceMessageMetaText);
                        currentPlayPauseImageView = (ImageView) view.findViewById(R.id.voiceMessagePlayPauseImage);
                        currentMessageBackground = (RelativeLayout) view.findViewById(R.id.voiceMessageRectangleBackground);

                        setButtonColors(1);
                        currentAudio = new PlayAudio().execute(log.get(listPosition).getUrl());
                    } catch (Exception e) {
                        stopAudio();
                        e.printStackTrace();
                    }
                } else if (position == listPosition){
                    stopAudio();
                } else if (nowPlaying){
                    stopAudio();

                    currentPlaying = position;
                    player = new MediaPlayer();
                    player.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
                    listPosition = position;
                    currentButton = view;
                    Log.d(LOG_TAG, log.get(position).getUrl());
                    currentMetaTextView = (TextView) view.findViewById(R.id.voiceMessageMetaText);
                    currentPlayPauseImageView = (ImageView) view.findViewById(R.id.voiceMessagePlayPauseImage);
                    currentMessageBackground = (RelativeLayout) view.findViewById(R.id.voiceMessageRectangleBackground);

                    setButtonColors(0, currentPlaying);
                    setButtonColors(1);

                    currentAudio = new PlayAudio().execute(log.get(listPosition).getUrl());
                }
            }
        }
    });

1 个答案:

答案 0 :(得分:0)

请尝试使用prepareAsync,这是我的代码......

mp.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
                    mp.setDataSource(a.getUrl());
                    mp.prepareAsync();
                    mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            activityList.get(position).setDuration(mp.getDuration()/1000);
                            holder.playButton.clearAnimation();
                            mp.start();
                        }
                    });