尝试在android中没有有效的媒体播放器的情况下调用getDuration

时间:2013-12-03 10:02:26

标签: android android-mediaplayer audio-streaming

主要有两类。一个是服务类,另一个是活动。 这是我的服务类,我想知道我犯了什么错误...它说没有有效的媒体播放器调用get duration ...我正在管理来自其他类的媒体播放器

public class MediaPlayerService extends Service implements OnBufferingUpdateListener, OnInfoListener, OnPreparedListener, OnErrorListener {
    private static StatefulMediaPlayer mMediaPlayer            = new StatefulMediaPlayer();
    private final Binder mBinder                        = new MediaPlayerBinder();
    private IMediaPlayerServiceClient mClient;

    /**
     * A class for clients binding to this service. The client will be passed an object of this class
     * via its onServiceConnected(ComponentName, IBinder) callback.
     */

    public class MediaPlayerBinder extends Binder {
        /**
         * Returns the instance of this service for a client to make method calls on it.
         * @return the instance of this service.
         */
        public MediaPlayerService getService() {
            return MediaPlayerService.this;
        }
    }

    /**
     * Returns the contained StatefulMediaPlayer
     * @return
     */
    public StatefulMediaPlayer getMediaPlayer() {
        return mMediaPlayer;
    }

    /**
     * Initializes a StatefulMediaPlayer for streaming playback of the provided StreamStation
     * @param station The StreamStation representing the station to play
     */
    public void initializePlayer(StreamStation station) {
        mClient.onInitializePlayerStart("Connecting...");
        mMediaPlayer = new StatefulMediaPlayer(station);
        mMediaPlayer.setOnBufferingUpdateListener(this);
        mMediaPlayer.setOnInfoListener(this);
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.prepareAsync();
    }

    /**
     * Initializes a StatefulMediaPlayer for streaming playback of the provided stream url
     * @param streamUrl The URL of the stream to play.
     */
    public void initializePlayer(String streamUrl) {

        mMediaPlayer = new StatefulMediaPlayer();
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        try {
            mMediaPlayer.setDataSource(streamUrl);
        }
        catch (Exception e) {
            Log.e("MediaPlayerService", "error setting data source");
            mMediaPlayer.setState(MPStates.ERROR);
        }
        mMediaPlayer.setOnBufferingUpdateListener(this);
        mMediaPlayer.setOnInfoListener(this);
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.prepareAsync();
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return mBinder;
    }

    @Override
    public void onBufferingUpdate(MediaPlayer player, int percent) {
        MusicPlayerActivity.seekbar.setSecondaryProgress(percent);
    }

    @Override
    public boolean onError(MediaPlayer player, int what, int extra) {
        mMediaPlayer.reset();
        mClient.onError();
        return true;
    }

    @Override
    public boolean onInfo(MediaPlayer mp, int what, int extra) {
        return false;
    }

    @Override
    public void onPrepared(MediaPlayer player) {
        mClient.onInitializePlayerSuccess();
        startMediaPlayer();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
          return START_STICKY;
    }

    /**
     * Pauses the contained StatefulMediaPlayer
     */
    public void pauseMediaPlayer() {
        Log.d("MediaPlayerService","pauseMediaPlayer() called");
        mMediaPlayer.pause();
        stopForeground(true);
    }

    /**
     * Sets the client using this service.
     * @param client The client of this service, which implements the IMediaPlayerServiceClient interface
     */
    public void setClient(IMediaPlayerServiceClient client) {
        this.mClient = client;
    }

    /**
     * Starts the contained StatefulMediaPlayer and foregrounds the service to support
     * persisted background playback.
     */
    public void startMediaPlayer() {
        Context context = getApplicationContext();

        //set to foreground
        /*Notification notification = new Notification(android.R.drawable.ic_media_play, "MediaPlayerService",
                System.currentTimeMillis());*/
        /*Notification notification = new Notification();*/
        /*Intent notificationIntent = new Intent(this, MusicPlayerActivity.class);
        notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        CharSequence contentTitle = "MediaPlayerService Is Playing";
        CharSequence contentText = mMediaPlayer.getStreamStation().getStationLabel();*/
        /*notification.setLatestEventInfo(context, contentTitle,
                contentText, pendingIntent);
        startForeground(1, notification);*/

        Log.d("MediaPlayerService","startMediaPlayer() called");
        mMediaPlayer.start();

       // MusicPlayerActivity.startPlayProgressUpdater();
        //MusicPlayerActivity.updateSeekProgress();
        updateSeekProgress();   
       //MusicPlayerActivity.setProgressBar();
    }

    private final static Handler handler1 = new Handler();
    private final static Runnable r = new Runnable() {  
        @Override
        public void run() {
            updateSeekProgress();                   
        }
    };

    public static void updateSeekProgress() {
        if (mMediaPlayer.isPlaying()) {
        MusicPlayerActivity.seekbar.setProgress((int)(((float)mMediaPlayer.getCurrentPosition() / mMediaPlayer.getDuration()) * 100));
            handler1.postDelayed(r, 1000);
        }
    }

    /**
     * Stops the contained StatefulMediaPlayer.
     */
    public void stopMediaPlayer() {
        stopForeground(true);
        mMediaPlayer.stop();
        mMediaPlayer.release();
    }

    public void resetMediaPlaer() {
        stopForeground(true);
        mMediaPlayer.reset();
    }
}

这是我正在播放歌曲的活动......

public class MusicPlayerActivity extends ActionBarActivity implements mp.IMediaPlayerServiceClient{

    public static StatefulMediaPlayer mMediaPlayer;
//    private StreamStation mSelectedStream = CONSTANTS.DEFAULT_STREAM_STATION;
    private StreamStation mSelectedStream;
    public static MediaPlayerService mService;
    public static String streamUrl;
    public static String lyricsText;
    TextView lyricsTextView;
    //ImageButton playButton;
    private ScrollView scrollView1;
    private Timer scrollTimer = null;

    private boolean mBound;

    public int lengthOfAudio;

    ActionBar actionBar;
    TextView txt_actionTitle;

    private ProgressDialog mProgressDialog;

    // streaming var
    private static final String LOG_TAG = "AudioRecordTest";
    private static ToggleButton playPauseButton = null;
    public static StreamingMediaPlayer audioStreamer;
    private int current = 0;
    private static boolean   running = true;
    private int duration = 0;
    private boolean isPlaying;
    //public static SeekBar progressBar;
    public static SeekBar seekbar;
    private static String mFileName = null;
    private MediaPlayer mPlayer = null;
    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_player);

        // initialize receiver
        IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        BroadcastReceiver mReceiver = new BootReceiver();
        registerReceiver(mReceiver, filter);

        actionBar = getSupportActionBar();
        actionBar.setDisplayShowCustomEnabled(true);
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setCustomView(R.layout.actionbar_view);
        txt_actionTitle = (TextView)actionBar.getCustomView().findViewById(R.id.action_title);
        actionBar.setIcon(R.drawable.music_icon);
        txt_actionTitle.setText(SongListActivity.songName);
        actionBar.setDisplayHomeAsUpEnabled(true);

        //progressBar = (SeekBar) findViewById(R.id.progressBar);
        seekbar = (SeekBar) findViewById(R.id.progressBar);

        lyricsTextView = (TextView) findViewById(R.id.lirics);
        lyricsTextView.setTypeface(HomeActivity.face);

        scrollView1 = (ScrollView) findViewById(R.id.scrollview);
        //playButton = (ImageButton) findViewById(R.id.playPause);

        bindToService();
        mProgressDialog = new ProgressDialog(this);
        initializeButtons();
        initControls();
        try {
            new LoadLyricsOperation().execute("");
        } catch (Exception ex) {
            // TODO: handle exception
            Log.e(" Lyrics - Background Process - ", ex.getMessage());
        }

        seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                    boolean fromUser) {
                // TODO Auto-generated method stub
                seekBar.setProgress(progress);
            }
        });

    }

    /*public static void setProgressBar(){
        Log.i("Total :", ""+mMediaPlayer.getDuration());
         progressBar.setMax(mMediaPlayer.getDuration());
         progressBar.postDelayed(onEverySecond, 1000);
    }
    */

     public void bindToService() {
            Intent intent = new Intent(this, MediaPlayerService.class);

            if (MediaPlayerServiceRunning()) {
                // Bind to LocalService
                bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
            }
            else {
                startService(intent);
                bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
            }
        }

    private void initializeButtons() {
        // PLAY/PAUSE BUTTON
        playPauseButton = (ToggleButton) findViewById(R.id.playPause);
        playPauseButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mBound) {
                    mMediaPlayer = mService.getMediaPlayer();

                    //pressed pause ->pause
                    if (!playPauseButton.isChecked()) {

                        if (mMediaPlayer.isStarted()) {
                            mService.pauseMediaPlayer();
                        }
                    }

                    //pressed play
                    else if (playPauseButton.isChecked()) {
                        // STOPPED, CREATED, EMPTY, -> initialize
                        if (mMediaPlayer.isStopped()
                                || mMediaPlayer.isCreated()
                                || mMediaPlayer.isEmpty())
                        {
                            //mMediaPlayer.getDuration();
                            /*mSelectedStream = streamUrl;*/
                            mSelectedStream = new StreamStation(streamUrl);
                            mService.initializePlayer(mSelectedStream);
                           // updateSeekProgress();
                        }

                        //prepared, paused -> resume play
                        else if (mMediaPlayer.isPrepared()
                                || mMediaPlayer.isPaused())
                        {
                            mService.startMediaPlayer();
                            //updateSeekProgress();
                            //progressBar.setMax(mMediaPlayer.getDuration());
                           // progressBar.postDelayed(onEverySecond, 1000);
                        }
                    }
                }
            }
        });
    }

    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder serviceBinder) {
            Log.d("MainActivity","service connected");

            //bound with Service. get Service instance
            MediaPlayerBinder binder = (MediaPlayerBinder) serviceBinder;
            mService = binder.getService();

            //send this instance to the service, so it can make callbacks on this instance as a client
            mService.setClient(MusicPlayerActivity.this);
            mBound = true;

            //Set play/pause button to reflect state of the service's contained player
            final ToggleButton playPauseButton = (ToggleButton) findViewById(R.id.playPause);
            playPauseButton.setChecked(mService.getMediaPlayer().isPlaying());

            //Set station Picker to show currently set stream station
            //Spinner stationPicker = (Spinner) findViewById(R.id.stationPicker);
            /*if(mService.getMediaPlayer() != null && mService.getMediaPlayer().getStreamStation() != null) {
                for (int i = 0; i < CONSTANTS.STATIONS.length; i++) {
                    if (mService.getMediaPlayer().getStreamStation().equals(CONSTANTS.STATIONS[i])) {
                        stationPicker.setSelection(i);
                        mSelectedStream = (StreamStation) stationPicker.getItemAtPosition(i);
                    }
                }
            }*/
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBound = false;
        }
    };

     /** Determines if the MediaPlayerService is already running.
     * @return true if the service is running, false otherwise.
     */
    private boolean MediaPlayerServiceRunning() {

        ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);

        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if ("mp.MediaPlayerService".equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

    public void onInitializePlayerSuccess() {
        mProgressDialog.dismiss();
        //updateSeekProgress();
        final ToggleButton playPauseButton = (ToggleButton) findViewById(R.id.playPause);
        playPauseButton.setChecked(true);
    }

    public void onInitializePlayerStart(String message) {
        mProgressDialog = ProgressDialog.show(this, "", message, true);
        mProgressDialog.getWindow().setGravity(Gravity.TOP);
        mProgressDialog.setCancelable(true);
        mProgressDialog.setOnCancelListener(new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialogInterface) {
                    MusicPlayerActivity.this.mService.resetMediaPlaer();
                    final ToggleButton playPauseButton = (ToggleButton) findViewById(R.id.playPause);
                    playPauseButton.setChecked(false);
            }

        });

    }

    @Override
    public void onError() {
            mProgressDialog.cancel();
    }

    /**
     * Closes unbinds from service, stops the service, and calls finish()
     */
    public void shutdownActivity() {

        if (mBound) {
            mService.stopMediaPlayer();
            // Detach existing connection.
            unbindService(mConnection);
            mBound = false;
         }
        Intent intent = new Intent(this, MediaPlayerService.class);
        stopService(intent);
        finish();
    }

    private void getLyrics() {
        // TODO Auto-generated method stub
        try {
            InputStream in = getResources().openRawResource(R.raw.z_data);
            DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder();
            Document doc = builder.parse(in,null);
            NodeList albumnode = doc.getElementsByTagName("album");
            for (int k = 0; k < albumnode.getLength(); k++) {
                Node album = albumnode.item(k);
                Element fstElmnt = (Element) album;
                String albu = fstElmnt.getAttribute("value");
                if (albu.equals(TrackFragment.albumName)) {
                    NodeList songList = fstElmnt.getElementsByTagName("songs");
                    for (int i = 0; i < songList.getLength(); i++) {
                        Node song = songList.item(i);
                        Element songElmnt = (Element) song;
                        String songval = songElmnt.getAttribute("value");
                        if (songval.equals(SongListActivity.songName)) {
                            NodeList urlList = songElmnt
                                    .getElementsByTagName("url");
                            Node uNode = urlList.item(0);
                            Element urlElememt = (Element) uNode;
                            streamUrl = urlElememt.getAttribute("value");

                            NodeList lyrcsList = songElmnt
                                    .getElementsByTagName("lyrics");
                            Node lNode = lyrcsList.item(0).getFirstChild();
                            lyricsText = lNode.getNodeValue();
                            //System.out.print(lyricsText);
                        }
                    }
                }
            }
            in.close();
        } catch (Exception t) {
            Log.e("Exception: ", t.getMessage());
        }
    }

    public class LoadLyricsOperation extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            try {
                getLyrics();
            } catch (Exception ex) {

            }
            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {
            try {

                if (lyricsText != null) {
                    lyricsTextView.setText(lyricsText);
                }

                if (streamUrl != null) {
                    //startStreamingAudio(streamUrl);

                    scroll();
                }

            } catch (Exception ex) {
            }
        }

        @Override
        protected void onPreExecute() {
            try {

            } catch (Exception ex) {

            }
        }
    }

    /*private void startStreamingAudio(String urlstring) {
        try {
            final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
            if (audioStreamer != null) {
                audioStreamer.interrupt();
            }
            audioStreamer = new StreamingMediaPlayer(this, textStreamed,
                    (ImageButton) playButton, streamButton, progressBar);
            audioStreamer.startStreaming(urlstring, 5208, 216);

            // streamButton.setEnabled(false);

        } catch (Exception e) {
            Log.e(getClass().getName(), "Error starting to stream audio.", e);
        }
    }*/

    public MusicPlayerActivity() {
        mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
        mFileName += "/audiorecordtest.mp3";
    }

    public class PlayButton extends Button {
        boolean mStartPlaying = true;

        OnClickListener clicker = new OnClickListener() {
            public void onClick(View v) {
                onPlay(mStartPlaying);
                if (mStartPlaying) {
                    setText("Stop playing");
                } else {
                    setText("Start playing");
                }
                mStartPlaying = !mStartPlaying;
            }
        };

        public PlayButton(Context ctx) {
            super(ctx);
            setText("Start playing");
            setOnClickListener(clicker);
        }
    }

    private void onPlay(boolean start) {
        if (start) {
            startPlaying();
        } else {
            stopPlaying();
        }
    }

    private void startPlaying() {
        mPlayer = new MediaPlayer();
        try {
            mPlayer.setDataSource(mFileName);
            mPlayer.prepare();
            mPlayer.start();
        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");
        }
    }

    private void stopPlaying() {
        mPlayer.release();
        mPlayer = null;
    }

    private void initControls() {
        /*  

        //playButton.setEnabled(false);
        playButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                if(!StreamingMediaPlayer.buffering) 
                {
                    if (audioStreamer.getMediaPlayer() != null) {
                        if (audioStreamer.getMediaPlayer().isPlaying()) {
                            audioStreamer.getMediaPlayer().pause();
                            playButton.setImageResource(R.drawable.player_play_icon);
                        } else {
                            audioStreamer.getMediaPlayer().start();
                            audioStreamer.startPlayProgressUpdater();
                            playButton.setImageResource(R.drawable.player_pause_icon);
                        }
                    }
                } 
            else {
                    Toast.makeText(MusicPlayerActivity.this, "Buffering...",
                            Toast.LENGTH_SHORT).show();
                }
                isPlaying = !isPlaying;
            }
        });

        startStreamingAudio(streamUrl);

    */

    }

    public void scroll() {
        if (scrollTimer == null) {
            scrollTimer = new Timer();
        }
        TimerTask scrollerSchedule = new TimerTask() {

            @Override
            public void run() {

                handler.post(new Runnable() {
                    public void run() {
                        // Here I want to increment the scrollbar's vertical
                        // position by 1
                        int x = scrollView1.getScrollY();
                        scrollView1.smoothScrollTo(0, x + 1);
                    }
                });
            }
        };
        scrollTimer.schedule(scrollerSchedule, 0, 120);
    }

    /*private static Runnable onEverySecond = new Runnable() {
        @Override
        public void run(){
            if(true == running){
                if(progressBar != null) {
                    Log.i("Current :", ""+mMediaPlayer.getCurrentPosition());
                    progressBar.setProgress(mMediaPlayer.getCurrentPosition());
                }

                if(mMediaPlayer.isPlaying()) {
                    progressBar.postDelayed(onEverySecond, 1000);
//                  updateTime();
                }
            }
        }
    };*/

    /*@Override
    public void onPrepared(MediaPlayer arg0) {
        // TODO Auto-generated method stub
        mService.onPrepared(arg0);
        duration = mMediaPlayer.getDuration();
        progressBar.setMax(duration);
        progressBar.postDelayed(onEverySecond, 1000);
    }*/

    protected void onDestroy() {
        super.onDestroy();
        if (audioStreamer != null) {
            audioStreamer.interrupt();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.image, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
        switch(item.getItemId()) 
        {
            case R.id.action_share:
                if (audioStreamer != null) {
                    audioStreamer.interrupt();
                }

                /*if(StreamingMediaPlayer.buffering)    
                {
                    audioStreamer.startPlayProgressUpdater();
                }*/

                Intent share = new Intent(Intent.ACTION_SEND);
                share.setType("text/plain");
                share.putExtra(Intent.EXTRA_TEXT,"I am Listening " + SongListActivity.songName +" Song.\n\n Lirics:\n"+lyricsText+"\n\n From : https://play.google.com/store/apps/details?id="+getPackageName());
                startActivity(Intent.createChooser(share, "Share"));
                break;

            case android.R.id.home:
                if (audioStreamer != null) {
                    audioStreamer.interrupt();
                }
                Intent i = new Intent(getApplicationContext(), SongListActivity.class);
                startActivity(i);
                break;
        }
        return false;
    }

    @Override
    public void onBackPressed() {

        if (playPauseButton.isChecked() == true) {
            //mService.pauseMediaPlayer();
            Toast.makeText(getApplicationContext(), "Stop Media Player", Toast.LENGTH_SHORT).show();
        }
        else
        {
            shutdownActivity();
            seekbar.setMax(0);
            BootReceiver.wasScreenOnmp = false;
            mMediaPlayer = null;
            finish();
        }

        /*if (audioStreamer != null) {
            //StreamingMediaPlayer.mediaPlayer = null;
            audioStreamer.interrupt();
        }*/
        //StreamingMediaPlayer.buffering = true;

        /*Intent i = new Intent(getApplicationContext(), SongListActivity.class);
        startActivity(i);*/
        //super.onBackPressed();
    }

    @Override
    protected void onPause() {

        if (BootReceiver.wasScreenOnmp) {
            // this is the case when onPause() is called by the system due to a
            // screen state change
            System.out.println("SCREEN TURNED OFF");
            //System.out.println(playPauseButton.isChecked());

            if(mMediaPlayer != null){
                mService.pauseMediaPlayer();
                playPauseButton.setChecked(false);

                /*if(mMediaPlayer.isPlaying())
                {
                    System.out.println("Song Playing");
                    mService.pauseMediaPlayer();
                }else {
                    System.out.println("Song Paused");
                }*/
            }

        } else {
            // this is when onPause() is called when the screen state has not
            // changed
        }
        super.onPause();
    }

    @Override
    protected void onResume() {

        super.onResume();
    }
}

0 个答案:

没有答案