Java Code Examples for android.media.MediaPlayer#getDuration()

The following examples show how to use android.media.MediaPlayer#getDuration() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SoundPlayerView.java    From droid-vizu with Apache License 2.0 6 votes vote down vote up
public void setMediaPlayer(MediaPlayer player) {
  rippleVisualizerView.setMediaPlayer(player);
  int durationMilliseconds = player.getDuration();
  if (durationMilliseconds == -1) {
    durationMilliseconds = 0;
  }

  setSecondToFirstDecimalPoint(durationMilliseconds);
  rippleVisualizerView.setOnMediaPlayFinishCallbackk(new OnMediaPlayFinishCallback() {
    @Override
    public void finished() {
      currentMediaState = State.PAUSED;
      updateControlButton();
    }
  });
}
 
Example 2
Source File: AlertPlugin.java    From microbit with Apache License 2.0 6 votes vote down vote up
public static int getDuration(MediaPlayer mediaPlayer, AssetFileDescriptor afd) {
    int duration = 500;

    try {
        mediaPlayer.reset();
        mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        afd.close();
        mediaPlayer.prepare();
        duration = mediaPlayer.getDuration();
    } catch(IOException e) {
        Log.e(TAG, e.toString());
    }

    mediaPlayer.reset();

    return duration;
}
 
Example 3
Source File: AlertPlugin.java    From microbit with Apache License 2.0 6 votes vote down vote up
public static int getDuration(MediaPlayer mediaPlayer, Uri fileUri) {
    int duration = 500;

    try {
        mediaPlayer.reset();
        mediaPlayer.setDataSource(MBApp.getApp(), fileUri);
        mediaPlayer.prepare();
        duration = mediaPlayer.getDuration();
    } catch(IOException e) {
        Log.e(TAG, e.toString());
    }

    mediaPlayer.reset();

    return duration;
}
 
Example 4
Source File: MusicService.java    From SMP with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onPrepared(MediaPlayer mp) {
    // if a songPos has been stored
    if (savedSongPos > 0) {
        // seek to it
        if (savedSongPos < mp.getDuration())
            mp.seekTo(savedSongPos);
        // reset songPos
        params.setSongPos(0);
        savedSongPos = 0;
    }

    // start playback
    mp.start();
    state.setState(PlayerState.Started);

    scrobble.send(Scrobble.SCROBBLE_COMPLETE);
    scrobble.send(Scrobble.SCROBBLE_START);
}
 
Example 5
Source File: MusicService.java    From SMP with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onPrepared(MediaPlayer mp) {
    // if a songPos has been stored
    if (savedSongPos > 0) {
        // seek to it
        if (savedSongPos < mp.getDuration())
            mp.seekTo(savedSongPos);
        // reset songPos
        params.setSongPos(0);
        savedSongPos = 0;
    }

    // start playback
    mp.start();
    state.setState(PlayerState.Started);

    scrobble.send(Scrobble.SCROBBLE_COMPLETE);
    scrobble.send(Scrobble.SCROBBLE_START);
}
 
Example 6
Source File: MediaServiceBinder.java    From Cirrus_depricated with GNU General Public License v2.0 5 votes vote down vote up
@Override
public int getDuration() {
    MediaPlayer currentPlayer = mService.getPlayer();
    if (currentPlayer != null) {
        return currentPlayer.getDuration();
    } else {
        return 0;
    }
}
 
Example 7
Source File: VideoSeekBar.java    From CameraV with GNU General Public License v3.0 5 votes vote down vote up
public RangeSeekBar<Integer> init(MediaPlayer mp) {
	this.mp = mp;
	
	setMax(mp.getDuration());
	post(progressRunnable);
	setOnSeekBarChangeListener(this);
	
	endpointBar = new RangeSeekBar<Integer>(0, mp.getDuration(), context);		
	return endpointBar;
	
}
 
Example 8
Source File: ApplozicAudioManager.java    From Applozic-Android-SDK with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public String refreshAudioDuration(String filePath) {
    MediaPlayer mediaPlayer = new MediaPlayer();
    try {
        mediaPlayer.setDataSource(filePath);
        mediaPlayer.prepare();
        int duration = mediaPlayer.getDuration();
        duration = duration / 1000;
        minute = duration / 60;
        second = (duration % 60) + 1;
        mediaPlayer.release();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return String.format("%02d:%02d", minute, second);
}
 
Example 9
Source File: RecordVoiceButton.java    From jmessage-android-uikit with MIT License 5 votes vote down vote up
private void finishRecord() {
    cancelTimer();
    stopRecording();
    if (recordIndicator != null) {
        recordIndicator.dismiss();
    }

    long intervalTime = System.currentTimeMillis() - startTime;
    if (intervalTime < MIN_INTERVAL_TIME) {
        Toast.makeText(getContext(), mContext.getString(IdHelper.getString(mContext, "jmui_time_too_short_toast")), Toast.LENGTH_SHORT).show();
        myRecAudioFile.delete();
    } else {
        if (myRecAudioFile != null && myRecAudioFile.exists()) {
            MediaPlayer mp = new MediaPlayer();
            try {
                FileInputStream fis = new FileInputStream(myRecAudioFile);
                mp.setDataSource(fis.getFD());
                mp.prepare();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //某些手机会限制录音,如果用户拒接使用录音,则需判断mp是否存在
            if (mp != null) {
                int duration = mp.getDuration() / 1000;//即为时长 是s
                if (duration < 1) {
                    duration = 1;
                } else if (duration > 60) {
                    duration = 60;
                }
                mListener.onRecordFinished(duration, myRecAudioFile.getAbsolutePath());
            } else {
                Toast.makeText(mContext, mContext.getString(IdHelper.getString(mContext,
                                "jmui_record_voice_permission_request")), Toast.LENGTH_SHORT).show();
            }
        }
    }
}
 
Example 10
Source File: RecordButtonUtil.java    From KJFrameForAndroid with Apache License 2.0 5 votes vote down vote up
public void startPlay(String audioPath, TextView timeView) {
    if (!mIsPlaying) {
        if (!StringUtils.isEmpty(audioPath)) {
            mPlayer = new MediaPlayer();
            try {
                mPlayer.setDataSource(audioPath);
                mPlayer.prepare();
                if (timeView != null) {
                    int len = (mPlayer.getDuration() + 500) / 1000;
                    timeView.setText(len + "s");
                }
                mPlayer.start();
                if (listener != null) {
                    listener.starPlay();
                }
                mIsPlaying = true;
                mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        stopPlay();
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            ViewInject.toast(KJActivityStack.create().topActivity()
                    .getString(R.string.record_sound_notfound));
        }
    } else {
        stopPlay();
    } // end playing
}
 
Example 11
Source File: InlineCarouselCardMediaView.java    From Android-SDK-Demo with MIT License 5 votes vote down vote up
private int calculatePercentViewed(final MediaPlayer mp)
{
    final float videoDuration = mp.getDuration();
    final float currentPosition = mp.getCurrentPosition();
    // NOTE: Media player bug: calling getCurrentPosition after the video finished playing gives slightly larger value than the total duration of the video.
    if ( currentPosition >= videoDuration )
    {
        // Video fully watched, return 100%.
        return 100;
    }

    final double percentViewed = ( currentPosition / videoDuration ) * 100f;
    return (int) Math.ceil( percentViewed );
}
 
Example 12
Source File: AudioPlayer.java    From GSYRecordWave with Apache License 2.0 5 votes vote down vote up
/**
 * 获取当前播放时长
 *
 * @return 本地播放时长
 */
public static long getDurationLocation(Context context, String path) {
    MediaPlayer player = MediaPlayer.create(context, Uri.fromFile(new File(path)));
    if (player != null)
        return player.getDuration();
    else
        return 0;
}
 
Example 13
Source File: AudioTransCoder.java    From SimpleVideoEditor with Apache License 2.0 5 votes vote down vote up
private void prepare() throws IOException {
    extractor = new MediaExtractor();
    extractor.setDataSource(mInputFile.getAbsolutePath());
    int numTracks = extractor.getTrackCount();
    for (int i = 0; i < numTracks; i++) {
        MediaFormat format = extractor.getTrackFormat(i);
        String mine = format.getString(MediaFormat.KEY_MIME);
        if (!TextUtils.isEmpty(mine) && mine.startsWith("audio")) {
            extractor.selectTrack(i);
            if (mDurationMs == 0) {
                try {
                    mDurationMs = format.getLong(MediaFormat.KEY_DURATION) / 1000;
                } catch (Exception e) {
                    e.printStackTrace();
                    MediaPlayer mediaPlayer = new MediaPlayer();
                    mediaPlayer.setDataSource(mInputFile.getAbsolutePath());
                    mediaPlayer.prepare();
                    mDurationMs = mediaPlayer.getDuration();
                    mediaPlayer.release();
                }
            }

            if (mDurationMs == 0) {
                throw new IllegalStateException("We can not get duration info from input file: " + mInputFile);
            }

            decoder = MediaCodec.createDecoderByType(mine);
            decoder.configure(format, null, null, 0);
            decoder.start();
            break;
        }
    }
}
 
Example 14
Source File: VideoPlayerContainer.java    From LLApp with Apache License 2.0 5 votes vote down vote up
@Override
public void onPrepared(MediaPlayer mp) {
	//准备播放,显示该控件
	setVisibility(View.VISIBLE);
	int duration=mp.getDuration();
	//设置最大事件,单位秒
	mDurationView.setText(mTimeFormat.format(new Date(duration)));
	mProgressBar.setMax((int) Math.floor(duration/1000));
	mp.start();
	mHandler.removeCallbacks(null, null);
	mHandler.post(playerRunnable);
}
 
Example 15
Source File: MNViderPlayer.java    From MNVideoPlayer with GNU General Public License v3.0 5 votes vote down vote up
@Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
//        Log.i(TAG, "二级缓存onBufferingUpdate: " + percent);
        if (percent >= 0 && percent <= 100) {
            int secondProgress = mp.getDuration() * percent / 100;
            mn_seekBar.setSecondaryProgress(secondProgress);
        }
    }
 
Example 16
Source File: VidstaPlayer.java    From Vidsta with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
    isPrepared = true;
    videoDuration = mediaPlayer.getDuration();
    seekBarDuration.setProgress(0);
    seekBarDuration.setMax(videoDuration);
    tvPosition.setText(VidstaUtil.getTimeString(0, false));
    tvDuration.setText(VidstaUtil.getTimeString(videoDuration, true));
    proViewVideoLoading.stop();
    proViewVideoLoading.setVisibility(INVISIBLE);
    removeView(videoLoadingView);
    videoPlayer.setOnVideoSizeChangedListener(this);

    if (initialVideoWidth == null && initialVideoHeight == null) {
        initialVideoWidth = videoPlayer.getVideoWidth();
        initialVideoHeight = videoPlayer.getVideoHeight();
    }

    if (autoPlay) {
        start();
    } else {
        controlPlayPause.setVisibility(VISIBLE);
        controlSeekBar.setVisibility(VISIBLE);
        start();
        pause();
    }
}
 
Example 17
Source File: HelpUtils.java    From browser with GNU General Public License v2.0 5 votes vote down vote up
public static int mediaDuration(Context context,String path){
    MediaPlayer mp = MediaPlayer.create(context, Uri.parse(path));
    if(mp==null){
        return 0;
    }
    int duration = mp.getDuration();
    mp.release();
    return duration;
}
 
Example 18
Source File: MaskProgressLayout.java    From AlbumCameraRecorder with MIT License 5 votes vote down vote up
@Override
public void addAudioUrl(String audioUrl) {
    MediaPlayer mediaPlayer = new MediaPlayer();
    try {
        mediaPlayer.setDataSource(audioUrl);
        mediaPlayer.prepare();
        int duration = mediaPlayer.getDuration();
        if (0 != duration) {
            MultiMediaView multiMediaView = new MultiMediaView(MultimediaTypes.AUDIO);
            multiMediaView.setUrl(audioUrl);
            multiMediaView.setViewHolder(this);

            if (this.audioList == null) {
                this.audioList = new ArrayList<>();
            }
            audioList.add(multiMediaView);

            // 显示音频播放控件,当点击播放的时候,才正式下载并且进行播放
            mViewHolder.playView.setVisibility(View.VISIBLE);
            isShowRemovceRecorder();
            RecordingItem recordingItem = new RecordingItem();
            recordingItem.setUrl(audioUrl);
            recordingItem.setLength(duration);
            mViewHolder.playView.setData(recordingItem, audioProgressColor);
            //记得释放资源
            mediaPlayer.release();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 19
Source File: ChatAdapter.java    From FlyWoo with Apache License 2.0 4 votes vote down vote up
private int getVoiceLength(View view, String path) {
    MediaPlayer mp = MediaPlayer.create(view.getContext(), Uri.parse("file://" + path));
    int duration = mp.getDuration() / 1000;
    mp.release();
    return duration;
}
 
Example 20
Source File: PickerActivity.java    From MultiImagePicker with MIT License 2 votes vote down vote up
public void onEvent(final Events.OnPickImageEvent pickImageEvent) {
    if (mPickOptions.videosEnabled && mPickOptions.videoLengthLimit > 0 && pickImageEvent.imageEntry.isVideo) {
        // Check to see if the selected video is too long in length
        final MediaPlayer mp = MediaPlayer.create(this, Uri.parse(pickImageEvent.imageEntry.path));
        final int duration = mp.getDuration();
        mp.release();
        if (duration > (mPickOptions.videoLengthLimit)) {
            Toast.makeText(this, getResources().getString(R.string.video_too_long).replace("$", String.valueOf(mPickOptions.videoLengthLimit / 1000)), Toast.LENGTH_SHORT).show();
            return; // Don't allow selection
        }
    }

    if (mPickOptions.pickMode == Picker.PickMode.MULTIPLE_IMAGES) {
        handleMultipleModeAddition(pickImageEvent.imageEntry);


    } else if (mPickOptions.pickMode == Picker.PickMode.SINGLE_IMAGE) {
        //Single image pick mode


        final ImagesPagerFragment pagerFragment;

        if (getSupportFragmentManager().findFragmentByTag(ImagesPagerFragment.TAG) != null) {

            pagerFragment = (ImagesPagerFragment) getSupportFragmentManager().findFragmentByTag(ImagesPagerFragment.TAG);
        } else {
            pagerFragment = new ImagesPagerFragment();
        }


        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment_container, pagerFragment, ImagesPagerFragment.TAG)
                .addToBackStack(ImagesPagerFragment.TAG)
                .commit();


    }


    updateFab();

}