停止当前音乐播放,并播放网络流 - ANDROID

时间:2016-08-09 14:23:25

标签: android android-mediaplayer

我已经使用滑动(带标签)为Android创建了一个音乐播放器应用程序。每当我切换到另一个片段时,当音乐正在播放并尝试从列表中播放网络流时,我收到此错误:

FATAL EXCEPTION: main
    Process: com.example.npopa.musicplayern, PID: 15665
    java.lang.IllegalStateException
    at android.media.MediaPlayer._setAudioStreamType(Native Method)
        at android.media.MediaPlayer.setAudioStreamType(MediaPlayer.java:1868)
        at com.example.npopa.musicplayern.MusicService.initStreamPlayer(MusicService.java:72)
        at com.example.npopa.musicplayern.RadioStreaming$2.onItemClick(RadioStreaming.java:88)

这是我的代码:

package com.example.npopa.musicplayern;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.example.npopa.musicplayern.adapter.RadioAdapter;
import com.example.npopa.musicplayern.helpers.Streams;

import java.util.ArrayList;

public class RadioStreaming extends Fragment {
    private EditText et_streamNameRS, et_streamUrlRS;
    private static ArrayList<Streams> m_streamsList;
    private DBHelper m_myDBHelp;
    private MusicService m_musicSrv;
    public static Context m_context;
    private ListView m_listView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.radio_streaming, container, false);

        m_context = getContext();
        et_streamNameRS = (EditText) rootView.findViewById(R.id.et_streamNameRS);
        et_streamUrlRS = (EditText) rootView.findViewById(R.id.et_streamUrlRS);
        Button bt_addStreamRS = (Button) rootView.findViewById(R.id.bt_addStreamRS);
        m_listView = (ListView) rootView.findViewById(R.id.stream_listRS);

        m_myDBHelp = new DBHelper();
        m_streamsList = m_myDBHelp.selectStreamsList();

        if (m_streamsList.isEmpty()) {
            Toast.makeText(RadioStreaming.m_context, "There's no streams in DB. ADD streams!", Toast.LENGTH_LONG).show();
        }
        Log.d("RadioStreaming", " -------- TAG select m_streamsList ------" + m_streamsList.toString());

        RadioAdapter adapt = new RadioAdapter(m_context, m_streamsList);
        m_listView.setAdapter(adapt);

        bt_addStreamRS.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = et_streamNameRS.getText().toString();
                String url = et_streamUrlRS.getText().toString();
                m_myDBHelp.insertStreamIntoDB(name, url);

                m_listView.invalidate();
                m_streamsList = null;
                m_streamsList = m_myDBHelp.selectStreamsList();

                RadioAdapter adapt2 = new RadioAdapter(m_context, m_streamsList);
                m_listView.setAdapter(adapt2);

                et_streamNameRS.setText("");
                et_streamUrlRS.setText("");
            }
        });

        m_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (!Functions.checkNetworkState(m_context)) {
                    Toast.makeText(getContext(), "Enable WIFI or Mobile Data!", Toast.LENGTH_LONG).show();
                } else {
                    m_musicSrv = MusicService.getInstance();

                    if (MusicService.m_player != null) {
                        if (m_musicSrv.isPlaying()) {
                            if (m_musicSrv.is_playing_music) {
                                new SongDetails().stopHandler();

                                MusicService.m_player.stop();
                                MusicService.m_player.reset();  //It requires again setDataSource for player object.
                            //    MusicService.m_player.stop();
                                MusicService.m_player.release();
                            //    MusicService.m_player = null;   // Initilize to null so it can be used later

                                m_musicSrv.initStreamPlayer(m_context);
                                m_musicSrv.setStreamList(m_streamsList);

                                m_musicSrv.setStream(Integer.parseInt(view.getTag().toString()));
                                m_musicSrv.playStream();
                            }
                            else {
                                MusicService.m_player.reset();

                                m_musicSrv.initStreamPlayer(m_context);
                                m_musicSrv.setStreamList(m_streamsList);

                                m_musicSrv.setStream(Integer.parseInt(view.getTag().toString()));
                                m_musicSrv.playStream();
                            }
                        }
                        else {
                            m_musicSrv.initStreamPlayer(m_context);
                            m_musicSrv.setStreamList(m_streamsList);

                            m_musicSrv.setStream(Integer.parseInt(view.getTag().toString()));
                            m_musicSrv.playStream();
                        }
                    }
                    else {
                        m_musicSrv.initStreamPlayer(m_context);
                        m_musicSrv.setStreamList(m_streamsList);

                        m_musicSrv.setStream(Integer.parseInt(view.getTag().toString()));
                        m_musicSrv.playStream();
                    }
                }
            }
        });

        return rootView;
    }
}

package com.example.npopa.musicplayern;

        import android.content.ContentUris;
        import android.content.Context;
        import android.graphics.Bitmap;
        import android.media.AudioManager;
        import android.media.MediaPlayer;
        import android.net.Uri;
        import android.os.PowerManager;
        import android.util.Log;
        import android.widget.Toast;

        import com.example.npopa.musicplayern.helpers.Streams;
        import com.example.npopa.musicplayern.helpers.Song;

        import java.util.ArrayList;
        import java.util.Random;

        public class MusicService implements MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener {
            public static MediaPlayer m_player;
            public static String m_songTitle = "";
            public static String m_artistName = "";
            private static String m_streamNAME, m_streamURL;
            public static Bitmap m_albumImageMS;
            public static ArrayList<Song> m_songs;
            public static ArrayList<Streams> m_streams;
            public static int m_songPosn;
            public static int m_streamPosition;
            private static int m_streamID;
            public static boolean m_shuffle = false;
            public static boolean m_repeat = false;
            public boolean is_playing_music = false;
            public boolean is_playing_streams = false;
            private Random m_rand;
            private DBHelper m_db;

            private static MusicService myService = new MusicService();
            // a private Constructor prevents any other class from instantiating
            private MusicService() {
            }
            public static MusicService getInstance() {
                if (myService == null) {
                    myService = new MusicService();
                }

                return myService;
            }

            public void initSongPlayer(Context context) {
                m_songs = new ArrayList<Song>();
                m_songPosn = 0;
                if (m_player == null) {
                    m_player = new MediaPlayer();
                }

                m_player.setWakeMode(context, PowerManager.PARTIAL_WAKE_LOCK);
                m_player.setAudioStreamType(AudioManager.STREAM_MUSIC);

                m_player.setOnPreparedListener(this);
                m_player.setOnCompletionListener(this);
                m_player.setOnErrorListener(this);
            }

            public void initStreamPlayer(Context context) {
                m_streams = new ArrayList<Streams>();
                m_streamPosition = 0;
                if (m_player == null) {
                    m_player = new MediaPlayer();
                }

                m_player.setOnPreparedListener(this);
                m_player.setOnBufferingUpdateListener(this);
                m_player.setOnErrorListener(this);

                m_player.setWakeMode(context, PowerManager.PARTIAL_WAKE_LOCK);
                m_player.setAudioStreamType(AudioManager.STREAM_MUSIC);
            }


            public void setSong(int songIndex) {
                m_songPosn = songIndex;
            }

            public void setSongList(ArrayList<Song> theSongs) {
                Log.d("MusicService", "setSongList() - playlist nou marime: " + theSongs.size());

                if (theSongs.size() > 0){
                    m_songs = theSongs;

                    m_db = new DBHelper();
                    m_db.deleteAllSongsPlaylist();
                    m_db.setSongsLastPlaylist(m_songs);
                }

            }

            public void setStream(int streamIndex) {
                m_streamPosition = streamIndex;
            }

            public void setStreamList(ArrayList<Streams> theStreams) {
                m_streams = theStreams;
            }

            public void playSong(Context context) {
                if(m_songs.size() == 0) {
                    Log.d("MusicService", "playSong() - playlist 0 elemente");
                }
                else {
                    is_playing_music = true;
                    is_playing_streams = false;
                    m_player.reset();
                    Song playSong = m_songs.get(m_songPosn);
                    m_songTitle = playSong.getTitle();
                    m_artistName = playSong.getArtist();
                    m_albumImageMS = playSong.getAlbumImage();
                    long currSong = playSong.getID();
                    Log.d("MusicService", "---------------------CURRENT SONG ID " + String.valueOf(currSong));

                    Uri trackUri = ContentUris.withAppendedId(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, currSong);
                    try {
                        m_player.setDataSource(context, trackUri);
                    } catch (Exception e) {
                        Log.e("MusicService", "Error setting data source", e);
                    }
                    m_player.prepareAsync();

                    m_db = new DBHelper();
                    m_db.updatePlayerInfo(String.valueOf(currSong), 1);
                }
            }

            public void playStream() {
                is_playing_music = false;
                is_playing_streams = true;

                m_player.reset();
                Streams currStream = m_streams.get(m_streamPosition);
                m_streamID = currStream.getId();
                m_streamNAME = currStream.getName();
                m_streamURL = currStream.getUrl();

                try {                       //   http://usa8-vn.mixstream.net:8138
                    m_player.setDataSource(m_streamURL);
                    Log.d("MusicService", "------------------ playStream() ---------------------" + m_streamURL);
                } catch (Exception e) {
                    //  e.printStackTrace();
                    Log.d("MusicService", "---------- Error setting stream data source", e);
                }
                m_player.prepareAsync();

                DBHelper dbhelp = new DBHelper();
                dbhelp.updatePlayerInfo(String.valueOf(m_streamID), 0);
            }

            public Bitmap getAlbumImageMS() {
                return m_albumImageMS;
            }

            public String getMusicTitle() {
                return m_songTitle;
            }

            public String getMusicArtist() {
                return m_artistName;
            }

            public int getCurrentPosition() {
                return m_player.getCurrentPosition();
            }

            public int getDuration() {
                return m_player.getDuration();
            }

            public boolean isPlaying() {
                if (m_player == null){
                    return false;
                }
                else {
                    return m_player.isPlaying();
                }
            }

            public void seekTO(int posn) {
                m_player.seekTo(posn);
            }

            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                if (is_playing_streams) {
                    Toast.makeText(MainActivity.m_context, "Playback Error - INVALID URL", Toast.LENGTH_LONG).show();
                }
                Log.v("MusicService", "Playback Error");
                mp.reset();
                return false;
            }

            @Override
            public void onCompletion(MediaPlayer mp) {
                if (m_player.getCurrentPosition() > 0) {
                    mp.reset();
                    playNextSong();
                }
            }

            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.start();
                if (is_playing_music) {
                    Log.d("MusicService", "---------- Playing MUSIC--- :" + getMusicTitle() + " - - by - - " + getMusicArtist());
                }
                else if (is_playing_streams) {
                    Toast.makeText(MainActivity.m_context, "Playing STREAM:" + m_streamNAME + " from " + m_streamURL, Toast.LENGTH_LONG).show();
                    Log.d("MusicService", "---------- Playing STREAM:" + m_streamNAME + " from " + m_streamURL);
                }
            }

            @Override
            public void onBufferingUpdate(MediaPlayer mediaPlayer, int percent) {
                Log.d("MusicService", "---------- Buffering " + percent);
                Toast.makeText(MainActivity.m_context, "Buffering: " + percent, Toast.LENGTH_LONG).show();
            }

            public void playNextSong() {
                m_rand = new Random();
                if (m_repeat == true) {
                    int pos1 = m_songPosn;
                    m_songPosn = pos1;
                } else if (m_shuffle == true) {
                    int newSong = m_songPosn;
                    while (newSong == m_songPosn) {
                        newSong = m_rand.nextInt(m_songs.size());
                    }
                    m_songPosn = newSong;
                } else if (m_repeat == true && m_shuffle == true) {
                    int pos2 = m_songPosn;
                    m_songPosn = pos2;
                } else {
                    ////////////////////////////////////////////
                    m_songPosn++;
                    if (m_songPosn >= m_songs.size()) {
                        m_songPosn = 0;
                    }
                }
                playSong(MainActivity.m_context);
            }

            public void playPrevSong() {
                if (m_shuffle == true) {
                    int newSong = m_songPosn;
                    while (newSong == m_songPosn) {
                        newSong = m_rand.nextInt(m_songs.size());
                    }
                    m_songPosn = newSong;
                } else {
                    m_songPosn--;
                    if (m_songPosn < 0) {
                        m_songPosn = m_songs.size() - 1;
                    }
                }
                playSong(MainActivity.m_context);
            }

            public void playNextStream() {
                m_streamPosition++;
                if (m_streamPosition >= m_streams.size()) {
                    m_streamPosition = 1;
                }
                playStream();
            }

            public void playPrevStream() {
                m_streamPosition--;
                if (m_streamPosition < 1) {
                    m_streamPosition = m_streams.size() - 1;
                }
                playStream();
            }
        }

感谢各种帮助。提前谢谢。

0 个答案:

没有答案