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

The following examples show how to use android.media.MediaPlayer#setLooping() . 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: MainActivity.java    From WeiXinRecordedDemo with MIT License 6 votes vote down vote up
private void playVideo(String videoPath){

        try {
            mMediaPlayer = new MediaPlayer();
            mMediaPlayer.setDataSource(videoPath);
            mMediaPlayer.setSurface(new Surface(textureView.getSurfaceTexture()));
            mMediaPlayer.setLooping(true);
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.start();

                    float ratio = mp.getVideoWidth()*1f/mp.getVideoHeight();
                    int width = textureView.getWidth();
                    ViewGroup.LayoutParams layoutParams = textureView.getLayoutParams();
                    layoutParams.height = (int) (width/ratio);
                    textureView.setLayoutParams(layoutParams);
                }
            });
            mMediaPlayer.prepareAsync();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
 
Example 2
Source File: BeepManager.java    From analyzer-of-android-for-Apache-Weex with Apache License 2.0 6 votes vote down vote up
private MediaPlayer buildMediaPlayer(Context activity) {
  MediaPlayer mediaPlayer = new MediaPlayer();
  try {
    AssetFileDescriptor file = activity.getResources().openRawResourceFd(R.raw.beep);
    try {
      mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
    } finally {
      file.close();
    }
    mediaPlayer.setOnErrorListener(this);
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setLooping(false);
    mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
    mediaPlayer.prepare();
    return mediaPlayer;
  } catch (IOException ioe) {
    Log.w(TAG, ioe);
    mediaPlayer.release();
    return null;
  }
}
 
Example 3
Source File: GuideFragment.java    From LefishGuide with Apache License 2.0 6 votes vote down vote up
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
    Surface surface = new Surface(surfaceTexture);
    try {
        int id = getArguments().getInt("Id");
        /**
         * mMediaPlayer = MediaPlayer.create(getContext(), R.raw.guide_one);
         * 创建实例是不行的,我也没有明白为什么
         */
        mMediaPlayer = new MediaPlayer();
        Uri video = Uri.parse("android.resource://" + getContext().getPackageName() + "/" + RES.get(id));
        mMediaPlayer.setDataSource(getContext(), video);

        mMediaPlayer.setSurface(surface);
        mMediaPlayer.prepare();
        mMediaPlayer.setLooping(false);
        mMediaPlayer.setOnBufferingUpdateListener(this);
        mMediaPlayer.setOnCompletionListener(this);
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.setOnVideoSizeChangedListener(this);
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 4
Source File: CutTimeActivity.java    From WeiXinRecordedDemo with MIT License 6 votes vote down vote up
private void initMediaPlay(SurfaceTexture surface){

        try {
            mMediaPlayer = new MediaPlayer();
            mMediaPlayer.setDataSource(path);
            mMediaPlayer.setSurface(new Surface(surface));
            mMediaPlayer.setLooping(true);
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mMediaPlayer.start();
                }
            });
            mMediaPlayer.prepareAsync();
        }catch (Exception e){
            e.printStackTrace();
        }

        initVideoSize();
        initThumbs();
    }
 
Example 5
Source File: VideoFileInputSource.java    From MockCamera with Apache License 2.0 6 votes vote down vote up
public void startPreview() {
    try {
        player = new MediaPlayer();
        AssetFileDescriptor afd = this.context.getAssets().openFd(this.filename);
        player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        player.setLooping(false);
        player.setOnCompletionListener(new VideoOnCompletionListener());
        player.setOnPreparedListener(this);
        player.prepareAsync();
        frameSize = new Size(this.player.getVideoWidth(), this.player.getVideoHeight());
        player.setSurface(new Surface(this.surfaceTexture));
        Log.d(TAG, "Video starting playback at: " + this.frameSize.width + "x" + this.frameSize.height);
    } catch (IOException e) {
        throw new RuntimeException("Could not open input video!", e);
    }
}
 
Example 6
Source File: IncomingRinger.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private MediaPlayer createPlayer(@NonNull Uri ringtoneUri) {
  try {
    MediaPlayer mediaPlayer = new MediaPlayer();

    mediaPlayer.setOnErrorListener(new MediaPlayerErrorListener());
    mediaPlayer.setDataSource(context, ringtoneUri);
    mediaPlayer.setLooping(true);

    if (Build.VERSION.SDK_INT <= 21) {
      mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
    } else {
      mediaPlayer.setAudioAttributes(new AudioAttributes.Builder()
                                                        .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
                                                        .setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION_SIGNALLING)
                                                        .build());
    }

    return mediaPlayer;
  } catch (IOException e) {
    Log.e(TAG, "Failed to create player for incoming call ringer");
    return null;
  }
}
 
Example 7
Source File: BeepManager.java    From CodeScaner with MIT License 6 votes vote down vote up
private MediaPlayer buildMediaPlayer(Context activity) {
  MediaPlayer mediaPlayer = new MediaPlayer();
  try {
    AssetFileDescriptor file = activity.getResources().openRawResourceFd(R.raw.beep);
    try {
      mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
    } finally {
      file.close();
    }
    mediaPlayer.setOnErrorListener(this);
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setLooping(false);
    mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
    mediaPlayer.prepare();
    return mediaPlayer;
  } catch (IOException ioe) {
    Log.w(TAG, ioe);
    mediaPlayer.release();
    return null;
  }
}
 
Example 8
Source File: AlarmAlertActivity.java    From SpecialAlarmClock with Apache License 2.0 6 votes vote down vote up
private void startAlarm() {
    if (alarm.getAlarmTonePath() != "") {
        mediaPlayer = new MediaPlayer();
        if (alarm.IsVibrate()) {
            vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            long[] pattern = {1000, 200, 200, 200};
            vibrator.vibrate(pattern, 0);
        }
        try {
            mediaPlayer.setVolume(1.0f, 1.0f);
            mediaPlayer.setDataSource(this, Uri.parse(alarm.getAlarmTonePath()));
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
            mediaPlayer.setLooping(true);
            mediaPlayer.prepare();
            mediaPlayer.start();

        } catch (Exception e) {
            mediaPlayer.release();
            alarmActive = false;
        }
    }

}
 
Example 9
Source File: BeepManager.java    From Study_Android_Demo with Apache License 2.0 6 votes vote down vote up
private MediaPlayer buildMediaPlayer(Context activity) {
  MediaPlayer mediaPlayer = new MediaPlayer();
  try {
    AssetFileDescriptor file = activity.getResources().openRawResourceFd(R.raw.beep);
    try {
      mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
    } finally {
      file.close();
    }
    mediaPlayer.setOnErrorListener(this);
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setLooping(false);
    mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
    mediaPlayer.prepare();
    return mediaPlayer;
  } catch (IOException ioe) {
    Log.w(TAG, ioe);
    mediaPlayer.release();
    return null;
  }
}
 
Example 10
Source File: IncomingRinger.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
private MediaPlayer createPlayer() {
  try {
    MediaPlayer mediaPlayer = new MediaPlayer();
    Uri         ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);

    mediaPlayer.setOnErrorListener(new MediaPlayerErrorListener());
    mediaPlayer.setDataSource(context, ringtoneUri);
    mediaPlayer.setLooping(true);
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);

    return mediaPlayer;
  } catch (Throwable tr) {
    Log.e(TAG, "Failed to create player for incoming call ringer");
    return null;
  }
}
 
Example 11
Source File: RxAudioPlayer.java    From RxAndroidAudio with MIT License 5 votes vote down vote up
/**
 * Non reactive API.
 */
@WorkerThread
public boolean playNonRxy(@NonNull final PlayConfig config,
        final MediaPlayer.OnCompletionListener onCompletionListener,
        final MediaPlayer.OnErrorListener onErrorListener) {
    if (!config.isArgumentValid()) {
        return false;
    }

    try {
        MediaPlayer player = create(config);
        setMediaPlayerListener(player, onCompletionListener, onErrorListener);
        player.setVolume(config.mLeftVolume, config.mRightVolume);
        player.setAudioStreamType(config.mStreamType);
        player.setLooping(config.mLooping);
        if (config.needPrepare()) {
            player.prepare();
        }
        player.start();

        mPlayer = player;
        return true;
    } catch (RuntimeException | IOException e) {
        Log.w(TAG, "startPlay fail, IllegalArgumentException: " + e.getMessage());
        stopPlay();
        return false;
    }
}
 
Example 12
Source File: PlayerService.java    From Pocket-Plays-for-Twitch with GNU General Public License v3.0 5 votes vote down vote up
private MediaPlayer getNewMediaPlayer() throws IOException {
	MediaPlayer mediaPlayer = new MediaPlayer();
	mediaPlayer.setDataSource(this, Uri.parse(url));
	mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
	mediaPlayer.setLooping(false);

	return mediaPlayer;
}
 
Example 13
Source File: AlarmService.java    From talalarmo with MIT License 5 votes vote down vote up
private void startPlayer() {
    mPlayer = new MediaPlayer();
    mPlayer.setOnErrorListener(mErrorListener);

    try {
        // add vibration to alarm alert if it is set
        if (App.getState().settings().vibrate()) {
            mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            mHandler.post(mVibrationRunnable);
        }
        // Player setup is here
        String ringtone = App.getState().settings().ringtone();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                && ringtone.startsWith("content://media/external/")
                && checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
            ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM).toString();
        }
        mPlayer.setDataSource(this, Uri.parse(ringtone));
        mPlayer.setLooping(true);
        mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
        mPlayer.setVolume(mVolumeLevel, mVolumeLevel);
        mPlayer.prepare();
        mPlayer.start();

        if (App.getState().settings().ramping()) {
            mHandler.postDelayed(mVolumeRunnable, VOLUME_INCREASE_DELAY);
        } else {
            mPlayer.setVolume(MAX_VOLUME, MAX_VOLUME);
        }
    } catch (Exception e) {
        if (mPlayer.isPlaying()) {
            mPlayer.stop();
        }
        stopSelf();
    }
}
 
Example 14
Source File: IntroTextureView.java    From evercam-android with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * MediaPlayer.OnPreparedListener
 * Callback for player.prepareAsync();
 */

@Override
public void onPrepared(MediaPlayer mp) {
    mp.setLooping(true);
    mp.start();
}
 
Example 15
Source File: NotificationKlaxon.java    From boilr with GNU General Public License v3.0 5 votes vote down vote up
private static void startAlarm(final Context context, MediaPlayer player, int alertType)
		throws IOException {
	AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
	int streamType = sAlertToStreamType.get(alertType);
	// do not play alarms if stream volume is 0 (typically because ringer mode is silent).
	if(audioManager.getStreamVolume(streamType) != 0) {
		player.setAudioStreamType(streamType);
		player.setLooping(true);
		player.prepare();
		audioManager.requestAudioFocus(null, streamType, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
		player.start();
	}
}
 
Example 16
Source File: LocationAwareService.java    From LocationAware with Apache License 2.0 5 votes vote down vote up
private void startPlayer() {
  mPlayer = new MediaPlayer();
  mPlayer.setOnErrorListener(mErrorListener);

  try {
    isAlarmRinging = true;
    // add vibration to alarm alert if it is set
    //if (App.getState().settings().vibrate()) {
    mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    mHandler.post(mVibrationRunnable);
    //}
    // Player setup is here
    String ringtone;// = App.getState().settings().ringtone();
    //if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
    //    && ringtone.startsWith("content://media/external/")
    //    && checkSelfPermission(
    //    Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
    ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM).toString();
    //}
    mPlayer.setDataSource(this, Uri.parse(ringtone));
    mPlayer.setLooping(true);
    mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
    mPlayer.setVolume(mVolumeLevel, mVolumeLevel);
    mPlayer.prepare();
    mPlayer.start();

    //if (App.getState().settings().ramping()) {
    //  mHandler.postDelayed(mVolumeRunnable, VOLUME_INCREASE_DELAY);
    //} else {
    mPlayer.setVolume(MAX_VOLUME, MAX_VOLUME);
    //}
  } catch (Exception e) {
    isAlarmRinging = false;
    if (mPlayer.isPlaying()) {
      mPlayer.stop();
    }
    stopSelf();
  }
}
 
Example 17
Source File: PictureSelectorActivity.java    From PictureSelector with Apache License 2.0 5 votes vote down vote up
/**
 * init Player
 *
 * @param path
 */
private void initPlayer(String path) {
    mediaPlayer = new MediaPlayer();
    try {
        mediaPlayer.setDataSource(path);
        mediaPlayer.prepare();
        mediaPlayer.setLooping(true);
        playAudio();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 18
Source File: FragmentShowImage.java    From iGap-Android with GNU Affero General Public License v3.0 4 votes vote down vote up
private void setMediaPlayer(MediaPlayer mMediaPlayer, final TextureView mTextureView, final ImageView imgPlay, final TouchImageView touchImageView) {

            if (mTextureView == null) {
                return;
            }
            Surface surfaceTexture = new Surface(mTextureView.getSurfaceTexture());

            if (surfaceTexture == null) {
                return;
            }

            try {
                if (mMediaPlayer != null) {
                    mMediaPlayer.setSurface(surfaceTexture);
                    mMediaPlayer.setLooping(false);
                    mMediaPlayer.prepareAsync();
                }
            } catch (IllegalStateException e) {
                e.getMessage();
            }


            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {

                    getRealSize(mp, mTextureView);
                    imgPlay.setVisibility(View.GONE);
                    mp.start();
                    MusicPlayer.pauseSound();
                    mTextureView.setVisibility(View.VISIBLE);
                    touchImageView.animate().setDuration(700).alpha(0F).start();

                    G.handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            touchImageView.setVisibility(View.GONE);
                            touchImageView.clearAnimation();
                        }
                    }, 700);

                    videoController.setEnabled(true);
                    videoController.show();
                }
            });

        }
 
Example 19
Source File: ChooseMusicActivity.java    From PLDroidShortVideo with Apache License 2.0 4 votes vote down vote up
private void initPlayer() {
    mMediaPlayer = new MediaPlayer();
    mMediaPlayer.setLooping(true);
}
 
Example 20
Source File: VoIPBaseService.java    From Telegram-FOSS with GNU General Public License v2.0 4 votes vote down vote up
protected void startRingtoneAndVibration(int chatID){
	SharedPreferences prefs = MessagesController.getNotificationsSettings(currentAccount);
	AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
	boolean needRing=am.getRingerMode()!=AudioManager.RINGER_MODE_SILENT;
	/*if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP){
		try{
			int mode=Settings.Global.getInt(getContentResolver(), "zen_mode");
			if(needRing)
				needRing=mode==0;
		}catch(Exception ignore){}
	}*/
	if(needRing){
		if(!USE_CONNECTION_SERVICE){
			am.requestAudioFocus(this, AudioManager.STREAM_RING, AudioManager.AUDIOFOCUS_GAIN);
		}
		ringtonePlayer=new MediaPlayer();
		ringtonePlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){
			@Override
			public void onPrepared(MediaPlayer mediaPlayer){
				ringtonePlayer.start();
			}
		});
		ringtonePlayer.setLooping(true);
		ringtonePlayer.setAudioStreamType(AudioManager.STREAM_RING);
		try{
			String notificationUri;
			if(prefs.getBoolean("custom_"+chatID, false))
				notificationUri=prefs.getString("ringtone_path_"+chatID, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE).toString());
			else
				notificationUri=prefs.getString("CallsRingtonePath", RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE).toString());
			ringtonePlayer.setDataSource(this, Uri.parse(notificationUri));
			ringtonePlayer.prepareAsync();
		}catch(Exception e){
			FileLog.e(e);
			if(ringtonePlayer!=null){
				ringtonePlayer.release();
				ringtonePlayer=null;
			}
		}
		int vibrate;
		if(prefs.getBoolean("custom_"+chatID, false))
			vibrate=prefs.getInt("calls_vibrate_"+chatID, 0);
		else
			vibrate=prefs.getInt("vibrate_calls", 0);
		if((vibrate!=2 && vibrate!=4 && (am.getRingerMode()==AudioManager.RINGER_MODE_VIBRATE || am.getRingerMode()==AudioManager.RINGER_MODE_NORMAL)) ||
				(vibrate==4 && am.getRingerMode()==AudioManager.RINGER_MODE_VIBRATE)){
			vibrator=(Vibrator) getSystemService(VIBRATOR_SERVICE);
			long duration=700;
			if(vibrate==1)
				duration/=2;
			else if(vibrate==3)
				duration*=2;
			vibrator.vibrate(new long[]{0, duration, 500}, 0);
		}
	}
}