Beispiel #1
12
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {

    if (mPlayer == null) {

      mPlayer = new MediaPlayer();
      mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
      mPlayer.setOnPreparedListener(this);
      mPlayer.setOnCompletionListener(this);
      mPlayer.setOnSeekCompleteListener(this);

      try {
        mSong = pickNextSong();

        mPlayer.setDataSource(this, Uri.parse(mSongResource[mSong]));

      } catch (IOException e) {
        e.printStackTrace();

        mPlayer.release();
        mPlayer = null;
      }
    }

    if (mPlayer != null && !mIsPrepared) {
      mPlayer.prepareAsync();
      mPlayWhenPrepared = true;
    }

    return START_STICKY;
  }
  // playback
  public Playback(SurfaceView surfaceview, int playerMode) {
    mmediaplayer = new MediaPlayer();

    msurfaceholder = surfaceview.getHolder();
    msurfaceholder.addCallback(this);
    // msurfaceholder.setFixedSize(surfaceview.getWidth(),
    // surfaceview.getHeight());
    msurfaceholder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    mmediaplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mmediaplayer.setDisplay(msurfaceholder);

    mmediaplayer.setOnErrorListener(errListener);
    mmediaplayer.setOnPreparedListener(preListener);
    mmediaplayer.setOnCompletionListener(completeListener);
    mmediaplayer.setOnSeekCompleteListener(seekListener);

    mPlayStatus = VideoConst.PLAY_STATUS_UNKNOW;

    if (playerMode == VideoConst.PLAYER_MODE_MMP) {
      videopl = PlayList.getPlayList();
      mcurPath = videopl.getCurrentPath(Const.FILTER_VIDEO);
    }
    mplayerMode = playerMode;

    pb = this;
  }
Beispiel #3
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();
    }
  }
  @Override
  public void onCreate() {

    feedBackIntent = new Intent(BROADCAST_FEEDBACK);
    seekIntent = new Intent(BROADCAST_SEEK);

    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setOnCompletionListener(this);
    mediaPlayer.setOnErrorListener(this);
    mediaPlayer.setOnBufferingUpdateListener(this);
    mediaPlayer.setOnInfoListener(this);
    mediaPlayer.setOnSeekCompleteListener(this);
    mediaPlayer.setOnPreparedListener(this);
    mediaPlayer.reset();

    DropboxConnect dropConnect = new DropboxConnect(getApplicationContext());
    dropboxApi = dropConnect.getDropboxAPI();

    nowplayingData = SongSQLite.getmInstance(getApplicationContext());
    playingSongList = nowplayingData.getAllSong(SongSQLite.TABLE_NOWPLAYING, null);
    intCurrentSong = 0;

    if (playingSongList == null) playingSongList = new ArrayList<>(); // If Database is Emply

    intTotalSong = playingSongList.size();
    updateCurrentSong();

    initNotification();
    Log.d(">>>> THAI <<<<", "onCreat() Service");
  }
  public void onPrepared(MediaPlayer mp) {
    Log.i("", "prepared");
    mp.setLooping(true);
    // video size check (media is a video if size is defined, audio if not)
    // int h = mp.getVideoHeight();
    // int w = mp.getVideoWidth();
    mp.setOnBufferingUpdateListener(
        new OnBufferingUpdateListener() {
          @Override
          public void onBufferingUpdate(MediaPlayer mp, int percent) {
            Log.i(this.getClass().getName(), "percent: " + percent);
            progress.setProgress(percent);
          }
        });
    // onSeekCompletionListener declaration
    mp.setOnSeekCompleteListener(
        new OnSeekCompleteListener() {
          @Override
          public void onSeekComplete(MediaPlayer mp) {
            if (!mp.isPlaying()) {
              playMedia(null);
            }
          }
        });

    mp.setOnCompletionListener(null);

    readyToPlay = true;
    // int time = vv.getDuration();
    int time_elapsed = vv.getCurrentPosition();
    Log.i("time elapsed", " " + time_elapsed);
    progress.setProgress(time_elapsed);

    progress.setOnTouchListener(
        new OnTouchListener() {

          // enables changing of the current playback position
          @Override
          public boolean onTouch(View v, MotionEvent event) {
            ProgressBar pb = (ProgressBar) v;

            int newPosition = (int) (100 * event.getX() / pb.getWidth());
            if (newPosition > pb.getSecondaryProgress()) {
              newPosition = pb.getSecondaryProgress();
            }

            switch (event.getAction()) {
                // update position when finger is DOWN/MOVED/UP
              case MotionEvent.ACTION_DOWN:
              case MotionEvent.ACTION_MOVE:
              case MotionEvent.ACTION_UP:
                pb.setProgress(newPosition);
                vv.seekTo((int) newPosition * vv.getDuration() / 100);
                break;
            }
            return true;
          }
        });
  }
  public void openVideo(Uri uri) {
    if (uri == null || mSurfaceHolder == null || getContext() == null) {
      // not ready for playback just yet, will try again later
      if (mSurfaceHolder == null && uri != null) {
        mUri = uri;
      }
      return;
    }

    mUri = uri;
    mDuration = 0;

    // Idle 状态:当使用new()方法创建一个MediaPlayer对象或者调用了其reset()方法时,该MediaPlayer对象处于idle状态。
    // End 状态:通过release()方法可以进入End状态,只要MediaPlayer对象不再被使用,就应当尽快将其通过release()方法释放掉
    // Initialized 状态:这个状态比较简单,MediaPlayer调用setDataSource()方法就进入Initialized状态,表示此时要播放的文件已经设置好了。
    // Prepared
    // 状态:初始化完成之后还需要通过调用prepare()或prepareAsync()方法,这两个方法一个是同步的一个是异步的,只有进入Prepared状态,才表明MediaPlayer到目前为止都没有错误,可以进行文件播放。

    Exception exception = null;
    try {
      if (mMediaPlayer == null) {
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setOnPreparedListener(mPreparedListener);
        mMediaPlayer.setOnCompletionListener(mCompletionListener);
        mMediaPlayer.setOnErrorListener(mErrorListener);
        mMediaPlayer.setOnVideoSizeChangedListener(mVideoSizeChangedListener);
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setOnSeekCompleteListener(mSeekCompleteListener);
        mMediaPlayer.setOnInfoListener(mInfoListener);
        //			mMediaPlayer.setScreenOnWhilePlaying(true);
        //				mMediaPlayer.setVolume(mSystemVolumn, mSystemVolumn);
        mMediaPlayer.setDisplay(mSurfaceHolder);
      } else {
        mMediaPlayer.reset();
      }
      mMediaPlayer.setDataSource(getContext(), uri);

      //			if (mLooping)
      //				mMediaPlayer.setLooping(true);//循环播放
      mMediaPlayer.prepareAsync();
      // we don't set the target state here either, but preserve the
      // target state that was there before.
      mCurrentState = STATE_PREPARING;
    } catch (IOException ex) {
      exception = ex;
    } catch (IllegalArgumentException ex) {
      exception = ex;
    } catch (Exception ex) {
      exception = ex;
    }
    if (exception != null) {
      Logger.e(exception);
      mCurrentState = STATE_ERROR;
      if (mErrorListener != null)
        mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
    }
  }
  public AudioApi(MediaPlayer audioPlayer) {
    this.audioPlayer = audioPlayer;

    audioPlayer.setOnErrorListener(this);
    audioPlayer.setOnPreparedListener(this);
    audioPlayer.setOnCompletionListener(this);
    audioPlayer.setOnSeekCompleteListener(this);
    audioPlayer.setOnBufferingUpdateListener(this);
  }
Beispiel #8
0
 private void initPlayer() {
   mPlayer = new MediaPlayer();
   mPlayer.setAudioSessionId(mPlayer.getAudioSessionId());
   mPlayer.setOnErrorListener(this);
   mPlayer.setOnInfoListener(this);
   mPlayer.setOnPreparedListener(this);
   mPlayer.setOnBufferingUpdateListener(this);
   mPlayer.setOnSeekCompleteListener(this);
   mPlayer.setOnCompletionListener(this);
 }
Beispiel #9
0
 private void initplayer() {
   if (player == null) {
     player = new MediaPlayer();
     player.setOnPreparedListener(MediaPlayerListener);
     player.setOnVideoSizeChangedListener(MediaPlayerListener);
     player.setOnSeekCompleteListener(MediaPlayerListener);
     player.setOnInfoListener(MediaPlayerListener);
     player.setOnCompletionListener(MediaPlayerListener);
     player.setOnErrorListener(MediaPlayerListener);
     player.setOnBufferingUpdateListener(MediaPlayerListener);
   }
 }
  @Override
  public void onCreate() {
    super.onCreate();

    // Create MediaPlayer
    __mediaPlayer = new MediaPlayer();

    Log.i("AudioService", "Created the __mediaPlayer.");

    // When called OnCompletionListener().
    __mediaPlayer.setOnCompletionListener(
        new OnCompletionListener() {
          public void onCompletion(MediaPlayer arg0) {
            __state = 0;
          }
        });

    __mediaPlayer.setOnSeekCompleteListener(
        new OnSeekCompleteListener() {
          @Override
          public void onSeekComplete(MediaPlayer mediaPlayer) {
            Log.d(
                "VID_PLAYER",
                "Seek Complete. Current Position: " + mediaPlayer.getCurrentPosition());
            mediaPlayer.start();
          }
        });

    IntentFilter receiverFilter = new IntentFilter();
    receiverFilter.addAction(Intent.ACTION_POWER_CONNECTED);
    registerReceiver(__musicReceiver, receiverFilter);

    NotificationManager noficicationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    NotificationCompat.Builder builder =
        new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.smile)
            .setContentTitle("Playing the music.")
            .setContentText("NiceMusicApp");

    Intent intent = new Intent(this, com.web2korea.nicemusicapp.MusicListActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
    builder.setContentIntent(pendingIntent);
    Notification notification = builder.build();

    notification.flags = Notification.FLAG_ONLY_ALERT_ONCE;
    // notification.flags = Notification.FLAG_ONGOING_EVENT;
    notification.flags = Notification.FLAG_AUTO_CANCEL;

    noficicationManager.notify(NOTIFICATION_REMOVE, notification);
  }
  public AndroidMusic(AssetFileDescriptor assetDescriptor) {
    mediaPlayer = new MediaPlayer();
    try {
      mediaPlayer.setDataSource(
          assetDescriptor.getFileDescriptor(),
          assetDescriptor.getStartOffset(),
          assetDescriptor.getLength());
      mediaPlayer.prepare();
      isPrepared = true;
      mediaPlayer.setOnCompletionListener(this);
      mediaPlayer.setOnSeekCompleteListener(this);
      mediaPlayer.setOnPreparedListener(this);
      mediaPlayer.setOnVideoSizeChangedListener(this);

    } catch (Exception e) {
      throw new RuntimeException("Couldn't load music");
    }
  }
  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;
  }
  /**
   * 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();
    }
  }
  private void createPlayer(SurfaceHolder holder) {
    if (mMediaPlayer != null) {
      destroyPlayer(holder);
    }

    mMediaPlayer = new MediaPlayer();
    mHolder = holder;

    mVideoWidth = 0;
    mVideoHeight = 0;
    mVideoDurationSeconds = 0;

    try {
      mMediaPlayer.setDisplay(mHolder);
      mMediaPlayer.setDataSource(mUrl);

      mMediaPlayer.setScreenOnWhilePlaying(true);

      mMediaPlayer.setOnPreparedListener(this);
      mMediaPlayer.setOnVideoSizeChangedListener(this);
      mMediaPlayer.setOnCompletionListener(this);
      mMediaPlayer.setOnErrorListener(this);
      mMediaPlayer.setOnInfoListener(this);
      mMediaPlayer.setOnBufferingUpdateListener(this);
      mMediaPlayer.setOnSeekCompleteListener(this);

      mMediaPlayer.prepareAsync();
    } 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();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Beispiel #15
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Remove title bar
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    // Remove notification bar
    this.getWindow()
        .setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    // set content view AFTER ABOVE sequence (to avoid crash)
    setContentView(R.layout.player);

    decorView = getWindow().getDecorView();
    uiOption = getWindow().getDecorView().getSystemUiVisibility();

    surfaceView = (SurfaceView) this.findViewById(R.id.SurfaceView);
    surfaceHolder = surfaceView.getHolder();
    surfaceHolder.addCallback(this);

    mediaPlayer = new MediaPlayer();
    mediaPlayer.setOnCompletionListener(this);
    mediaPlayer.setOnErrorListener(this);
    mediaPlayer.setOnInfoListener(this);
    mediaPlayer.setOnPreparedListener(this);
    mediaPlayer.setOnSeekCompleteListener(this);
    mediaPlayer.setOnVideoSizeChangedListener(this);

    mMenuBar = (RelativeLayout) findViewById(R.id.menuBar);
    mMenuButton = (ImageView) findViewById(R.id.menuButton);
    mVideoList = (LinearLayout) findViewById(R.id.videoList);
    mTitle = (TextView) findViewById(R.id.MovieTitle);
    mMenuButton.setOnClickListener(this);
    mVideoList.setOnClickListener(this);

    /*
     * String filePath = Environment.getExternalStorageDirectory().getPath()
     * + "/Movies/Spanglish_H264_AAC_800x432.mp4";
     */

    // POINT: sdcard 의 동영상 파일 목록을 구하기
    String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
    File sdRoot = new File(sdPath);
    FileList(sdRoot);

    for (int i = 0; i < mFileList.size(); i++) {
      if ((mFileList.get(i).endsWith(".mp4")) || (mFileList.get(i).endsWith(".mkv"))) {
        Log.e("TAT", mFileList.get(i));
        mVideoFileList.add(mFileList.get(i));
      }
    }

    if (mVideoFileList.isEmpty()) {
      Toast.makeText(this, "재생할 파일이 없습니다.", 1).show();
    }

    for (int i = 0; i < mVideoFileList.size(); i++) {
      final String path = mVideoFileList.get(i);
      final String filename = path.substring(path.lastIndexOf("/") + 1);
      final TextView text = new TextView(this);
      text.setContentDescription(i + "");
      text.setSingleLine();
      text.setPadding(
          text.getPaddingLeft() + 10,
          text.getPaddingTop() + 10,
          text.getPaddingRight(),
          text.getPaddingBottom());
      text.setHeight(80);
      text.setText(filename);
      text.setOnClickListener(
          new OnClickListener() {
            @Override
            public void onClick(View v) {
              try {
                if (mediaPlayer.isPlaying()) mediaPlayer.stop();
                mediaPlayer.reset();
                mediaPlayer.setDataSource(path);
                mediaPlayer.prepare();
                idx = Integer.parseInt(text.getContentDescription().toString());
                mTitle.setText("[ " + filename + " ]");
              } catch (IllegalArgumentException e) {
                Log.v(LOGTAG, e.getMessage());
                finish();
              } catch (IllegalStateException e) {
                Log.v(LOGTAG, e.getMessage());
                finish();
              } catch (SecurityException e) {
                e.printStackTrace();
              } catch (IOException e) {
                e.printStackTrace();
              }
            }
          });
      mVideoList.addView(text);
    }

    /* TODO : intend를 통해 클릭한 동영상 path 넘겨주기 */
    // Intent intent = getIntent();
    // mmList = intent.getStringArrayListExtra("vList");

    String filePath = mVideoFileList.get(0);

    try {
      mediaPlayer.setDataSource(filePath);
      String filename = filePath.substring(filePath.lastIndexOf("/") + 1);
      mTitle.setText("[ " + filename + " ]");
    } catch (IllegalArgumentException e) {
      Log.v(LOGTAG, e.getMessage());
      finish();
    } catch (IllegalStateException e) {
      Log.v(LOGTAG, e.getMessage());
      finish();
    } catch (IOException e) {
      Log.v(LOGTAG, e.getMessage());
      finish();
    }

    controller =
        new MediaController(this) {
          @Override
          public void show() {
            super.show(0);
            mMenuBar.setVisibility(View.VISIBLE);
          }

          @Override
          public void hide() {
            super.hide();
            mMenuBar.setVisibility(View.INVISIBLE);
            ((ScrollView) mVideoList.getParent()).setVisibility(View.INVISIBLE);
          }
        };
    currentDisplay = getWindowManager().getDefaultDisplay();

    //
    // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    // uiOption |= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
  }