Ejemplo n.º 1
1
 protected long getDuration(String file) {
   long duration = -2;
   if (!isPlaying & !isStreaming(file)) {
     try {
       mPlayer = new MediaPlayer();
       mPlayer.setDataSource("/sdcard/" + file);
       mPlayer.prepare();
       duration = mPlayer.getDuration();
       mPlayer.release();
     } catch (Exception e) {
       e.printStackTrace();
       return (-3);
     }
   } else if (isPlaying & !isStreaming(file)) {
     duration = mPlayer.getDuration();
   } else if (isPlaying & isStreaming(file)) {
     try {
       duration = mPlayer.getDuration();
     } catch (Exception e) {
       e.printStackTrace();
       return (-4);
     }
   } else {
     return -1;
   }
   return duration;
 }
Ejemplo n.º 2
0
  public void startPlayback(float percentage) {
    if (state() == PLAYING_PAUSED_STATE) {
      mSampleStart = System.currentTimeMillis() - mPlayer.getCurrentPosition();
      mPlayer.seekTo((int) (percentage * mPlayer.getDuration()));
      mPlayer.start();
      setState(PLAYING_STATE);
    } else {
      stop();

      mPlayer = new MediaPlayer();
      try {
        mPlayer.setDataSource(mSampleFile.getAbsolutePath());
        mPlayer.setOnCompletionListener(this);
        mPlayer.setOnErrorListener(this);
        mPlayer.prepare();
        mPlayer.seekTo((int) (percentage * mPlayer.getDuration()));
        mPlayer.start();
      } catch (IllegalArgumentException e) {
        setError(INTERNAL_ERROR);
        mPlayer = null;
        return;
      } catch (IOException e) {
        setError(STORAGE_ACCESS_ERROR);
        mPlayer = null;
        return;
      }

      mSampleStart = System.currentTimeMillis();
      setState(PLAYING_STATE);
    }
  }
Ejemplo n.º 3
0
 @Override
 public void onPrepared(MediaPlayer player) {
   // TODO Auto-generated method stub
   Log.i("tvinfo", "onPrepared");
   player.start();
   playSeek.setEnabled(true);
   playSeek.setMax(player.getDuration() / 1000);
   totaltime.setText(Utils.longToString(player.getDuration()));
   if (tupdate == null) {
     tupdate = new SeekBarUpdateThread(handler);
     tupdate.start();
   }
 }
Ejemplo n.º 4
0
        @Override
        public void handleMessage(Message msg) {
          if (mediaPlayer.isPlaying()) {

            int progress = (mediaPlayer.getCurrentPosition() * 100) / mediaPlayer.getDuration();
            Integer timeValues[] = new Integer[3];
            timeValues[0] = mediaPlayer.getCurrentPosition();
            timeValues[1] = mediaPlayer.getDuration();
            timeValues[2] = progress;

            Constants.PROGRESSBAR_HANDLER.sendMessage(
                Constants.PROGRESSBAR_HANDLER.obtainMessage(0, timeValues));
          }
        }
 @Override
 public void play() {
   if (mMediaPlayer.getCurrentPosition() >= mMediaPlayer.getDuration()) {
     mMediaPlayer.seekTo(0);
   }
   mMediaPlayer.start();
 }
 private void sendMaxPos() {
   if (mMediaPlayer != null) {
     intent = new Intent(UPDATE_MAX_POS);
     intent.putExtra("maxPos", mMediaPlayer.getDuration());
     sendBroadcast(intent);
   }
 }
  private int getDurationSeconds() {
    if (mMediaPlayer != null) {
      return mMediaPlayer.getDuration() / 1000;
    }

    return 0;
  }
Ejemplo n.º 8
0
 public int getDuration() {
   int duration = 0;
   if (mp != null) {
     duration = mp.getDuration();
   }
   return duration;
 }
Ejemplo n.º 9
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;
   }
 }
Ejemplo n.º 10
0
  public double getDuration() {
    destroyMediaPlayer();
    mediaPlayer = new MediaPlayer();
    try {
      mediaPlayer.setDataSource(getOutputMediaFile().getPath());
    } 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();
    }
    try {
      mediaPlayer.prepare();
    } catch (IllegalStateException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    double duration = mediaPlayer.getDuration();
    destroyMediaPlayer();
    releaseAll();

    return duration;
  }
Ejemplo n.º 11
0
 @Override
 public void onClick(View v) {
   // TODO Auto-generated method stub
   if (v.getId() == R.id.button3) {
     /** ImageButton onClick event handler. Method which start/pause mediaplayer playing */
     if (!cURL.equals("")) {
       try {
         String s = cURL.replace(" ", "");
         mediaPlayer.setDataSource(s);
         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);
         // play.setText("Pause");
       } else {
         mediaPlayer.pause();
         // buttonPlayPause.setImageResource(R.drawable.button_play);
         // play.setText("Play");
       }
       primarySeekBarProgressUpdater();
     }
   }
 }
Ejemplo n.º 12
0
 @Override
 public void onPrepared(MediaPlayer mp) {
   mediaPlayer.start();
   if (totalTime < 0) {
     totalTime = mediaPlayer.getDuration();
   }
 }
Ejemplo n.º 13
0
  // 录音完毕加载 ListView item
  private void finishRecord() {
    cancelTimer();
    stopRecording();
    if (recordIndicator != null) recordIndicator.dismiss();

    long intervalTime = System.currentTimeMillis() - startTime;
    if (intervalTime < MIN_INTERVAL_TIME) {
      MUIToast.toast(getContext(), R.string.time_too_short_toast);
      myRecAudioFile.delete();
      return;
    } else {
      if (myRecAudioFile != null && myRecAudioFile.exists()) {
        MediaPlayer mp = MediaPlayer.create(mContext, Uri.parse(myRecAudioFile.getAbsolutePath()));
        // 某些手机会限制录音,如果用户拒接使用录音,则需判断mp是否存在
        if (mp != null) {
          int duration = mp.getDuration() / 1000; // 即为时长 是s
          if (duration < 1) duration = 1;
          else if (duration > 60) duration = 60;

          mHandler
              .obtainMessage(
                  Api.UPLOAD_VOICE_CALLBACK, duration, 0, myRecAudioFile.getAbsolutePath())
              .sendToTarget();
        } else {
          MUIToast.toast(mContext, R.string.record_voice_permission_request);
        }
      }
    }
  }
        @Override
        public void onPrepared(MediaPlayer mp) {
          // 必须是正常状态
          if (mCurrentState == STATE_PREPARING) {
            mCurrentState = STATE_PREPARED;
            try {
              mDuration = mp.getDuration();
            } catch (IllegalStateException e) {
              Logger.e(e);
            }

            try {
              mVideoWidth = mp.getVideoWidth();
              mVideoHeight = mp.getVideoHeight();
            } catch (IllegalStateException e) {
              Logger.e(e);
            }

            switch (mTargetState) {
              case STATE_PREPARED:
                if (mOnPreparedListener != null) mOnPreparedListener.onPrepared(mMediaPlayer);
                break;
              case STATE_PLAYING:
                start();
                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();
    }
  }
Ejemplo n.º 16
0
  private int transmit(final AudioFile audio) throws Exception {

    FileDescriptor fd = audio.getFileDescriptor(context);

    if (fd == null) {
      Log.e(TAG, "Null WAV File supplied to transmit()");
      return 0;
    }

    if (mediaPlayer == null) initMediaPlayer();

    if (mediaPlayer.isPlaying()) {
      return mediaPlayer.getDuration() - mediaPlayer.getCurrentPosition();
    }

    mediaPlayer.setOnCompletionListener(
        new OnCompletionListener() {
          @Override
          public void onCompletion(MediaPlayer mp) {
            mp.reset();
            // Delete audio file to save internal memory
            audio.delete(context);
          }
        });

    try {
      mediaPlayer.setDataSource(fd);
      mediaPlayer.prepare();
      mediaPlayer.start();
    } catch (IllegalArgumentException e) {
      Log.e(TAG, "IllegalArgumentException in transmit()", e);
      return 0;
    } catch (IllegalStateException e) {
      Log.e(TAG, "IllegalStateException in transmit()", e);
      // Release and instantiate new MediaPlayer object just in case
      mediaPlayer.release();
      initMediaPlayer();
      return 0;
    } catch (IOException e) {
      Log.e(TAG, "IOException in transmit()", e);
      return 0;
    }

    Log.i(TAG, "Transmitting " + audio.getFilename() + ", " + mediaPlayer.getDuration() + "ms");

    return mediaPlayer.getDuration();
  }
  @Override
  public int getDuration() {
    if (mMediaPlayer != null) {
      return mMediaPlayer.getDuration();
    }

    return 0;
  }
Ejemplo n.º 18
0
  public void setSong(int index, Cursor c) {
    queue = c;
    int result =
        audioManager.requestAudioFocus(
            afListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

    stageQueueAdapter = new PlayerQueueAdapter(root, c);
    stageQueue.setAdapter(stageQueueAdapter);
    stageQueue.setOnItemClickListener(songSelected);

    if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
      try {
        c.moveToPosition(index);
        String path = c.getString(c.getColumnIndex(MediaStore.Audio.Media.DATA));
        if (isPlayerSet) {
          player.stop();
        }
        player.reset();
        player.setDataSource(path);
        player.prepare();
        player.start();
        isPlayerSet = true;
        playerPlayPauseButton.setBackgroundResource(R.drawable.player_pause_button);

        seekBar.setMax(player.getDuration());
        playerTotalTime.setText(convertTime(player.getDuration()));
        seekBar.setProgress(0);
        seekBarHandler.postDelayed(updateSeekBarTask, 100);
        String albumId = c.getString(c.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
        (new ImageLoader()).execute(albumId, artView);

        ImageView titleArt = (ImageView) root.title.findViewById(R.id.title_songscreen_album_art);
        TextView song = (TextView) root.title.findViewById(R.id.title_songscreen_text_1);
        TextView artist = (TextView) root.title.findViewById(R.id.title_songscreen_text_2);

        song.setText(c.getString(c.getColumnIndex(MediaStore.Audio.Media.TITLE)));
        artist.setText(c.getString(c.getColumnIndex(MediaStore.Audio.Media.ARTIST)));
        (new ImageLoader()).execute(albumId, titleArt);

        root.song = song.getText().toString();
        root.artist = artist.getText().toString();
      } catch (Exception e) {
        return;
      }
    }
  }
Ejemplo n.º 19
0
  @Override
  public void onPrepared(MediaPlayer mp) {
    mp.start();

    Intent intent = new Intent(START_SEEKBAR);
    intent.putExtra("Duration", mPlayer.getDuration());
    sendBroadcast(intent);
  }
Ejemplo n.º 20
0
 public int getDuration() {
   if (mediaPlayer != null) {
     duration = mediaPlayer.getDuration();
   } else {
     return 0;
   }
   return duration;
 }
Ejemplo n.º 21
0
 private void onCompletion() {
   Log.v(TAG, "00");
   if ((this.handler != null) && (mediaPlayer.getDuration() > 0)) {
     Message message = Message.obtain();
     message.what = 100;
     handler.sendMessage(message);
   }
 }
Ejemplo n.º 22
0
  @Override
  public int getDuration() {
    if (isInPlaybackState()) {
      return mMediaPlayer.getDuration();
    }

    return -1;
  }
Ejemplo n.º 23
0
 @Override
 public void onPrepared(MediaPlayer mp) {
   playMedia();
   Intent intent11 = new Intent(MusicPlayerFragment.RESPONE);
   intent11.putExtra(MusicPlayerFragment.RESPONE, MusicPlayerFragment.FTIME);
   intent11.putExtra(MusicPlayerFragment.TIME_RESPONE, mediaPlayer.getDuration() + "");
   sendBroadcast(intent11);
 }
Ejemplo n.º 24
0
 public int currentProgress() {
   if (mediaMode == MediaMode.UnInitialized) {
     int duration = currentDuration();
     if (duration == 0) return 0;
     return currentPostion() * 100 / duration;
   }
   return mediaPlayer.getCurrentPosition() * 100 / mediaPlayer.getDuration();
 }
Ejemplo n.º 25
0
  @Override
  public boolean onTouchEvent(MotionEvent event) {
    if (!FloatingService.bLock) {
      noticeShowControllerView(mMediaPlayer.getCurrentPosition(), mMediaPlayer.getDuration(), true);
    }

    return super.onTouchEvent(event);
  }
Ejemplo n.º 26
0
 public void bumpForwardSeconds(int bump) {
   if (currentPodcastInPlayer >= metaHolder.getSize()) return;
   try {
     int npos = mediaPlayer.getCurrentPosition() + bump * 1000;
     if (npos < 0) {
       npos = 0;
     } else if (npos > mediaPlayer.getDuration()) {
       npos = mediaPlayer.getDuration() - 1;
       mediaPlayer.seekTo(npos);
     }
     mediaPlayer.seekTo(npos);
   } catch (Exception e) {
     // do nothing
   }
   if (!mediaPlayer.isPlaying()) {
     saveState();
   }
 }
Ejemplo n.º 27
0
 private void LogMediaPosition() {
   if (cds.player_state.equals("playing")) {
     mediaPosition = mp.getCurrentPosition();
     mediaMax = mp.getDuration();
     progressIntent.putExtra("counter", mediaPosition);
     progressIntent.putExtra("mediamax", mediaMax);
     getApplicationContext().sendBroadcast(progressIntent);
   }
 }
Ejemplo n.º 28
0
    @Override
    public void onPrepared(MediaPlayer _mediaPlayer) {

      if (this.isResetting
          && RadioMaster.getInstance().getCurrentRadio().getCurrentStation().getIsFullTrack()) {
        _mediaPlayer.seekTo((int) (Math.random() * _mediaPlayer.getDuration()));
      }
      _mediaPlayer.start();
    }
Ejemplo n.º 29
0
  public synchronized long BackgroundMusicCreateFromFile(String fileName, int[] error) {
    if (fileName.equals("")) {
      error[0] = GAUDIO_CANNOT_OPEN_FILE;
      return 0;
    }

    AssetFileDescriptor fd = null;

    if (fileName.startsWith("/")) {
      File file = new File(fileName);
      if (!file.isFile()) {
        error[0] = GAUDIO_CANNOT_OPEN_FILE;
        return 0;
      }
    } else {
      if (patchFile_ != null) fd = patchFile_.getAssetFileDescriptor(fileName);
      if (fd == null && mainFile_ != null) fd = mainFile_.getAssetFileDescriptor(fileName);
      if (fd == null)
        try {
          fd = WeakActivityHolder.get().getAssets().openFd("assets/" + fileName);
        } catch (IOException e) {
        }

      if (fd == null) {
        error[0] = GAUDIO_CANNOT_OPEN_FILE;
        return 0;
      }
    }

    MediaPlayer player = new MediaPlayer();

    int duration = 0;

    try {
      if (fd != null) {
        player.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
        fd.close();
      } else {
        player.setDataSource(fileName);
      }
      player.prepare();
      duration = player.getDuration();
      player.release();
      player = null;
    } catch (Exception e) {
      error[0] = GAUDIO_UNRECOGNIZED_FORMAT;
      return 0;
    }

    long gid = nextgid();

    sounds_.put(gid, new Sound(fileName, duration));

    return gid;
  }
Ejemplo n.º 30
0
  /** When user stops moving the progress hanlder */
  public void onStopTrackingTouch(SeekBar seekBar) {
    mHandler.removeCallbacks(mUpdateTimeTask);
    int totalDuration = mp.getDuration();
    int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);

    // forward or backward to certain seconds
    mp.seekTo(currentPosition);

    // update timer progress again
    updateProgressBar();
  }