Exemplo n.º 1
0
  private void createPlayer() {
    try {
      if (mSongSelector == null) mSongSelector = new SongSelector(getContentResolver(), this);

      if (mPlayer == null) {
        mPlayer = new MediaPlayer();

        mPlayer.setOnPreparedListener(this);
        mPlayer.setOnSeekCompleteListener(this);
        mPlayer.setOnCompletionListener(this);
        mPlayer.setOnErrorListener(this);

        mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
      }
    } catch (IllegalArgumentException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (SecurityException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IllegalStateException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Exemplo n.º 2
0
  @Override
  public void onCreate() {
    super.onCreate();
    // if the mediaPlayer object is null, create it
    if (player == null) player = new MediaPlayer();
    // acquire partial wake lock to allow background playback
    player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);

    registerReceiver(stopServiceReceiver, new IntentFilter(NOTIFICATION_FILTER));

    phoneStateListener =
        new PhoneStateListener() {
          @Override
          public void onCallStateChanged(int state, String incomingNumber) {
            if (state == TelephonyManager.CALL_STATE_RINGING) {
              resetPlayer(MediaService.this);
            } else if (state == TelephonyManager.CALL_STATE_IDLE) {
              // Could resume music here, but listener is removed.
            } else if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
              resetPlayer(MediaService.this);
            }
            super.onCallStateChanged(state, incomingNumber);
          }
        };
  }
Exemplo n.º 3
0
 public void initAudioPlayer() {
   mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
   mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
   mediaPlayer.setOnPreparedListener(this);
   // mediaPlayer.setOnCompletionListener(this);
   mediaPlayer.setOnErrorListener(this);
 }
 public void initMusicPlayer() {
   // set player properties
   player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
   player.setAudioStreamType(AudioManager.STREAM_MUSIC);
   // set listeners
   player.setOnPreparedListener(this);
   player.setOnCompletionListener(this);
   player.setOnErrorListener(this);
 }
Exemplo n.º 5
0
 public void onCreate() {
   super.onCreate();
   position = 0;
   play = new MediaPlayer();
   play.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
   play.setAudioStreamType(AudioManager.STREAM_MUSIC);
   play.setOnPreparedListener(this);
   play.setOnErrorListener(this);
   play.setOnCompletionListener(this);
 }
Exemplo n.º 6
0
  private void setupMediaPlayerIfNeeded() {
    Logger.debug(TAG, ">>>" + "setupMediaPlayerIfNeeded");
    if (mediaPlayer == null) {
      mediaPlayer = new MediaPlayer();
      mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);

      mediaPlayer.setOnPreparedListener(onPreparedListener);
      mediaPlayer.setOnCompletionListener(onCompletionListener);
      mediaPlayer.setOnErrorListener(onErrorListener);

    } else {
      mediaPlayer.reset();
    }
  }
Exemplo n.º 7
0
  /**
   * Makes sure the media player exists and has been reset. This will create the media player if
   * needed, or reset the existing media player if one already exists.
   */
  void createMediaPlayerIfNeeded() {
    if (mPlayer == null) {
      mPlayer = new MediaPlayer();

      // Make sure the media player will acquire a wake-lock while playing. If we don't do
      // that, the CPU might go to sleep while the song is playing, causing playback to stop.
      //
      // Remember that to use this, we have to declare the android.permission.WAKE_LOCK
      // permission in AndroidManifest.xml.
      mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);

      // we want the media player to notify us when it's ready preparing, and when it's done
      // playing:
      mPlayer.setOnPreparedListener(this);
      mPlayer.setOnCompletionListener(this);
      mPlayer.setOnErrorListener(this);
    } else mPlayer.reset();
  }
  private MediaPlayer initializePlayer() {
    MediaPlayer player = new MediaPlayer();
    player.setAudioStreamType(AudioManager.STREAM_MUSIC);
    player.setOnPreparedListener(this);
    player.setOnCompletionListener(this);
    player.setOnErrorListener(this);
    player.setOnSeekCompleteListener(this);
    player.setWakeMode(this, PowerManager.PARTIAL_WAKE_LOCK);

    IntentFilter filter = new IntentFilter();
    filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    filter.addAction(Intent.ACTION_HEADSET_PLUG);
    filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
    filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
    registerReceiver(audioOutputChangedEventReceiver, filter);

    return player;
  }
Exemplo n.º 9
0
  /**
   * Makes sure the media player exists and has been reset. This will create the media player if
   * needed, or reset the existing media player if one already exists.
   */
  private void createMediaPlayerIfNeeded() {
    LogHelper.d(TAG, "createMediaPlayerIfNeeded. needed? ", (mMediaPlayer == null));
    if (mMediaPlayer == null) {
      mMediaPlayer = new MediaPlayer();

      // Make sure the media player will acquire a wake-lock while
      // playing. If we don't do that, the CPU might go to sleep while the
      // song is playing, causing playback to stop.
      mMediaPlayer.setWakeMode(mService.getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);

      // we want the media player to notify us when it's ready preparing,
      // and when it's done playing:
      mMediaPlayer.setOnPreparedListener(this);
      mMediaPlayer.setOnCompletionListener(this);
      mMediaPlayer.setOnErrorListener(this);
      mMediaPlayer.setOnSeekCompleteListener(this);
    } else {
      mMediaPlayer.reset();
    }
  }
Exemplo n.º 10
0
  @Override
  public void onCreate() {
    Util.setUncaughtExceptionHandler(this);
    super.onCreate();

    mediaPlayer = new MediaPlayer();
    mediaPlayer.setWakeMode(this, PowerManager.PARTIAL_WAKE_LOCK);

    mediaPlayer.setOnErrorListener(
        new MediaPlayer.OnErrorListener() {
          @Override
          public boolean onError(MediaPlayer mediaPlayer, int what, int more) {
            handleError(new Exception("MediaPlayer error: " + what + " (" + more + ")"));
            return false;
          }
        });

    if (equalizerAvailable) {
      equalizerController = new EqualizerController(this, mediaPlayer);
      if (!equalizerController.isAvailable()) {
        equalizerController = null;
      } else {
        equalizerController.loadSettings();
      }
    }
    if (visualizerAvailable) {
      visualizerController = new VisualizerController(this, mediaPlayer);
      if (!visualizerController.isAvailable()) {
        visualizerController = null;
      }
    }

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
    wakeLock.setReferenceCounted(false);

    instance = this;
    lifecycleSupport.onCreate();
  }
Exemplo n.º 11
0
  protected void playNew() {
    if (mMediaPlayer != null) {
      mMediaPlayer.reset();
    } else {
      mMediaPlayer = new MediaPlayer();
    }
    mMediaPlayerState = MediaPlayerState.IDLE;
    try {
      mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
      mMediaPlayer.setOnCompletionListener(this);
      mMediaPlayer.setOnErrorListener(this);
      mMediaPlayer.setOnPreparedListener(this);
      mMediaPlayer.setDataSource(path);
      mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
      mMediaPlayer.prepareAsync();

      mMediaPlayerState = MediaPlayerState.PREPARING;

    } catch (Exception e) {
      e.printStackTrace();
      log("===>>>>" + e.getMessage());
    }
  }
Exemplo n.º 12
0
 @Override
 public void setWakeMode(@NonNull Context context, int mode) {
   audioPlayer.setWakeMode(context, mode);
 }
Exemplo n.º 13
0
 private void initPlayer() {
   mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
   mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
 }
Exemplo n.º 14
0
  @Override
  public void onCreate() {
    super.onCreate();

    android_id =
        Settings.Secure.getString(
            getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);

    currentPlaylist = new ArrayList<Track>();

    realm = Realm.getInstance(Migration.getConfig(this));
    tracks =
        realm.where(Track.class).equalTo("isHidden", false).equalTo("isAvailable", true).findAll();

    mOnAudioFocusChangeListener =
        new AudioManager.OnAudioFocusChangeListener() {
          @Override
          public void onAudioFocusChange(int focusChange) {
            switch (focusChange) {
              case AudioManager.AUDIOFOCUS_GAIN:
                audioFocus = true;

                mp.setVolume(1f, 1f);

                if (wasPlaying) {
                  playPause();
                }
                break;
              case AudioManager.AUDIOFOCUS_LOSS:
                audioFocus = false;
                wasPlaying = false;

                if (mp.isPlaying()) {
                  mp.stop();
                  am.abandonAudioFocus(mOnAudioFocusChangeListener);
                }
                break;
              case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                audioFocus = false;
                if (mp.isPlaying()) {
                  playPause();
                }
                break;
              case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                if (mp.isPlaying()) {
                  mp.setVolume(0.2f, 0.2f);
                }
                break;
            }
          }
        };

    am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    mp = new MediaPlayer();
    mp.setOnPreparedListener(
        new MediaPlayer.OnPreparedListener() {
          @Override
          public void onPrepared(MediaPlayer mp) {
            sendBroadcast(new Intent().setAction(INTENT_MP_READY));

            Log.d(TAG, "mp.onPrepared!");

            mStartTime = System.currentTimeMillis();
            accumulatedPlaytimeForThisTrack = 0;

            playPause();
          }
        });

    mp.setOnCompletionListener(
        new MediaPlayer.OnCompletionListener() {
          @Override
          public void onCompletion(MediaPlayer mp) {
            Log.d(
                TAG,
                "onCompletion is called! I want to monitor in the future to see if when i skip a song, will this method be played");

            if (currentTrack != null) {
              createTrackStats(currentTrack.getLocal_id(), TrackStats.SONG_COMPLETED);
              prepNextSong();
            }
          }
        });

    mp.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);

    mReceiver =
        new BroadcastReceiver() {
          @Override
          public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "intent.getAction(): " + intent.getAction());
            switch (intent.getAction()) {
              case MainActivity.INTENT_PLAY_PAUSE:
                playPause();
                break;
              case MainActivity.INTENT_NEXT:
                checkIfRegisterAsSkip();
                prepNextSong();
                break;
              case MainActivity.INTENT_LIKED:
                if (currentTrack != null) {
                  createTrackStats(currentTrack.getLocal_id(), TrackStats.SONG_LIKED);
                }
                break;
              case MainActivity.INTENT_DISLIKED:
                if (currentTrack != null) {
                  createTrackStats(currentTrack.getLocal_id(), TrackStats.SONG_DISLIKED);
                }
                prepNextSong();
                break;
              case INTENT_SESSION_TRACKS_GENERATED:
                prepNextSong();
                break;
              case INTENT_DISMISS_NOTIFICATION:
                stopMediaPlayerService();
                break;
              case INTENT_THERE_IS_NO_SONGS:
                stopMediaPlayerService();
                break;
              case AudioManager.ACTION_AUDIO_BECOMING_NOISY:
                pause();
                break;
              case android.content.Intent.ACTION_HEADSET_PLUG:
                int state = intent.getIntExtra("state", 4);
                if (state == 0) {
                  // unplugged
                  pause();
                } else if (state == 1) {
                  // plugged in
                  if (currentTrack != null) {
                    play();
                  }
                } else {
                  // others??
                }
                break;
            }
          }
        };

    intentFilter = new IntentFilter();
    intentFilter.addAction(MainActivity.INTENT_PLAY_PAUSE);
    intentFilter.addAction(MainActivity.INTENT_NEXT);
    intentFilter.addAction(MainActivity.INTENT_LIKED);
    intentFilter.addAction(MainActivity.INTENT_DISLIKED);
    intentFilter.addAction(INTENT_DISMISS_NOTIFICATION);
    intentFilter.addAction(INTENT_THERE_IS_NO_SONGS);
    intentFilter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    intentFilter.addAction(android.content.Intent.ACTION_HEADSET_PLUG);
    // intentFilter.addAction(INTENT_SESSION_TRACKS_GENERATED);

    registerReceiver(mReceiver, intentFilter);

    initNotification();
  }
  private void playmp3() {
    boolean mExternalStorageAvailable = false;
    String state = Environment.getExternalStorageState();
    Logger.d(TAG, "Go Play 3");
    if (Environment.MEDIA_MOUNTED.equals(state)) {
      // We can read and write the media
      mExternalStorageAvailable = true;
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
      // We can only read the media
      mExternalStorageAvailable = true;
    } else {
      // Something else is wrong. It may be one of many other states, but all we need
      //  to know is we can neither read nor write
      mExternalStorageAvailable = false;
    }
    if (mExternalStorageAvailable) {
      // Log.i(TAG, Environment.getExternalStorageState());
      File filesystem = Environment.getExternalStorageDirectory();
      if (usedropboxchecked) {
        Logger.d(
            TAG,
            "Music Player knows that we should use a foder that is synced with a cloud storage");
        localfolderstring =
            filesystem.getPath()
                + "/"
                + AlarmClockConstants.BASE_FOLDER
                + "/"
                + AmbientAlarmManager.getAlarmByRegisteredAction(actionID).getAlarmID()
                + "/"
                + actionID;
      }
      File file = new File(localfolderstring);
      // Log.d(TAG, "wakeupsongsX");
      File[] filelist3 = new File[0];
      // Log.d(TAG, "--1");
      try {
        filelist3 = file.listFiles();
      } catch (Exception e) {
        Logger.d(TAG, "Could not get Filelist");
      }
      // Log.d(TAG, "--2");
      // count mp3s
      int numberOfMp3 = 0;
      String musicpath = "";
      if (filelist3 != null) {
        for (int i = 0; i < filelist3.length; i++) {
          // Log.d(TAG, "--2b");
          if (filelist3[i].getName().endsWith("mp3")) {
            // Log.d(TAG, "Number of MP3s");
            numberOfMp3++;
          }
        }
        // Log.d(TAG, "FILELIST LENGTH " + numberOfMp3);
        if (numberOfMp3 > 0) {
          int randomsongnumber = (int) (Math.random() * (filelist3.length));
          musicpath = filelist3[randomsongnumber].getAbsolutePath();
          File f = new File(musicpath);
          String artist = "";
          String song = "";
          try {
            MP3File mp3 = new MP3File(f);
            ID3v1 id3 = mp3.getID3v1Tag();
            artist = id3.getArtist();
            // Log.d(TAG, "----------->ARTIST:" + artist);
            song = id3.getSongTitle();
            // Log.d(TAG, "----------->SONG:" + song);
            Scrobbler.scrobble(artist, song);
          } catch (IOException e1) {
            e1.printStackTrace();
          } catch (TagException e1) {
            e1.printStackTrace();
          } catch (Exception ex) {
            // Log.e(TAG, "There has been an exception while extracting ID3 Tag Information from the
            // MP3");
          }
        }
      }
      try {
        mp = new MediaPlayer();
        if (numberOfMp3 == 0) {
          Logger.d(TAG, "DEFAULT FILE");
          mp = MediaPlayer.create(this, mediaarray[0]);
          // mp.setLooping(true);
          mp.setVolume(0.99f, 0.99f);
          mp.setOnCompletionListener(this);
          mp.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
          mp.setOnPreparedListener(this);
          mp.prepareAsync();
        } else {
          mp.setDataSource(musicpath);
          mp.setLooping(false);
          mp.setVolume(0.99f, 0.99f);
          Logger.d(TAG, "...");
          mp.setOnCompletionListener(this);
          mp.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
          Logger.d(TAG, "....");
          mp.setOnPreparedListener(this);
          Logger.d(TAG, ".....");
          mp.prepareAsync();
        }

      } catch (IllegalArgumentException e) {
        e.printStackTrace();
      } catch (IllegalStateException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
    } else {
      Logger.d(TAG, "not read or writeable...");
    }
  }