@Override
  public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
    Surface s = new Surface(surfaceTexture);

    try {
      mMediaPlayer = new MediaPlayer();
      mMediaPlayer.setDataSource(mContext, mVideoUri);
      mMediaPlayer.setSurface(s);
      mMediaPlayer.prepare();
      mMediaPlayer.setOnBufferingUpdateListener(this);
      mMediaPlayer.setOnCompletionListener(this);
      mMediaPlayer.setOnPreparedListener(this);
      mMediaPlayer.setOnVideoSizeChangedListener(this);
      mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
      mMediaPlayer.seekTo(0);
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (SecurityException e) {
      e.printStackTrace();
    } catch (IllegalStateException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    /*
    if ( mMediaPlayer != null ) {
       mSeekBar.setProgress( 0 );
       mSeekBar.setMax( mMediaPlayer.getDuration() );
       mVideoTextureView.SetVideoSize( mMediaPlayer.getVideoWidth(), mMediaPlayer.getVideoHeight() );
    }

    */
  }
Exemplo n.º 2
0
  @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");
  }
Exemplo n.º 3
0
  private void playVideo() {
    doCleanUp();
    try {
      /*
       * Set path variable to progressive streamable mp4 or 3gpp
       * format URL. Http protocol should be used. Mediaplayer can only
       * play "progressive streamable contents" which basically means: 1.
       * the movie atom has to precede all the media data atoms. 2. The
       * clip has to be reasonably interleaved.
       */
      path = "http://www.androidbook.com/akc/filestorage/android/documentfiles/3389/movie.mp4";
      //            path = "http://forum.ea3w.com/coll_ea3w/attach/2008_10/12237832415.3gp";

      // Create a new media player and set the listeners
      mMediaPlayer = new MediaPlayer();
      mMediaPlayer.setDataSource(path);
      mMediaPlayer.setDisplay(holder);
      mMediaPlayer.prepare();
      mMediaPlayer.setOnBufferingUpdateListener(this);
      mMediaPlayer.setOnCompletionListener(this);
      mMediaPlayer.setOnPreparedListener(this);
      mMediaPlayer.setOnVideoSizeChangedListener(this);
      mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

    } catch (Exception e) {
      Log.e(TAG, "error: " + e.getMessage(), e);
    }
  }
Exemplo n.º 4
0
  private void openVideo() {
    if (mUri == null || mSurfaceHolder == null) {
      // not ready for playback just yet, will try again later
      return;
    }

    if (mMediaPlayer != null) {
      mMediaPlayer.reset();
      mMediaPlayer.release();
      mMediaPlayer = null;
    }
    try {
      mMediaPlayer = new MediaPlayer();
      mMediaPlayer.setOnPreparedListener(mPreparedListener);
      mIsPrepared = false;
      mMediaPlayer.setOnCompletionListener(mCompletionListener);
      mMediaPlayer.setOnErrorListener(mErrorListener);
      mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
      mCurrentBufferPercentage = 0;
      mMediaPlayer.setDataSource(mContext, mUri);
      mMediaPlayer.setDisplay(mSurfaceHolder);
      mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
      mMediaPlayer.setScreenOnWhilePlaying(true);
      mMediaPlayer.prepareAsync();
      attachMediaController();
    } catch (IOException ex) {
      Log.w("VideoView", "Unable to open content: " + mUri, ex);
      return;
    } catch (IllegalArgumentException ex) {
      Log.w("VideoView", "Unable to open content: " + mUri, ex);
      return;
    }
  }
  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;
          }
        });
  }
Exemplo n.º 6
0
  public AudioApi(MediaPlayer audioPlayer) {
    this.audioPlayer = audioPlayer;

    audioPlayer.setOnErrorListener(this);
    audioPlayer.setOnPreparedListener(this);
    audioPlayer.setOnCompletionListener(this);
    audioPlayer.setOnSeekCompleteListener(this);
    audioPlayer.setOnBufferingUpdateListener(this);
  }
Exemplo n.º 7
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);
 }
  private void openVideo() {
    if (mUri == null || mSurfaceHolder == null) {
      // not ready for playback just yet, will try again later
      return;
    }
    // Tell the music playback service to pause
    // TODO: these constants need to be published somewhere in the framework.
    Intent i = new Intent("com.android.music.musicservicecommand");
    i.putExtra("command", "pause");
    getContext().sendBroadcast(i);

    if (mMediaPlayer != null) {
      mMediaPlayer.reset();
      mMediaPlayer.release();
      mMediaPlayer = null;
    }
    try {
      mMediaPlayer = new MediaPlayer();
      mMediaPlayer.setOnPreparedListener(mPreparedListener);
      mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
      mIsPrepared = false;
      Log.v(TAG, "reset duration to -1 in openVideo");
      mDuration = -1;
      mMediaPlayer.setOnCompletionListener(mCompletionListener);
      mMediaPlayer.setOnErrorListener(mErrorListener);
      mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
      mCurrentBufferPercentage = 0;
      if (URLUtil.isAssetUrl(mUri.toString())) { // DST: 20090606 detect asset url
        AssetFileDescriptor afd = null;
        try {
          String path = mUri.toString().substring("file:///android_asset/".length());
          afd = getContext().getAssets().openFd(path);
          mMediaPlayer.setDataSource(
              afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        } finally {
          if (afd != null) {
            afd.close();
          }
        }
      } else {
        setDataSource();
      }
      mMediaPlayer.setDisplay(mSurfaceHolder);
      mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
      mMediaPlayer.setScreenOnWhilePlaying(true);
      mMediaPlayer.prepareAsync();
      attachMediaController();
    } catch (IOException ex) {
      Log.w(TAG, "Unable to open content: " + mUri, ex);
      return;
    } catch (IllegalArgumentException ex) {
      Log.w(TAG, "Unable to open content: " + mUri, ex);
      return;
    }
  }
  /** This method initialise all the views in project */
  private void initView() {
    buttonPlayPause = (ImageButton) findViewById(R.id.ButtonTestPlayPause);
    buttonPlayPause.setOnClickListener(this);

    seekBarProgress = (SeekBar) findViewById(R.id.SeekBarTestPlay);
    // seekBarProgress.setMax(99); // It means 100% .0-99
    seekBarProgress.setOnTouchListener(this);
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setOnBufferingUpdateListener(this);
    mediaPlayer.setOnCompletionListener(this);
  }
Exemplo n.º 10
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);
   }
 }
Exemplo n.º 11
0
 public void onPrepared(MediaPlayer mPlayer) {
   if (isPlaying) {
     mPlayer.setOnCompletionListener(this);
     mPlayer.setOnBufferingUpdateListener(
         new OnBufferingUpdateListener() {
           public void onBufferingUpdate(MediaPlayer mPlayer, int percent) {
             /* TODO: call back, e.g. update outer progress bar */
             Log.d("AudioOnBufferingUpdate", "percent: " + percent);
           }
         });
     mPlayer.start();
   }
 }
Exemplo n.º 12
0
  private void openVideo() {
    if (mUri == null || mSurfaceHolder == null) {
      // not ready for playback just yet, will try again later
      return;
    }
    // Tell the music playback service to pause
    // TODO: these constants need to be published somewhere in the framework.
    Intent i = new Intent("com.android.music.musicservicecommand");
    i.putExtra("command", "pause");
    mContext.sendBroadcast(i);

    // we shouldn't clear the target state, because somebody might have
    // called start() previously
    release(false);
    try {
      mMediaPlayer = new MediaPlayer();
      if (mAudioSession != 0) {
        mMediaPlayer.setAudioSessionId(mAudioSession);
      } else {
        mAudioSession = mMediaPlayer.getAudioSessionId();
      }
      mMediaPlayer.setOnPreparedListener(mPreparedListener);
      mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
      mMediaPlayer.setOnCompletionListener(mCompletionListener);
      mMediaPlayer.setOnErrorListener(mErrorListener);
      mMediaPlayer.setOnInfoListener(mOnInfoListener);
      mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
      mCurrentBufferPercentage = 0;
      mMediaPlayer.setDataSource(mContext, mUri, mHeaders);
      mMediaPlayer.setDisplay(mSurfaceHolder);
      mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
      mMediaPlayer.setScreenOnWhilePlaying(true);
      mMediaPlayer.prepareAsync();
      // we don't set the target state here either, but preserve the
      // target state that was there before.
      mCurrentState = STATE_PREPARING;
      attachMediaController();
    } catch (IOException ex) {
      Log.w(TAG, "Unable to open content: " + mUri, ex);
      mCurrentState = STATE_ERROR;
      mTargetState = STATE_ERROR;
      mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
      return;
    } catch (IllegalArgumentException ex) {
      Log.w(TAG, "Unable to open content: " + mUri, ex);
      mCurrentState = STATE_ERROR;
      mTargetState = STATE_ERROR;
      mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
      return;
    }
  }
Exemplo n.º 13
0
  protected void initialize() throws IOException {
    try {
      mp = new MediaPlayer();
      String url = TiConvert.toString(proxy.getProperty(TiC.PROPERTY_URL));
      if (URLUtil.isAssetUrl(url)) {
        Context context = proxy.getTiContext().getTiApp();
        String path = url.substring(TiConvert.ASSET_URL.length());
        AssetFileDescriptor afd = null;
        try {
          afd = context.getAssets().openFd(path);
          // Why mp.setDataSource(afd) doesn't work is a problem for another day.
          // http://groups.google.com/group/android-developers/browse_thread/thread/225c4c150be92416
          mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        } catch (IOException e) {
          Log.e(LCAT, "Error setting file descriptor: ", e);
        } finally {
          if (afd != null) {
            afd.close();
          }
        }
      } else {
        Uri uri = Uri.parse(url);
        if (uri.getScheme().equals(TiC.PROPERTY_FILE)) {
          mp.setDataSource(uri.getPath());
        } else {
          remote = true;
          mp.setDataSource(url);
        }
      }

      mp.setLooping(looping);
      mp.setOnCompletionListener(this);
      mp.setOnErrorListener(this);
      mp.setOnInfoListener(this);
      mp.setOnBufferingUpdateListener(this);

      mp.prepare(); // Probably need to allow for Async
      setState(STATE_INITIALIZED);

      setVolume(volume);
      if (proxy.hasProperty(TiC.PROPERTY_TIME)) {
        setTime(TiConvert.toInt(proxy.getProperty(TiC.PROPERTY_TIME)));
      }
    } catch (Throwable t) {
      Log.w(LCAT, "Issue while initializing : ", t);
      release();
      setState(STATE_STOPPED);
    }
  }
Exemplo n.º 14
0
 public void openVideo() {
   mediaPlayer = new MediaPlayer();
   try {
     mediaPlayer.reset();
     mediaPlayer.setDisplay(surfaceHolder);
     mediaPlayer.setAudioStreamType(3);
     mediaPlayer.setDataSource(videoUrl);
     mediaPlayer.prepareAsync();
     mediaPlayer.setOnPreparedListener(this);
     mediaPlayer.setOnBufferingUpdateListener(this);
     mediaPlayer.setOnCompletionListener(this);
   } catch (Exception e) {
     while (true) Log.e(TAG, e.getMessage());
   }
 }
  private void playVideo(Integer Media) {
    doCleanUp();
    try {

      /*
               * TODO: Set path variable to progressive streamable mp4 or
               * 3gpp format URL. Http protocol should be used.
               * Mediaplayer can only play "progressive streamable
               * contents" which basically means:    }

      private void playVideo(Integer Media) {
          doCleanUp();
          try {

              /*
               * TODO: Set path variable to progressive streamable mp4 or
               * 3gpp format URL. Http protocol should be used.
               * Mediaplayer can only play "progressive streamable
               * contents" which basically means: 1. the movie atom has to
               * precede all the media data atoms. 2. The clip has to be
               * reasonably interleaved.
               *
               */
      if (path == "") {
        // Tell the user to provide a media file URL.
        Toast.makeText(
                MediaPlayerVideoActivity.this,
                "Please edit MediaPlayerDemo_Video Activity,"
                    + " and set the path variable to your media file URL.",
                Toast.LENGTH_LONG)
            .show();
      }

      // Create a new media player and set the listeners
      mMediaPlayer = new MediaPlayer();
      mMediaPlayer.setDataSource(path);
      mMediaPlayer.setDisplay(holder);
      mMediaPlayer.prepare();
      mMediaPlayer.setOnBufferingUpdateListener(this);
      mMediaPlayer.setOnCompletionListener(this);
      mMediaPlayer.setOnPreparedListener(this);
      mMediaPlayer.setOnVideoSizeChangedListener(this);
      mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

    } catch (Exception e) {
      Log.e(TAG, "error: " + e.getMessage(), e);
    }
  }
  public void setupVideoTexture() {

    vmaterial = new VideoMaterial();
    vt = mTextureManager.addVideoTexture();
    int textureid = vt.getTextureId();

    mTexture = new SurfaceTexture(textureid);
    mMediaPlayer = new MediaPlayer();
    mMediaPlayer.setOnPreparedListener(this);
    mMediaPlayer.setOnBufferingUpdateListener(this);
    mMediaPlayer.setOnCompletionListener(this);
    mMediaPlayer.setOnErrorListener(this);
    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mMediaPlayer.setSurface(new Surface(mTexture));
    mMediaPlayer.setLooping(true);
  }
Exemplo n.º 17
0
  private void openVideo() {
    if (mUri == null || mSurfaceHolder == null) {
      // not ready for playback just yet, will try again later
      return;
    }

    // we shouldn't clear the target state, because somebody might have
    // called start() previously
    release(false);
    try {
      mMediaPlayer = new MediaPlayer();
      mMediaPlayer.setOnPreparedListener(mPreparedListener);
      mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
      mDuration = -1;
      mMediaPlayer.setOnCompletionListener(mCompletionListener);
      mMediaPlayer.setOnErrorListener(mErrorListener);
      mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
      mCurrentBufferPercentage = 0;
      mMediaPlayer.setDataSource(getContext(), mUri, mHeaders);
      mMediaPlayer.setDisplay(mSurfaceHolder);
      mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
      mMediaPlayer.setScreenOnWhilePlaying(true);
      mMediaPlayer.prepareAsync();
      // we don't set the target state here either, but preserve the
      // target state that was there before.
      mCurrentState = STATE_PREPARING;
      attachMediaController();
    } catch (IOException ex) {
      Log.w(TAG, "Unable to open content: " + mUri, ex);
      mCurrentState = STATE_ERROR;
      mTargetState = STATE_ERROR;
      mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
      return;
    } catch (IllegalArgumentException ex) {
      Log.w(TAG, "Unable to open content: " + mUri, ex);
      mCurrentState = STATE_ERROR;
      mTargetState = STATE_ERROR;
      mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
      return;
    } catch (IllegalStateException ex) {
      Log.w(TAG, "Unable to open content: " + mUri, ex);
      mCurrentState = STATE_ERROR;
      mTargetState = STATE_ERROR;
      mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
      return;
    }
  }
Exemplo n.º 18
0
  private void openVideo() {
    /*
     * if (mUri == null || mSurfaceHolder == null) { // not ready for
     * playback just yet, will try again later return; }
     */
    if (mInputStream == null || mSurfaceHolder == null) {
      return;
    }
    // Tell the music playback service to pause
    // TODO: these constants need to be published somewhere in the
    // framework.
    Intent i = new Intent("com.android.music.musicservicecommand");
    i.putExtra("command", "pause");
    mContext.sendBroadcast(i);

    if (mMediaPlayer != null) {
      mMediaPlayer.reset();
      mMediaPlayer.release();
      mMediaPlayer = null;
    }
    try {
      mMediaPlayer = new MediaPlayer();
      mMediaPlayer.setOnPreparedListener(mPreparedListener);
      mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
      mIsPrepared = false;
      Log.v(TAG, "reset duration to -1 in openVideo");
      mDuration = -1;
      mMediaPlayer.setOnCompletionListener(mCompletionListener);
      mMediaPlayer.setOnErrorListener(mErrorListener);
      mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
      mCurrentBufferPercentage = 0;
      // mMediaPlayer.setDataSource(mContext, mUri);
      mMediaPlayer.setDataSource(mInputStream.getFD());
      mMediaPlayer.setDisplay(mSurfaceHolder);
      mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
      mMediaPlayer.setScreenOnWhilePlaying(true);
      mMediaPlayer.prepareAsync();
      attachMediaController();
    } catch (IOException ex) {
      Log.w(TAG, "Unable to open content: " + mInputStream, ex);
      return;
    } catch (IllegalArgumentException ex) {
      Log.w(TAG, "Unable to open content: " + mInputStream, ex);
      return;
    }
  }
Exemplo n.º 19
0
  public void release() {
    try {
      if (mp != null) {

        mp.setOnCompletionListener(null);
        mp.setOnErrorListener(null);
        mp.setOnBufferingUpdateListener(null);
        mp.setOnInfoListener(null);

        mp.release();
        mp = null;
        if (DBG) {
          Log.d(LCAT, "Native resources released.");
        }
        remote = false;
      }
    } catch (Throwable t) {
      Log.w(LCAT, "Issue while releasing : ", t);
    }
  }
  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();
    }
  }
Exemplo n.º 21
0
    public void surfaceCreated(SurfaceHolder holder) {
      Log.d(TAG, "surfaceCreated called");

      // TODO: Holy hack batman. Fix this asap.
      ArrayList<String> videos = ((PlaybackActivity) getActivity()).getVideos();
      String url = getId() == R.id.video_1_fragment ? videos.get(0) : videos.get(1);

      try {
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setDataSource(this.getActivity(), Uri.fromFile(new File(url)));
        mMediaPlayer.setDisplay(mSurfaceHolder);
        mMediaPlayer.prepare();
        mMediaPlayer.setOnBufferingUpdateListener(this);
        mMediaPlayer.setOnCompletionListener(this);
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.setOnVideoSizeChangedListener(this);
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setLooping(true);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
Exemplo n.º 22
0
  private void openVideo() {
    if ((mFd == null && mUri == null) || mSurfaceHolder == null) {
      // not ready for playback just yet, will try again later
      return;
    }
    // Tell the music playback service to pause
    // TODO: these constants need to be published somewhere in the framework.
    Intent i = new Intent("com.android.music.musicservicecommand");
    i.putExtra("command", "pause");
    mContext.sendBroadcast(i);

    // we shouldn't clear the target state, because somebody might have
    // called start() previously
    release(false);
    try {
      mMediaPlayer = new MediaPlayer();
      // TODO: create SubtitleController in MediaPlayer, but we need
      // a context for the subtitle renderers
      final Context context = getContext();
      // final SubtitleController controller = new SubtitleController(context,
      // mMediaPlayer.getMediaTimeProvider(), mMediaPlayer);
      // controller.registerRenderer(new WebVttRenderer(context));
      // mMediaPlayer.setSubtitleAnchor(controller, this);

      if (mAudioSession != 0) {
        mMediaPlayer.setAudioSessionId(mAudioSession);
      } else {
        mAudioSession = mMediaPlayer.getAudioSessionId();
      }
      mMediaPlayer.setOnPreparedListener(mPreparedListener);
      mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
      mMediaPlayer.setOnCompletionListener(mCompletionListener);
      mMediaPlayer.setOnErrorListener(mErrorListener);
      mMediaPlayer.setOnInfoListener(mInfoListener);
      mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
      mCurrentBufferPercentage = 0;

      if (mUri != null) {
        mMediaPlayer.setDataSource(mContext, mUri, mHeaders);
      } else {
        mMediaPlayer.setDataSource(mFd);
      }

      mMediaPlayer.setDisplay(mSurfaceHolder);
      mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
      mMediaPlayer.setScreenOnWhilePlaying(true);
      mMediaPlayer.prepareAsync();

      /*   for (Pair<InputStream, MediaFormat> pending: mPendingSubtitleTracks) {
          try {
              mMediaPlayer.addSubtitleSource(pending.first, pending.second);
          } catch (IllegalStateException e) {
              mInfoListener.onInfo(
                      mMediaPlayer, MediaPlayer.MEDIA_INFO_UNSUPPORTED_SUBTITLE, 0);
          }
      }*/

      // we don't set the target state here either, but preserve the
      // target state that was there before.
      mCurrentState = STATE_PREPARING;
      attachMediaController();
    } catch (IOException ex) {
      Log.w(TAG, "Unable to open content: ", ex);
      mCurrentState = STATE_ERROR;
      mTargetState = STATE_ERROR;
      mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
      return;
    } catch (IllegalArgumentException ex) {
      Log.w(TAG, "Unable to open content: ", ex);
      mCurrentState = STATE_ERROR;
      mTargetState = STATE_ERROR;
      mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
      return;
    } finally {
      mPendingSubtitleTracks.clear();
    }
  }
Exemplo n.º 23
0
 public MusicPlayer() {
   player = new MediaPlayer();
   player.setAudioStreamType(AudioManager.STREAM_MUSIC);
   player.setOnBufferingUpdateListener(this);
   player.setOnPreparedListener(this);
 }
Exemplo n.º 24
0
  public void run() {
    synchronized (this.lock) {
      if (player == null) {
        player = new android.media.MediaPlayer();
      }
    }
    try {
      player.setOnCompletionListener(this);
      player.setOnErrorListener(this);
      player.setOnBufferingUpdateListener(this);

      synchronized (this.lock) {
        while (fileName == null && (this.status == PREPARED || this.status == PLAYING)) {
          this.lock.wait(250);
        }
      }
      if (fileName == null) {
        synchronized (this.lock) {
          this.status = EXIT;
        }
      } else {
        setDataSource(fileName, loop);
      }
      synchronized (this.lock) {
        while (this.status == PREPARED) {
          this.lock.wait();
        }
      }

      int currentStatus = 0;
      synchronized (this.lock) {
        currentStatus = this.status;
      }

      if (currentStatus == PLAYING) {
        player.start();
      }

      synchronized (this.lock) {
        this.started = true;

        while (this.status == PLAYING) {
          if (!this.done) {
            int duration = player.getDuration();
            int position = player.getCurrentPosition();
            if (duration > 0 && position + 10000 > duration) {
              this.done = true;
              this.schedule(duration, position);
            }
          }
          this.lock.wait(3000);
        }
        this.started = false;
      }

      player.stop();
      player.release();
      synchronized (this.lock) {
        player = null;
      }

    } catch (Exception e) {
    }
    synchronized (this.lock) {
      this.status = EXIT;
    }
    callback();
  }
  /** Loads a movie from a file in the assets folder */
  @SuppressLint("NewApi")
  public boolean load(
      String filename,
      MEDIA_TYPE requestedType,
      boolean playOnTextureImmediately,
      int seekPosition) {
    // If the client requests that we should be able to play ON_TEXTURE,
    // then we need to create a MediaPlayer:

    boolean canBeOnTexture = false;
    boolean canBeFullscreen = false;

    boolean result = false;
    mMediaPlayerLock.lock();
    mSurfaceTextureLock.lock();

    // If the media has already been loaded then exit.
    // The client must first call unload() before calling load again:
    if ((mCurrentState == MEDIA_STATE.READY) || (mMediaPlayer != null)) {
      DebugLog.LOGD("Already loaded");
    } else {
      if (((requestedType == MEDIA_TYPE.ON_TEXTURE)
              || // If the client requests on texture only
              (requestedType == MEDIA_TYPE.ON_TEXTURE_FULLSCREEN))
          && // or on texture with full screen
          (Build.VERSION.SDK_INT
              >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)) // and this is an ICS device
      {
        if (mSurfaceTexture == null) {
          DebugLog.LOGD("Can't load file to ON_TEXTURE because the Surface Texture is not ready");
        } else {
          try {
            mMediaPlayer = new MediaPlayer();

            try {
              // This example shows how to load the movie from the assets folder of the app
              // However, if you would like to load the movie from the sdcard or from a network
              // location
              // simply comment the three lines below
              //	                            AssetFileDescriptor afd =
              // mParentActivity.getAssets().openFd(filename);
              //
              // mMediaPlayer.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
              //	                            afd.close();

              File file = new File(VideoPlayback.sdCardDir, filename);
              fileCheck = file;
              if (file.exists()) {
                mMediaPlayer.setDataSource(VideoPlayback.sdCardDir + "/" + filename);

                // Variavel global que sera usada para deletar o video
                // caso caia no ErrorListener, pois significa que
                // ela esta corrompida.

                fileCheck = file;
                mMediaPlayer.prepareAsync();
                mMediaPlayer.setOnPreparedListener(this);
                mMediaPlayer.setOnBufferingUpdateListener(this);
                mMediaPlayer.setOnCompletionListener(this);
                mMediaPlayer.setOnErrorListener(this);
                mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mMediaPlayer.setSurface(new Surface(mSurfaceTexture));
                canBeOnTexture = true;
                mShouldPlayImmediately = playOnTextureImmediately;
              }

              mCurrentState = MEDIA_STATE.READY;

            } catch (Exception e) {
              // Se cair aqui, provavelmente o arquivo esta corrompido
              // entao deletamos o arquivo, e ele � baixado novamente
              fileCheck.delete();
              mCurrentState = MEDIA_STATE.READY;
            }

          } catch (Exception e) {
            DebugLog.LOGE("Error while creating the MediaPlayer: " + e.toString());

            mCurrentState = MEDIA_STATE.ERROR;
            mMediaPlayerLock.unlock();
            mSurfaceTextureLock.unlock();
            return false;
          }
        }
      }
      // If it's not an ICE CREAM SANDWICH device at least
      else {
        try {
          // We need to verify that the file exists
          //                        AssetFileDescriptor afd =
          // mParentActivity.getAssets().openFd(filename);
          //                        afd.close();

          File file = new File(VideoPlayback.sdCardDir, filename);
          fileCheck = file;
          //                        if (!file.exists()) {
          mCurrentState = MEDIA_STATE.READY;
          mVideoType = MEDIA_TYPE.FULLSCREEN;
          //                        }

        } catch (Exception e) {
          DebugLog.LOGD("File does not exist");
          mCurrentState = MEDIA_STATE.ERROR;
          mMediaPlayerLock.unlock();
          mSurfaceTextureLock.unlock();
          return false;
        }
      }

      // If the client requests that we should be able to play FULLSCREEN
      // then we need to create a FullscreenPlaybackActivity
      if ((requestedType == MEDIA_TYPE.FULLSCREEN)
          || (requestedType == MEDIA_TYPE.ON_TEXTURE_FULLSCREEN)) {
        mPlayerHelperActivityIntent = new Intent(mParentActivity, FullscreenPlayback.class);
        mPlayerHelperActivityIntent.setAction(android.content.Intent.ACTION_VIEW);
        canBeFullscreen = true;
      }

      // We store the parameters for further use
      mMovieName = filename;
      mSeekPosition = seekPosition;

      if (canBeFullscreen && canBeOnTexture) mVideoType = MEDIA_TYPE.ON_TEXTURE_FULLSCREEN;
      else if (canBeFullscreen) {
        mVideoType = MEDIA_TYPE.FULLSCREEN;
        mCurrentState = MEDIA_STATE.READY;
      } // If it is pure fullscreen then we're ready otherwise we let the MediaPlayer load first
      else if (canBeOnTexture) mVideoType = MEDIA_TYPE.ON_TEXTURE;
      else mVideoType = MEDIA_TYPE.UNKNOWN;

      result = true;
    }

    mSurfaceTextureLock.unlock();
    mMediaPlayerLock.unlock();

    return result;
  }
Exemplo n.º 26
0
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.rutaaudio);

    tv1 = (TextView) findViewById(R.id.textView1);
    tv2 = (TextView) findViewById(R.id.textView2);
    tv4 = (TextView) findViewById(R.id.textView4);
    imbPlay = (Button) findViewById(R.id.button3);
    sigPaso = (Button) findViewById(R.id.Button01);
    volver = (Button) findViewById(R.id.button1);

    seekBarProgress = (SeekBar) findViewById(R.id.seekBar1);
    seekBarProgress.setMax(99);
    seekBarProgress.setOnTouchListener(this);

    vPaso = "P1";
    // tv4.setText("Paso:"+NPASO+" de "+ sTOTALPASOS);

    mediaPlayer = new MediaPlayer();
    mediaPlayer.setOnBufferingUpdateListener(this);
    mediaPlayer.setOnCompletionListener(this);

    extras = getIntent().getExtras();
    canal = extras.getString("canal");
    codigo = extras.getInt("cod");
    concepto = extras.getString("origen");
    codruta = extras.getString("codigoruta");
    codqr = extras.getString("scodqr");
    destino = extras.getString("destino");
    qrdestino = extras.getString("qrdestino");
    // Toast.makeText(getBaseContext(), String.valueOf(codigo).toString(),
    // Toast.LENGTH_LONG).show();

    if (codigo == 4) {
      txtyaudio = false;
      canal = getResources().getString(R.string.audesp);
    } else if (codigo == 5) {
      txtyaudio = false;
      canal = getResources().getString(R.string.auding);
    } else if (codigo == 6) {
      txtyaudio = true;
      canal = getResources().getString(R.string.audesp);
    } else if (codigo == 7) {
      txtyaudio = true;
      canal = getResources().getString(R.string.auding);
    }
    if (codqr.startsWith("QR")) {
      codqr = codqr.replace(" ", "");
      String tmp = codqr.replace("QR", "");

      ene = Integer.parseInt(tmp);
    } else {
      codqr = codqr.replace(" ", "");
      String tmp = codqr.replace("QR", "");
      ene = Integer.parseInt(tmp);
    }

    // ********** Eleccion de tabla RUTAS según edificio *************
    if (ene < 1500) {
      queTabla = getResources().getString(R.string.tabla_etsiitpasos);
    } else if (ene >= 1500) {
      queTabla = getResources().getString(R.string.tabla_ftipasos);
    }
    codruta = codruta.trim();

    tv2.setText(concepto + "\n" + destino);

    if (codigo >= 6 && codigo <= 7) {
      // new ConsultaExtra(getApplicationContext()).execute(KEY_121);
      new ConsultaExtra().execute("Inicio");
    }
    new RutaAudio().execute("Inicio");

    imbPlay.setOnClickListener(this);

    volver.setOnClickListener(
        new OnClickListener() {
          @Override
          public void onClick(View v) {
            Intent i = new Intent(RutasAudio.this, CapturaQRAudio.class);
            i.putExtra("cod", codigo);
            i.putExtra("sconcepto", destino);
            i.putExtra("scodqr", qrdestino);
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(i);
          }
        });
    sigPaso.setOnClickListener(
        new OnClickListener() {
          @Override
          public void onClick(View v) {
            // NPASO += 1;
            // TODO Auto-generated method stub
            /*if (NPASO == 0)
            {
            	NPASO += 1;
            	vPaso = "P1";
            	tv2.setText(vPaso);
            	new MyTask().execute(KEY_121);
            }
            else*/
            if (NPASO == TOTALPASOS - 1) {
              Toast.makeText(getBaseContext(), "Último paso", Toast.LENGTH_SHORT).show();
            }

            if (NPASO == 1) {
              NPASO += 1;
              vPaso = "P2";
            } else if (NPASO == 2) {
              NPASO += 1;
              vPaso = "P3";
            } else if (NPASO == 3) {
              NPASO += 1;
              vPaso = "P4";
            } else if (NPASO == 4) {
              NPASO += 1;
              vPaso = "P5";
            } else if (NPASO == 5) {
              NPASO += 1;
              vPaso = "P6";
            } else if (NPASO == 6) {
              NPASO += 1;
              vPaso = "P7";
            }
            if (NPASO > cnp) {
              NPASO = 1;
              vPaso = "P1";
            }
          }
        });
  } // Fin de onCreate
Exemplo n.º 27
0
  // 创建播放器
  private void initPlayer() {
    reset();
    // 创建播放器
    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

    mMediaPlayer.setOnPreparedListener(
        new OnPreparedListener() {

          @Override
          public void onPrepared(MediaPlayer mp) {
            // mp.start();
            try {
              if (onPreparedListener != null) {
                onPreparedListener.onPrepared(mp);
              }
            } catch (IllegalStateException e) {
              LogManager.printStackTrace(e);
            } catch (Exception e) {
              LogManager.printStackTrace(e);
            }
          }
        });

    mMediaPlayer.setOnCompletionListener(
        new OnCompletionListener() {

          @Override
          public void onCompletion(MediaPlayer mp) {
            try {
              if (onCompletionListener != null) {
                LogManager.i(TAG, "OnCompletionListener  ----play completion");
                onCompletionListener.onCompletion(mp);
              }
            } catch (IllegalArgumentException e) {
              LogManager.printStackTrace(e, "MediaPlayerService", "onCompletion");
            } catch (IllegalStateException e) {
              LogManager.printStackTrace(e, "MediaPlayerService", "onCompletion");
            } catch (Exception e) {
              LogManager.printStackTrace(e);
            }
          }
        });

    mMediaPlayer.setOnErrorListener(
        new OnErrorListener() {

          @Override
          public boolean onError(MediaPlayer mp, int what, int extra) {

            LogManager.e(TAG, " on Error " + what + "  " + extra);
            // 无法复用播放器
            hasReady = false;
            try {
              if (onErrorListener != null) {
                return onErrorListener.onError(mp, what, extra);
              }
            } catch (IllegalStateException e) {
              LogManager.printStackTrace(e);
            } catch (Exception e) {
              LogManager.printStackTrace(e);
            }
            return true;
          }
        });

    mMediaPlayer.setOnInfoListener(
        new OnInfoListener() {

          @Override
          public boolean onInfo(MediaPlayer mp, int what, int extra) {
            LogManager.d(TAG, "what:" + what + ",extra:" + extra);
            switch (what) {
              case 702: // buffer结束缓冲 -> 音乐恢复播放
                isBufferingCauseStop = false;
                break;
              case 703: // buffer不足造成 -> 音乐暂停播放
                isBufferingCauseStop = true;
                break;
              case 701: // buffer开始缓冲 -> buffer不足时发生
                break;
              default:
            }
            return false;
          }
        });

    mMediaPlayer.setOnBufferingUpdateListener(
        new OnBufferingUpdateListener() {

          @Override
          public void onBufferingUpdate(MediaPlayer mp, int newBufferPercentage) {

            if (mBaseContext.getPrefBoolean(KeyList.PKEY_CUREENT_MUSIC_IS_DLAN, false)) {
              return;
            }

            bufferPercentage = newBufferPercentage;
            /** 暂时未查到 -2147483648 是什么状态,但此状态下歌曲是在缓冲的 */
            LogManager.i(TAG, " buffer percent:" + newBufferPercentage + "%");

            if (bufferPercentage != -2147483648 && bufferPercentage < 0 || isBufferingCauseStop) {
              long now = System.currentTimeMillis();
              if (bufferingLowStart == 0) {
                bufferingLowStart = now;
                LogManager.d(TAG, "缓冲发生不足");
              } else {
                long s = now - bufferingLowStart;
                LogManager.d(TAG, "缓冲持续不足:" + s + "ms");
                if (s >= bufferingLowOverdue) { // 超过缓冲超时时间了
                  LogManager.d("缓冲不足超时");
                  bufferingLowStart = 0;
                  // 暂停
                  if (onBufferingOverdueListener != null) {
                    onBufferingOverdueListener.onBufferingUpdate(mp, s);
                  }
                }
              }

            } else {
              bufferingLowStart = 0;
              LogManager.d(TAG, "mediaPlayer buffer percent:" + newBufferPercentage + "%");
              // 当剩余时间不足时,开始预加载下一首歌曲,且仅预加载一次
            }
          }
        });
  }
Exemplo n.º 28
0
  private void prepare() {
    mp = new MediaPlayer();
    try {
      //        	mp.setDataSource("http://forum.ea3w.com/coll_ea3w/attach/2008_10/12237832415.3gp");
      //
      //	mp.setDataSource("http://res.happyge.com:8081/client/test2/101/10101/101010100/img/400000.mp4");
      mp.setDataSource(url);
      mp.prepareAsync();
    } catch (IllegalArgumentException | SecurityException | IllegalStateException | IOException e) {
      e.printStackTrace();
    }
    mp.setOnBufferingUpdateListener(
        new OnBufferingUpdateListener() {

          @Override
          public void onBufferingUpdate(MediaPlayer mp, int percent) {}
        });
    mp.setOnCompletionListener(
        new MediaPlayer.OnCompletionListener() {

          @Override
          public void onCompletion(MediaPlayer mp) {
            state = VideoState.stop;
            ivStart.setVisibility(View.VISIBLE);
            ivStop.setVisibility(View.INVISIBLE);
            ivPause.setVisibility(View.INVISIBLE);
          }
        });
    mp.setOnPreparedListener(
        new OnPreparedListener() {

          @Override
          public void onPrepared(MediaPlayer mp) {
            mIsVideoReadyToBePlayed = true;
            mp.seekTo(0);
            startVideoPlayback();
          }
        });
    mp.setOnVideoSizeChangedListener(
        new OnVideoSizeChangedListener() {

          @Override
          public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {

            if (width == 0 || height == 0) {
              return;
            }
            //				if (width > AppInfo.getScreenWidth()) {
            double d = (double) AppInfo.getScreenWidth() / width;
            width = AppInfo.getScreenWidth();
            height = (int) (height * d);
            //				}
            mIsVideoSizeKnown = true;
            mVideoWidth = width;
            mVideoHeight = height;

            startVideoPlayback();
          }
        });
    mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
  }