Пример #1
0
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null) {
      String action = intent.getAction();
      if ("play".equals(action)) {
        if (mMediaPlayer == null || !mMediaPlayer.isPlaying()) {
          play();
        }
      } else if ("pause".equals(action)) {
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
          pause();
        }
      } else if ("stop".equals(action)) {
        if (mMediaPlayer != null) {
          stop();
        }
      } else if ("next".equals(action)) {
        // 未実装
      } else if ("back".equals(action)) {
        // 未実装
      } else if ("playpause".equals(action)) {
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
          pause();
        } else {
          play();
        }
      }
    }

    return START_STICKY;
  }
Пример #2
0
 @Override
 public void onClick(View view) {
   switch (view.getId()) {
     case R.id.imgPlay:
       if (countClickButtonPlay % 2 == 0) {
         if (!mediaPlayer.isPlaying()) {
           seekBar.setMax((int) TimeUnit.MILLISECONDS.toSeconds(mediaPlayer.getDuration()));
           mediaPlayer.start();
           isPlaying = true;
           updateSeekBarThread = new Thread(updateSeekBar);
           updateSeekBarThread.start();
           imgPlay.setImageResource(R.drawable.ic_media_pause);
         }
       } else {
         if (mediaPlayer.isPlaying()) {
           mediaPlayer.pause();
           imgPlay.setImageResource(R.drawable.ic_media_play);
         }
       }
       countClickButtonPlay++;
       break;
     case R.id.imgSpeaker:
       AudioManager audioManager =
           (AudioManager) PlayActivity.this.getSystemService(Context.AUDIO_SERVICE);
       audioManager.adjustStreamVolume(
           AudioManager.STREAM_MUSIC, AudioManager.ADJUST_SAME, AudioManager.FLAG_SHOW_UI);
       break;
   }
 }
Пример #3
0
  public boolean onTouchEvent(MotionEvent touchevent) {
    switch (touchevent.getAction()) {
      case MotionEvent.ACTION_DOWN:
        {
          x1 = touchevent.getX();
          y1 = touchevent.getY();
          break;
        }
      case MotionEvent.ACTION_UP:
        {
          x2 = touchevent.getX();
          y2 = touchevent.getY();

          // if left to right swipe event on screen
          if (x1 < x2) {
            if (mpCheer.isPlaying()) mpCheer.stop();
            Intent i = new Intent(this, MainActivity.class);
            startActivity(i);
          }

          // if right to left swipe event on screen
          if (x1 > x2) {
            if (mpCheer.isPlaying()) mpCheer.stop();
            Intent i = new Intent(this, Shoes.class);
            startActivity(i);
          }

          break;
        }
    }
    return false;
  }
  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (mIsPrepared
        && keyCode != KeyEvent.KEYCODE_BACK
        && keyCode != KeyEvent.KEYCODE_VOLUME_UP
        && keyCode != KeyEvent.KEYCODE_VOLUME_DOWN
        && keyCode != KeyEvent.KEYCODE_MENU
        && keyCode != KeyEvent.KEYCODE_CALL
        && keyCode != KeyEvent.KEYCODE_ENDCALL
        && mMediaPlayer != null
        && mMediaController != null) {
      if (keyCode == KeyEvent.KEYCODE_HEADSETHOOK || keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE) {
        if (mMediaPlayer.isPlaying()) {
          pause();
          mMediaController.show();
        } else {
          start();
          mMediaController.hide();
        }
        return true;
      } else if (keyCode == KeyEvent.KEYCODE_MEDIA_STOP && mMediaPlayer.isPlaying()) {
        pause();
        mMediaController.show();
      } else {
        toggleMediaControlsVisiblity();
      }
    }

    return super.onKeyDown(keyCode, event);
  }
Пример #5
0
  public void musicControl(int _action) {

    switch (_action) {
      case REW:
        gotoPrevTrack();

        break;

      case PLAY:
        Log.i(TAG, "PLAY MUSIC");

        if (mPlayer != null && mIsPrepared) {
          showNotification();
          mPlayer.start();
        }

        break;

      case PAUSE:
        Log.i(TAG, "PAUSE MUSIC");

        if (mPlayer.isPlaying()) {
          mPlayer.pause();
          stopForeground(true);
        }
        break;

      case STOP:
        Log.i(TAG, "STOP MUSIC");

        if (mPlayer != null && mPlayer.isPlaying()) {

          stopForeground(true);

          mPlayer.stop();
          mIsPrepared = false;

          mPlayer.reset();
          try {
            mPlayer.setDataSource(this, Uri.parse(mSongResource[mSong]));
          } catch (IOException e) {
            e.printStackTrace();
          }

          mPlayer.prepareAsync();
          mPlayWhenPrepared = false;
        }

        break;

      case FF:
        Log.i(TAG, "FAST FORWARD MUSIC");

        stopAndSetToSong(mSong, true);

        break;
    }
  }
 private void seekTo(int time) {
   if (player.isPlaying()) {
     soundSystemHandler.removeCallbacks(progressChangeTracker);
   }
   playbackInfo.setTime(time);
   player.seekTo(playbackInfo.getTime());
   updateSoundSystemInfo();
   if (player.isPlaying()) {
     soundSystemHandler.postDelayed(progressChangeTracker, PROGRESS_UPDATE_DELAY);
   }
 }
Пример #7
0
  /** When user click button play on GUI. */
  public void playSong() {
    if (mPlayer.isPlaying()) {
      mPlayer.pause();
      sendBr(IM_PAUSE);

    } else {
      sendBr(IM_PLAYING);
      mPlayer.start();
    }
    Log.i(TAG, "isPlaying :" + mPlayer.isPlaying());
  }
Пример #8
0
  public void testRestartProjectWithSound() {
    String projectName = UiTestUtils.PROJECTNAME1;
    // creating sprites for project:
    Sprite firstSprite = new Sprite("sprite1");
    Script startScript = new StartScript(firstSprite);

    PlaySoundBrick playSoundBrick = new PlaySoundBrick(firstSprite);

    startScript.addBrick(playSoundBrick);

    firstSprite.addScript(startScript);

    ArrayList<Sprite> spriteList = new ArrayList<Sprite>();
    spriteList.add(firstSprite);
    Project project = UiTestUtils.createProject(projectName, spriteList, getActivity());

    File soundFile =
        UiTestUtils.saveFileToProject(
            projectName,
            "soundfile.mp3",
            at.tugraz.ist.catroid.uitest.R.raw.longsound,
            getInstrumentation().getContext(),
            UiTestUtils.FileTypes.SOUND);

    SoundInfo soundInfo = new SoundInfo();
    soundInfo.setSoundFileName(soundFile.getName());
    soundInfo.setTitle(soundFile.getName());
    playSoundBrick.setSoundInfo(soundInfo);

    firstSprite.getSoundList().add(soundInfo);

    storageHandler.saveProject(project);

    MediaPlayer mediaPlayer = SoundManager.getInstance().getMediaPlayer();
    UiTestUtils.clickOnActionBar(solo, R.id.menu_start);
    solo.waitForActivity(StageActivity.class.getSimpleName());
    solo.sleep(1000);
    assertTrue("Sound not playing.", mediaPlayer.isPlaying());
    int positionBeforeRestart = mediaPlayer.getCurrentPosition();
    solo.goBack();
    solo.sleep(500);
    assertFalse("Sound playing but should be paused.", mediaPlayer.isPlaying());
    solo.clickOnButton(getActivity().getString(R.string.restart_current_project));
    solo.sleep(300);
    @SuppressWarnings("unchecked")
    ArrayList<MediaPlayer> mediaPlayerArrayList =
        (ArrayList<MediaPlayer>)
            UiTestUtils.getPrivateField("mediaPlayers", SoundManager.getInstance());
    int positionAfterRestart = mediaPlayerArrayList.get(0).getCurrentPosition();
    assertTrue("Sound not playing after stage restart.", mediaPlayerArrayList.get(0).isPlaying());
    assertTrue("Sound did not play from start!", positionBeforeRestart > positionAfterRestart);
  }
Пример #9
0
  /**
   * Reconfigures MediaPlayer according to audio focus settings and starts/restarts it. This method
   * starts/restarts the MediaPlayer respecting the current audio focus state. So if we have focus,
   * it will play normally; if we don't have focus, it will either leave the MediaPlayer paused or
   * set it to a low volume, depending on what is allowed by the current focus settings. This method
   * assumes mPlayer != null, so if you are calling it, you have to do so from a context where you
   * are sure this is the case.
   */
  void configAndStartMediaPlayer() {
    if (mAudioFocus == AudioFocus.NoFocusNoDuck) {
      // If we don't have audio focus and can't duck, we have to pause, even if mState
      // is State.Playing. But we stay in the Playing state so that we know we have to resume
      // playback once we get the focus back.
      if (mPlayer.isPlaying()) mPlayer.pause();
      return;
    } else if (mAudioFocus == AudioFocus.NoFocusCanDuck)
      mPlayer.setVolume(DUCK_VOLUME, DUCK_VOLUME); // we'll be relatively quiet
    else mPlayer.setVolume(1.0f, 1.0f); // we can be loud

    if (!mPlayer.isPlaying()) mPlayer.start();
  }
Пример #10
0
 @Override
 public void onClick(View v) {
   switch (v.getId()) {
     case R.id.play:
       if (!mediaPlayer.isPlaying()) mediaPlayer.start();
       break;
     case R.id.pause:
       if (mediaPlayer.isPlaying()) mediaPlayer.pause();
       else if (!mediaPlayer.isPlaying()) mediaPlayer.start();
       break;
     case R.id.stop:
       if (mediaPlayer.isPlaying()) mediaPlayer.stop();
       break;
   }
 }
Пример #11
0
  @Override
  public void onPrepared(MediaPlayer mp) {

    if (isPrepare) {
      if (playType == PLAY_TYPE_LOD || playType == PLAY_TYPE_ONDEMAND) {
        // TODO 数据库操作 记忆续播
        MPConPlayManager cPm =
            MPConPlayUtils.findConnectionPlay(currentPosition, parentName, getChildName());
        if (cPm != null && cPm.getEpisodePos() == currentPosition && cPm.getPlayIndex() != 0) {
          mp.seekTo(cPm.getPlayIndex());
        }

        mHandler.sendEmptyMessage(SHOW_CONTROL_ANIMATION);
      }

      mp.start();
      isPrepare = false;

      if (mDialog != null && mDialog.isShowing()) {
        mDialog.dismiss();
      }
      // 判断是否是本地播放或在线点播
      if (playType == PLAY_TYPE_LOD || playType == PLAY_TYPE_ONDEMAND) {
        if (mp.isPlaying() && !mSeekBar.isPressed()) {

          mHandler.sendEmptyMessage(UPDATA_PLAY_TIME);
        }
      }

      mProgressBar.setVisibility(View.INVISIBLE);

      mPlayer.setScreenOnWhilePlaying(true);
    }
  }
Пример #12
0
 @Override
 public void onClick(View v) {
   switch (v.getId()) {
     case R.id.imgbtn_left:
       {
         if (isRecording == false) {
           if (isAudioPlaying == false) {
             RecordingNow(true);
           } else {
             // PlaySound(false, false, true,false);
           }
         } else {
           RecordingNow(false);
         }
         break;
       }
     case R.id.imgbtn_right:
       {
         if (isAudioPlaying == false) {
           // PlaySound(true, false, false,false);
         } else {
           if (mPlayer.isPlaying()) {
             // PlaySound(false, true, false,false);
           } else {
             // PlaySound(false, false, false, true);
           }
         }
         break;
       }
   }
 }
  @Override
  public void onClick(View v) {
    if (v.getId() == R.id.ButtonTestPlayPause) {
      /** ImageButton onClick event handler. Method which start/pause mediaplayer playing */
      try {
        mediaPlayer.setDataSource(
            "http://stream7.cache12.vcdn.vn/fsfsdfdsfdserwrwq3/df399b944be816f5fcf8d0671209dad5/55a0a05d/2015/05/15/6/6/66dd8254b28ea00774d136e251a40a98.mp3"); // setup song from http://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3 URL to mediaplayer data source
        mediaPlayer
            .prepare(); // you must call this method after setup the datasource in setDataSource
        // method. After calling prepare() the instance of MediaPlayer starts load
        // data from URL to internal buffer.
      } catch (Exception e) {
        e.printStackTrace();
      }

      mediaFileLengthInMilliseconds =
          mediaPlayer.getDuration(); // gets the song length in milliseconds from URL

      if (!mediaPlayer.isPlaying()) {
        mediaPlayer.start();
        buttonPlayPause.setImageResource(R.drawable.button_pause);
      } else {
        mediaPlayer.pause();
        buttonPlayPause.setImageResource(R.drawable.button_play);
      }

      primarySeekBarProgressUpdater();
    }
  }
Пример #14
0
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {

          super.onCallStateChanged(state, incomingNumber);
          Log.d("radio", " Got something with the phone : " + state);

          if (state != TelephonyManager.CALL_STATE_IDLE) {

            if (mediaPlayer.isPlaying()) {

              mediaPlayer.stop();
              try {
                mediaPlayer.prepareAsync();
              } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
              }
              wasPlaying = true;
            }
          } else if (wasPlaying) {

            mediaPlayer.start();
            wasPlaying = false;
          }
        }
 @Override
 public void dispose() {
   if (mediaPlayer.isPlaying()) {
     mediaPlayer.stop();
   }
   mediaPlayer.release();
 }
  public void onEventMainThread(PlayPauseEvent event) {
    Log.d(TAG, "onEventMainThread: PlayPauseEvent");

    if (!isStarted()) {
      Log.d(TAG, "The service has not been started yet.");
      postProcesses.add(
          new Runnable() {
            @Override
            public void run() {
              if (player.isPlaying()) {
                pauseTrack();
              } else {
                playTrack();
              }
            }
          });
      return;
    }

    if (player.isPlaying()) {
      pauseTrack();
    } else {
      if (state == STATE_PREPARED) {
        playTrack();
      } else {
        postProcesses.add(
            new Runnable() {
              @Override
              public void run() {
                playTrack();
              }
            });
      }
    }
  }
Пример #17
0
 /** Stops the currently playing music, and releases resources. */
 private void unload_Music() {
   if (Music != null) {
     if (Music.isPlaying()) Music.stop();
     Music.release();
     Music = null;
   }
 }
Пример #18
0
 @Override
 public void handleMessage(Message msg) {
   // TODO Auto-generated method stub
   super.handleMessage(msg);
   // Log.i("tvinfo", msg.what + "-" + msg.obj);
   if (msg.what == 1) {
     progress.setVisibility(View.VISIBLE);
     title.setText("开始播放 ...");
   }
   if (msg.what == 2) {
     title.setText("开始加载 ...");
   }
   if (msg.what == 3) {
     title.setText("开始播放 ...");
     play(prg);
   }
   if (msg.what == 4) {
     title.setText("加载失败 ...");
   }
   if (msg.what == 9) {
     show("获取", "正在获取播放列表,请稍后...");
   }
   if (msg.what == -100) {
     playmenu.setVisibility(View.GONE);
   }
   if (msg.what == 66) {
     if (player != null && player.isPlaying() && !isseek) {
       currtime.setText(Utils.longToString(player.getCurrentPosition()));
       playSeek.setProgress(player.getCurrentPosition() / 1000);
     }
   }
 }
Пример #19
0
 public void stop() {
   Log.v(TAG, "stop");
   if (mediaPlayer.isPlaying()) {
     stopMonitor.setIsRunning(false);
     mediaPlayer.stop();
   }
 }
Пример #20
0
  public void stop() {
    try {
      if (mp != null) {

        if (mp.isPlaying() || isPaused()) {
          if (DBG) {
            Log.d(LCAT, "audio is playing, stop()");
          }
          setState(STATE_STOPPING);
          mp.stop();
          setState(STATE_STOPPED);
          if (remote) {
            stopProgressTimer();
          }
          try {
            mp.prepare();
          } catch (IOException e) {
            Log.e(LCAT, "Error while preparing audio after stop(). Ignoring.");
          } catch (IllegalStateException e) {
            Log.w(LCAT, "Error while preparing audio after stop(). Ignoring.");
          }
        }

        if (isPaused()) {
          paused = false;
        }
      }
    } catch (Throwable t) {
      Log.e(LCAT, "Error : ", t);
    }
  }
Пример #21
0
 public void playPause() {
   if (!mp.isPlaying()) {
     play();
   } else {
     pause();
   }
 }
Пример #22
0
        @Override
        public boolean onInfo(MediaPlayer player, int whatInfo, int extra) {
          switch (whatInfo) {
            case MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING:
              break;

            case MediaPlayer.MEDIA_INFO_BUFFERING_START:
              if (player.isPlaying()) {
                Logger.LOGD(TAG, "resume to pause MEDIA_INFO_BUFFERING_START");
                needResume = true;
                if (!mLoading.isShowing()) mLoading.show();
              }
              break;
            case MediaPlayer.MEDIA_INFO_BUFFERING_END:
              if (needResume) {
                player.start();
                needResume = false;
                Logger.LOGD(TAG, "resume to play!!!! MEDIA_INFO_BUFFERING_END");
                mLoading.cancel();
              }
              break;
            default:
              Logger.LOGD(TAG, "what=" + whatInfo + ",extra=" + extra);
              break;
          }
          return false;
        }
Пример #23
0
 private void releaseMediaPlayer() {
   if (mMediaPlayer != null) {
     if (mMediaPlayer.isPlaying()) mMediaPlayer.stop();
     mMediaPlayer.release();
     mMediaPlayer = null;
   }
 }
Пример #24
0
 public void pause() {
   Log.v(TAG, "pause");
   if (mediaPlayer.isPlaying()) {
     stopMonitor.setIsRunning(false);
     mediaPlayer.pause();
   }
 }
 private static void startNotification() {
   Intent i = new Intent(context, SalatTimes.class);
   notification.setLatestEventInfo(
       context,
       context.getString(R.string.app_name),
       notification.tickerText,
       PendingIntent.getActivity(
           context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT));
   notification.contentIntent =
       PendingIntent.getBroadcast(
           context,
           0,
           new Intent(context, ClickNotificationReceiver.class),
           PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT);
   notification.deleteIntent =
       PendingIntent.getBroadcast(
           context,
           0,
           new Intent(context, ClearNotificationReceiver.class),
           PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT);
   ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE))
       .notify(1, notification);
   if (mediaPlayer == null || !mediaPlayer.isPlaying()) {
     try {
       Thread.sleep(CONSTANT.POST_NOTIFICATION_DELAY);
     } catch (Exception ex) {
       // Just trying to make sure the notification completes before we fall asleep again
     }
     WakeLock.release();
   }
 }
Пример #26
0
 // 服务开始的时候执行
 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {
   if (!player.isPlaying()) {
     player.start();
   }
   return START_STICKY;
 }
Пример #27
0
 public boolean isPlaying() {
   boolean result = false;
   if (mp != null) {
     result = mp.isPlaying();
   }
   return result;
 }
Пример #28
0
 public void play() {
   if (mMediaPlayer.isPlaying()) {
     mMediaPlayer.seekTo(0);
   } else {
     mMediaPlayer.start();
   }
 }
Пример #29
0
 public void play(int position) {
   if (mediaPlayer.isPlaying()) {
     mediaPlayer.stop();
   }
   currentPodcastInPlayer = position;
   play();
 }
 private void updateSoundSystemInfo() {
   playbackInfo.setStatus(
       player != null && player.isPlaying() ? PlaybackStatus.PLAYING : PlaybackStatus.PAUSED);
   playbackInfo.setTime(player != null ? player.getCurrentPosition() : 0);
   updateSoundSystemUI();
   mActivity.getSmartHouseController().updatePlaybackInfo(copyPlaybackInfo());
 }