Пример #1
0
  /**
   * Starts playing the next song. If manualUrl is null, the next song will be randomly selected
   * from our Media Retriever (that is, it will be a random song in the user's device). If manualUrl
   * is non-null, then it specifies the URL or path to the song that will be played next.
   */
  void playNextSong(String manualUrl) {
    mState = State.Stopped;
    relaxResources(false); // release everything except MediaPlayer

    try {
      if (manualUrl != null) {
        // set the source of the media player to a manual URL or path
        createMediaPlayerIfNeeded();
        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mPlayer.setDataSource(manualUrl);
        mSongTitle = manualUrl;
        mIsStreaming = manualUrl.startsWith("http:") || manualUrl.startsWith("https:");
      } else {
        mIsStreaming = false; // playing a locally available song

        MusicRetriever.Item item = mRetriever.getRandomItem();
        if (item == null) {
          say("No song to play :-(");
          return;
        }

        // set the source of the media player a a content URI
        createMediaPlayerIfNeeded();
        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mPlayer.setDataSource(getApplicationContext(), item.getURI());
        mSongTitle = item.getTitle();
      }

      mState = State.Preparing;
      setUpAsForeground(mSongTitle + " (loading)");

      // starts preparing the media player in the background. When it's done, it will call
      // our OnPreparedListener (that is, the onPrepared() method on this class, since we set
      // the listener to 'this').
      //
      // Until the media player is prepared, we *cannot* call start() on it!
      mPlayer.prepareAsync();

      // If we are streaming from the internet, we want to hold a Wifi lock, which prevents
      // the Wifi radio from going to sleep while the song is playing. If, on the other hand,
      // we are *not* streaming, we want to release the lock if we were holding it before.
      if (mIsStreaming) mWifiLock.acquire();
      else if (mWifiLock.isHeld()) mWifiLock.release();
    } catch (IOException ex) {
      Log.e("MusicService", "IOException playing next song: " + ex.getMessage());
      ex.printStackTrace();
    }
  }
 @Override
 protected Void doInBackground(Void... arg0) {
   mRetriever.prepare();
   return null;
 }