我为什么会收到此错误" java.lang.IllegalStateException"在Mediaplayer安卓应用

时间:2016-09-14 13:32:12

标签: android

我是Android开发新手,目前我正在开发android mediaplayer简单应用程序。所以,我的问题是为什么我得到这个例外。根据我的项目我定义了三个片段,第一个片段是播放器片段,它显示媒体播放器控制和播放歌曲,第二个片段是播放列表,其中包含歌曲列表,第三个片段是最近的播放列表,其中包含最近播放的歌曲。在此项目中,当我点击播放列表片段项目播放新歌并突然生成java.lang.IllegalStateException此例外。

这是我的播放器片段

package com.v1.sensoft.m_player.Fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.audiofx.Visualizer;
import android.net.sip.SipSession; 
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.MotionEventCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.v1.sensoft.m_player.Activity.AudioFxActivit;
import com.v1.sensoft.m_player.Adapter.SongAdapter;
import com.v1.sensoft.m_player.R;
import com.v1.sensoft.m_player.Utility.SongsManager;
import com.v1.sensoft.m_player.Utility.Utilities;
import com.v1.sensoft.m_player.Visualizer.SliderView;
import com.v1.sensoft.m_player.Visualizer.VisualizerView;
import com.v1.sensoft.m_player.djView.ClickWheel;
import com.v1.sensoft.m_player.djView.WheelModel;
import com.v1.sensoft.m_player.model.SongModel;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;


public class Player extends Fragment implements WheelModel.Listener,MediaPlayer.OnCompletionListener,SeekBar.OnSeekBarChangeListener {

private ImageButton btnPlay;
private ImageButton btnForward;
private ImageButton btnBackward;
private ImageButton btnNext;
private ImageButton btnPrevious;
private ImageButton btnRepeat;
private ImageButton btnShuffle;
private SeekBar songProgressBar;
private TextView songTitleLabel;
private TextView songCurrentDurationLabel;
private TextView songTotalDurationLabel;
// Media Player
public static MediaPlayer mp,mp2;
VisualizerView mVisualizerView;
SliderView sl;
private Visualizer mVisualizer;
// Handler to update UI timer, progress bar etc,.
private Handler mHandler = new Handler();;
private SongsManager songManager;
private Utilities utils;
private int seekForwardTime = 5000; // 5000 milliseconds
private int seekBackwardTime = 5000; // 5000 milliseconds
private int currentSongIndex = 0;
private boolean isShuffle = false;
private boolean isRepeat = false;
private ArrayList<SongModel> songsList = new ArrayList<SongModel>();
int songIndex;
SongAdapter songAdapter;
public Player(int position) {
    songIndex = position;
}

public Player() {

}


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

    View android = inflater.inflate(R.layout.player, container, false);

    ClickWheel wheel = (ClickWheel) android.findViewById(R.id.wheel);
        wheel.getModel().addListener(this);
    // variable initialization for button
    btnPlay = (ImageButton) android.findViewById(R.id.btnPlay);
    btnForward = (ImageButton) android.findViewById(R.id.btnForward);
    btnBackward = (ImageButton) android.findViewById(R.id.btnBackward);
    btnNext = (ImageButton) android.findViewById(R.id.btnNext);
    btnPrevious = (ImageButton) android.findViewById(R.id.btnPrevious);
    btnRepeat = (ImageButton) android.findViewById(R.id.btnRepeat);
    btnShuffle = (ImageButton) android.findViewById(R.id.btnShuffle);
    songProgressBar = (SeekBar) android.findViewById(R.id.songProgressBar);
    songTitleLabel = (TextView) android.findViewById(R.id.songTitle);
        songTitleLabel.setSelected(true);
        songTitleLabel.setEllipsize(TextUtils.TruncateAt.MARQUEE);
        songTitleLabel.setSingleLine(true);
    songCurrentDurationLabel = (TextView)android.findViewById(R.id.songCurrentDurationLabel);
    songTotalDurationLabel = (TextView) android.findViewById(R.id.songTotalDurationLabel);
   // mVisualizerView = (VisualizerView) android.findViewById(R.id.myvisualizerview);
    //audioManager = (AudioManager)getActivity().getSystemService(Context.AUDIO_SERVICE);

   /* //sliding finger up and increase and decrease volume
    android.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            int action = MotionEventCompat.getActionMasked(event);
            if (action == MotionEvent.ACTION_MOVE) {
                // put your volume change logic here, for example compare previously recorded x/y position to new one and change volume
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 5, 0);
            }
            return true;
        }
    });*/
    //Visualizer method
    mp = new MediaPlayer();
   // initAudio();

    songManager = new SongsManager();
    utils = new Utilities();

    // Listeners
    songProgressBar.setOnSeekBarChangeListener(this); // Important
    mp.setOnCompletionListener(this); // Important

    // Getting all songs list
    songsList = songManager.getPlayList();
    // By default play first song
    if (songIndex==0)
    {
        playSong(0);
    }
    else
    {
        playSong(songIndex);
    }
    btnPlay.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // check for already playing
            if (mp.isPlaying()) {
                if (mp != null) {
                    mp.pause();
                    btnPlay.setImageResource(R.drawable.btn_play);
                }
            } else {
                // Resume song
                if (mp != null) {
                    mp.start();
                    btnPlay.setImageResource(R.drawable.btn_pause);
                }
            }

        }
    });
    btnForward.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            int currentPosition = mp.getCurrentPosition();
            if(currentPosition + seekForwardTime <= mp.getDuration()){
                mp.seekTo(currentPosition + seekForwardTime);
            }else{
                mp.seekTo(mp.getDuration());
            }
        }
    });
    btnBackward.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            int currentPosition = mp.getCurrentPosition();
            if(currentPosition - seekBackwardTime >= 0){
                mp.seekTo(currentPosition - seekBackwardTime);
            }else{
                mp.seekTo(0);
            }

        }
    });
    btnNext.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if(currentSongIndex < (songsList.size() - 1)){
                playSong(currentSongIndex + 1);
                currentSongIndex = currentSongIndex + 1;
            }else{
                playSong(0);
                currentSongIndex = 0;
            }

        }
    });
    btnPrevious.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if(currentSongIndex > 0){
                playSong(currentSongIndex - 1);
                currentSongIndex = currentSongIndex - 1;
            }else{
                playSong(songsList.size() - 1);
                currentSongIndex = songsList.size() - 1;
            }

        }
    });
    btnRepeat.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if(isRepeat){
                isRepeat = false;
                Toast.makeText(getActivity().getApplicationContext(), "Repeat is OFF", Toast.LENGTH_SHORT).show();
                btnRepeat.setImageResource(R.drawable.btn_repeat);
            }else{
                isRepeat = true;
                Toast.makeText(getActivity().getApplicationContext(), "Repeat is ON", Toast.LENGTH_SHORT).show();
                isShuffle = false;
                btnRepeat.setImageResource(R.drawable.btn_repeat_focused);
                btnShuffle.setImageResource(R.drawable.btn_shuffle);
            }
        }
    });
    btnShuffle.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if(isShuffle){
                isShuffle = false;
                Toast.makeText(getActivity().getApplicationContext(), "Shuffle is OFF", Toast.LENGTH_SHORT).show();
                btnShuffle.setImageResource(R.drawable.btn_shuffle);
            }else{
                isShuffle= true;
                Toast.makeText(getActivity().getApplicationContext(), "Shuffle is ON", Toast.LENGTH_SHORT).show();
                isRepeat = false;
                btnShuffle.setImageResource(R.drawable.btn_shuffle_focused);
                btnRepeat.setImageResource(R.drawable.btn_repeat);
            }
        }
    });
    return android;

}
public void playSong(int songIndex){
    try {
        Log.e("playSong()...", "....is called");
        mp.reset();
        mp.setDataSource(songsList.get(songIndex).getSongPath());
        mp.prepare();
        songProgressBar.setProgress(0);
        songProgressBar.setMax(100);
        String songTitle = songsList.get(songIndex).getSongTitle();
        songTitleLabel.setText(songTitle);
        btnPlay.setImageResource(R.drawable.btn_pause);
        updateProgressBar();
        mp.start();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    Log.i("song...songIndex...", "..." + songIndex);

    mHandler.removeCallbacks(mUpdateTimeTask);
    if(resultCode == 100){
        currentSongIndex = data.getExtras().getInt("songIndex");
        Log.i("song...currentSongIndex...", "..." + currentSongIndex);
        // play selected song
        playSong(currentSongIndex);
    }

}
private Runnable mUpdateTimeTask = new Runnable() {
    public void run() {
        long totalDuration = mp.getDuration();
        long currentDuration = mp.getCurrentPosition();

        songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));

        songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));

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

        songProgressBar.setProgress(progress);

        mHandler.postDelayed(this,100);
    }
};
private void updateProgressBar() {
    mHandler.postDelayed(mUpdateTimeTask,100);
}
@Override
public void onCompletion(MediaPlayer mp) {
    if(isRepeat){
        playSong(currentSongIndex);
    } else if(isShuffle){
        Random rand = new Random();
        currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;
        playSong(currentSongIndex);
    } else{
        if(currentSongIndex < (songsList.size() - 1)){
            playSong(currentSongIndex + 1);
            currentSongIndex = currentSongIndex + 1;
        }else{
            playSong(0);
            currentSongIndex = 0;
        }
    }
}

@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {
    mHandler.removeCallbacks(mUpdateTimeTask);
}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
    mHandler.removeCallbacks(mUpdateTimeTask);
    int totalDuration = mp.getDuration();
    int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);

    mp.seekTo(currentPosition);
    updateProgressBar();
}
@Override
public void onDialPositionChanged(WheelModel sender, int nicksChanged) {

    getActivity().setVolumeControlStream(AudioManager.STREAM_MUSIC);
    mp2 =MediaPlayer.create(getActivity(),R.raw.djlazer);
    mp2.start();
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (this.isVisible()) {

        if (!isVisibleToUser) {

        }
    }
}
@Override
public void onDestroy() {
    super.onDestroy();
    mHandler.removeCallbacks(mUpdateTimeTask);
    if(mp!=null)
    {
        if(mp.isPlaying()) mp.stop();
        mp.reset();
        mp.release();
    }
}
}

播放列表片段。

public class Playlists extends ListFragment {


EditText edtSearch;
SongAdapter songAdapter;
ArrayList<SongModel> songList = new ArrayList<SongModel>();
SongsManager songsManager = new SongsManager();

// Songs list
public ArrayList<SongModel> songsList = new ArrayList<>();
 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
     View windows = inflater.inflate(R.layout.playlist, container, false);
     return windows;
}

@Override
public void onViewCreated(View v, Bundle savedInstanceState) {
    super.onViewCreated(v, savedInstanceState);

    getListView().setFastScrollEnabled(true);
    //ListView animation
    LayoutAnimationController controller
            = AnimationUtils.loadLayoutAnimation(
            getActivity(), R.anim.list_layout_controller);
    getListView().setLayoutAnimation(controller);
    edtSearch = (EditText)getView().findViewById(R.id.search);
    final ArrayList<SongModel> songsListData = songsManager.songList;
    Log.i("songsListData...",""+songsListData.size());
    SongsManager plm = new SongsManager();

    // get all songs from sdcard
    this.songsList = plm.getPlayList();
    // looping through playlist
    for (int i = 0; i < songsListData.size(); i++) {
        // creating new HashMap
        SongModel song = songsListData.get(i);
        // adding HashList to ArrayList
        songsListData.add(song);
    }

    songAdapter = new SongAdapter(getActivity(),songsList);
    setListAdapter(songAdapter);
    // selecting single ListView item
    ListView lv = getListView();

    // listening to single listitem click
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

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

            Log.i("Index", "..." + position);
            songAdapter.setSelectedIndex(position);
            Intent i = new Intent(getActivity().getApplicationContext(),Main.class);
            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
            SongModel songModel = (SongModel) songAdapter.getItem(position);
            int indexOfSong = songAdapter.songsList.indexOf(songModel);

            // Sending songIndex to PlayerActivity
            i.putExtra("songIndex", indexOfSong);

            startActivityForResult(i, 100);


            //putting song in recentSongList arraylist
            SongModel model = (SongModel) songAdapter.getItem(position);
            model.setSongTitle(songModel.getSongTitle());
            model.setSongPath(songModel.getSongPath());
            Constant.recentSongList.add(model);
            Log.i("recentSongList...","..."+Constant.recentSongList.size());
            getActivity().finish();
        }
    });
    lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

            removeItemFromList(position);
            return true;
        }

        private void removeItemFromList(int position) {

            final int deletePosition = position;

            AlertDialog.Builder alert = new AlertDialog.Builder(
                    getActivity());

            alert.setTitle("Delete");
            alert.setMessage("Do you want delete this song?");
            alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TOD O Auto-generated method stub

                    // main code on after clicking yes
                    songsList.remove(deletePosition);
                    songAdapter.notifyDataSetChanged();
                    songAdapter.notifyDataSetInvalidated();

                }
            });
            alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    dialog.dismiss();
                }
            });

            alert.show();
        }
    });
    edtSearch.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence cs, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String text = edtSearch.getText().toString().toLowerCase(Locale.getDefault());
            songAdapter.filter(text);
        }
    });
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);

    if (this.isVisible()) {
        // If we are becoming invisible, then...
        Log.d("setUserVisibleHint()...", "PlayList...Visible");
        if (!isVisibleToUser) {
            Log.d("setUserVisibleHint()...", "PlayList...notVisible");
            // TODO stop audio playback
        }
    }
}

这是我的logcat

09-14 18:43:12.052 17474-17474/com.v1.sensoft.m_player E/AndroidRuntime:    FATAL EXCEPTION: main
09-14 18:43:12.052 17474-17474/com.v1.sensoft.m_player E/AndroidRuntime:  Process: com.v1.sensoft.m_player, PID: 17474
09-14 18:43:12.052 17474-17474/com.v1.sensoft.m_player E/AndroidRuntime: java.lang.IllegalStateException
09-14 18:43:12.052 17474-17474/com.v1.sensoft.m_player E/AndroidRuntime:      at android.media.MediaPlayer.getDuration(Native Method)
09-14 18:43:12.052 17474-17474/com.v1.sensoft.m_player E/AndroidRuntime:     at com.v1.sensoft.m_player.Fragment.Player$8.run(Player.java:289)
09-14 18:43:12.052 17474-17474/com.v1.sensoft.m_player E/AndroidRuntime:     at android.os.Handler.handleCallback(Handler.java:808)
09-14 18:43:12.052 17474-17474/com.v1.sensoft.m_player E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:103)
09-14 18:43:12.052 17474-17474/com.v1.sensoft.m_player E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:193)
09-14 18:43:12.052 17474-17474/com.v1.sensoft.m_player E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5333)
09-14 18:43:12.052 17474-17474/com.v1.sensoft.m_player E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)
09-14 18:43:12.052 17474-17474/com.v1.sensoft.m_player E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:515)
09-14 18:43:12.052 17474-17474/com.v1.sensoft.m_player E/AndroidRuntime:       atcom.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)

那么,我怎么能解决这个问题。如果有什么问题请帮帮忙。 提前感谢...

2 个答案:

答案 0 :(得分:1)

根据the official document about MediaPlayerMediaPlayer.getDuration()似乎是MediaPlayer.getDuration() MediaPlayer IdleInitializedError州。

当您使用MediaPlayer进行开发时,您应该好好照顾MediaPlayer的州。

答案 1 :(得分:0)

Android媒体播放器存在很多问题。 当媒体播放器处于空闲状态时,您无法调用方法。

Official Documents  像这样说。

  

此外,使用new创建的MediaPlayer对象处于空闲状态,而使用其中一个重载方便创建方法创建的对象不处于空闲状态。实际上,如果使用create方法创建成功,则对象处于Prepared状态。

使用

MediaPlayer mediaPlayer = MediaPlayer.create(this, Uri.parse("uriString"));

它已经调用了prepare()方法,因此您可以开始自由使用它。 希望它能奏效。