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

The following examples show how to use android.media.MediaPlayer#start() . 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: AudioRecordingActivity.java    From coursera-android with MIT License 6 votes vote down vote up
private void startPlaying() {

        mPlayer = new MediaPlayer();

        mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mPlayButton.performClick();
                mPlayButton.setChecked(false);
            }
        });

        try {
            mPlayer.setDataSource(mFileName);
            mPlayer.prepare();
            mPlayer.start();
        } catch (IOException e) {
            Log.e(TAG, "Couldn't prepare and start MediaPlayer");
        }

    }
 
Example 2
Source File: FullscreenVideoView.java    From fullscreen-video-view with Apache License 2.0 6 votes vote down vote up
@Override
public void onMediaPlayerPrepared(
        MediaPlayer mediaPlayer,
        int videoWidth,
        int videoHeight,
        boolean isAutoStartEnabled
) {
    hideProgressBar();

    if (surfaceView != null) {
        surfaceView.updateLayoutParams(videoWidth, videoHeight);
    }

    if (!isVisible) {
        isMediaPlayerPrepared = true;
        // Start media player if auto start is enabled
        if (isAutoStartEnabled) {
            mediaPlayer.start();
            hideThumbnail();
        }
    }
    // Seek to a specific time
    seekTo(seekToTimeMillis);
}
 
Example 3
Source File: Notifications.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
private void soundAlert(String soundUri) {
    manager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
    int maxVolume = manager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    currentVolume = manager.getStreamVolume(AudioManager.STREAM_MUSIC);
    manager.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, 0);
    Uri notification = Uri.parse(soundUri);
    MediaPlayer player = MediaPlayer.create(mContext, notification);

    player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            manager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);
        }
    });
    player.start();
}
 
Example 4
Source File: Notifications.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
public static void soundAlert(String soundUri) {
    manager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
    int maxVolume = manager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    currentVolume = manager.getStreamVolume(AudioManager.STREAM_MUSIC);
    manager.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, 0);
    Uri notification = Uri.parse(bg_notification_sound);
    MediaPlayer player = MediaPlayer.create(mContext, notification);

    player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            manager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);
        }
    });
    player.start();
}
 
Example 5
Source File: MainActivity.java    From astrobee_android with Apache License 2.0 6 votes vote down vote up
public void onPlaybackClick(View v) {
    File f = new File(getExternalFilesDir(null), "recording.mp4");

    if (!mPlaying) {
        try {
            mPlayer = new MediaPlayer();
            mPlayer.setDataSource(f.getAbsolutePath());
            mPlayer.setOnCompletionListener(mOnCompletionListener);
            mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mPlayer.prepare();
            mPlayer.start();
            mPlaying = true;
            setState(STATE_PLAYING_BACK);
        } catch (IOException e) {
            Log.e(TAG, "error trying to playback recording");
        }
    } else {
        mPlayer.setOnCompletionListener(null);
        mPlayer.stop();
        mPlayer.release();
        mPlayer = null;

        mPlaying = false;
        setState(STATE_IDLE);
    }
}
 
Example 6
Source File: PlayService.java    From music_player with Open Software License 3.0 6 votes vote down vote up
@Override
public void onPrepared(MediaPlayer mp) {
    //关闭加载框
    EventBus.getDefault().post(new dismissEvent());
    if (onetime) {
        EventBus.getDefault().post(new UIChangeEvent(MyConstant.initialize));
        onetime = false;
    }
    mp.start();
    MyApplication.setMediaDuration(mp.getDuration());
    MyApplication.setState(MyConstant.playing);
    EventBus.getDefault().post(new UIChangeEvent(MyConstant.mediaChangeAction));
    updateMetaDataAndBuildNotification();
    //储存播放次数
    new savePlayTimesTask().execute();
}
 
Example 7
Source File: MusicService.java    From Beginner-Level-Android-Studio-Apps with GNU General Public License v3.0 6 votes vote down vote up
@Override
    public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
        Intent notIntent = new Intent(this, MainActivity.class);
        notIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendInt = PendingIntent.getActivity(this, 0,
                notIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Notification.Builder builder = new Notification.Builder(this);

        builder.setContentIntent(pendInt)
                .setSmallIcon(R.drawable.play)
                .setTicker(songTitle)
                .setOngoing(true)
                .setContentTitle("Playing")
  .setContentText(songTitle);
        Notification not = builder.build();

        startForeground(NOTIFY_ID, not);

    }
 
Example 8
Source File: VideoOutputActivity.java    From SimpleVideoEdit with Apache License 2.0 5 votes vote down vote up
private void setMediaPlayer() {
    player = new MediaPlayer();
    player.setOnCompletionListener(this);
    player.setOnInfoListener(this);
    player.setOnPreparedListener(this);
    try {
        player.setDataSource(mSVE.getAllInputClips().get(0).getClipPath());
        player.prepare();
        player.start();
    } catch (IOException e) {

    }
}
 
Example 9
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 10
Source File: MediaPlayerHelper.java    From ml-authentication with Apache License 2.0 5 votes vote down vote up
public static void play(Context context, int resId) {
    Log.i(MediaPlayerHelper.class.getName(), "play");

    final MediaPlayer mediaPlayer = MediaPlayer.create(context, resId);
    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            mediaPlayer.release();
        }
    });
    mediaPlayer.start();
}
 
Example 11
Source File: soundPlayer.java    From Game with GNU General Public License v3.0 5 votes vote down vote up
public static void playSoundFile(String key) {
    try {
        if (!orsc.mudclient.optionSoundDisabled) {
            File sound = orsc.mudclient.soundCache.get(key + ".wav");
            if (sound == null)
                return;
            try {
                MediaPlayer player = new MediaPlayer();
                AudioAttributes audioAttrib = new AudioAttributes.Builder()
                        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                        .setUsage(AudioAttributes.USAGE_MEDIA)
                        .build();
                player.setDataSource(sound.getPath());
                player.setAudioAttributes(audioAttrib);
                player.setLooping(false);
                player.prepare();
                player.start();
                player.setOnCompletionListener(MediaPlayer::release);

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

    } catch (RuntimeException ignored) {
    }
}
 
Example 12
Source File: VideoViewTV.java    From letv with Apache License 2.0 5 votes vote down vote up
public void start(MediaPlayer mMediaPlayer) {
    if (isInPlaybackState()) {
        mMediaPlayer.start();
        this.mCurrentState = 3;
    }
    this.mTargetState = 3;
}
 
Example 13
Source File: RecordView.java    From RecordView with Apache License 2.0 5 votes vote down vote up
private void playSound(int soundRes) {

        if (isSoundEnabled) {
            if (soundRes == 0)
                return;

            try {
                player = new MediaPlayer();
                AssetFileDescriptor afd = context.getResources().openRawResourceFd(soundRes);
                if (afd == null) return;
                player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                afd.close();
                player.prepare();
                player.start();
                player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        mp.release();
                    }

                });
                player.setLooping(false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
 
Example 14
Source File: noxmllayoutexample.java    From ui with Apache License 2.0 5 votes vote down vote up
private void startPlaying() {
    mPlayer = new MediaPlayer();
    try {
        mPlayer.setDataSource(mFileName);
        mPlayer.prepare();
        mPlayer.start();
    } catch (IOException e) {
        Log.e(LOG_TAG, "prepare() failed");
    }
}
 
Example 15
Source File: JZMediaSystem.java    From JZVideoDemo with MIT License 5 votes vote down vote up
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
    mediaPlayer.start();
    if (currentDataSource.toString().toLowerCase().contains("mp3") ||
            currentDataSource.toString().toLowerCase().contains("wav")) {
        JZMediaManager.instance().mainThreadHandler.post(new Runnable() {
            @Override
            public void run() {
                if (JZVideoPlayerManager.getCurrentJzvd() != null) {
                    JZVideoPlayerManager.getCurrentJzvd().onPrepared();
                }
            }
        });
    }
}
 
Example 16
Source File: SoundLogic.java    From redalert-android with Apache License 2.0 5 votes vote down vote up
static void playSoundURI(Uri alarmSoundUi, Context context) {
    // No URI?
    if (alarmSoundUi == null) {
        return;
    }

    // Already initialized or currently playing?
    stopSound(context);

    // Create new MediaPlayer
    mPlayer = new MediaPlayer();

    // Wake up processor
    mPlayer.setWakeMode(context, PowerManager.PARTIAL_WAKE_LOCK);

    // Set stream type
    mPlayer.setAudioStreamType(getSoundStreamType(context));

    try {
        // Set URI data source
        mPlayer.setDataSource(context, alarmSoundUi);

        // Prepare media player
        mPlayer.prepare();
    }
    catch (Exception exc) {
        // Log it
        Log.e(Logging.TAG, "Media player preparation failed", exc);

        // Show visible error toast
        Toast.makeText(context, exc.toString(), Toast.LENGTH_LONG).show();
    }

    // Actually start playing
    mPlayer.start();
}
 
Example 17
Source File: MusicService.java    From audiostream-metadata-retriever with Apache License 2.0 4 votes vote down vote up
@Override
public void onPrepared(MediaPlayer mp)
{
    mp.start();
}
 
Example 18
Source File: EaseChatRowVoicePlayClickListener.java    From Study_Android_Demo with Apache License 2.0 4 votes vote down vote up
public void playVoice(String filePath) {
	if (!(new File(filePath).exists())) {
		return;
	}
	playMsgId = message.getMsgId();
	AudioManager audioManager = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);

	mediaPlayer = new MediaPlayer();
	if (EaseUI.getInstance().getSettingsProvider().isSpeakerOpened()) {
		audioManager.setMode(AudioManager.MODE_NORMAL);
		audioManager.setSpeakerphoneOn(true);
		mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
	} else {
		audioManager.setSpeakerphoneOn(false);// 关闭扬声器
		// 把声音设定成Earpiece(听筒)出来,设定为正在通话中
		audioManager.setMode(AudioManager.MODE_IN_CALL);
		mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
	}
	try {
		mediaPlayer.setDataSource(filePath);
		mediaPlayer.prepare();
		mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

			@Override
			public void onCompletion(MediaPlayer mp) {
				// TODO Auto-generated method stub
				mediaPlayer.release();
				mediaPlayer = null;
				stopPlayVoice(); // stop animation
			}

		});
		isPlaying = true;
		currentPlayListener = this;
		mediaPlayer.start();
		showAnimation();

		// 如果是接收的消息
		if (message.direct() == EMMessage.Direct.RECEIVE) {
		    if (!message.isAcked() && chatType == ChatType.Chat) {
                    // 告知对方已读这条消息
		            EMClient.getInstance().chatManager().ackMessageRead(message.getFrom(), message.getMsgId());
		    }
			if (!message.isListened() && iv_read_status != null && iv_read_status.getVisibility() == View.VISIBLE) {
				// 隐藏自己未播放这条语音消息的标志
				iv_read_status.setVisibility(View.INVISIBLE);
				message.setListened(true);
				EMClient.getInstance().chatManager().setMessageListened(message);
			}

		}

	} catch (Exception e) {
	    System.out.println();
	}
}
 
Example 19
Source File: ToastUtils.java    From AndroidAPS with GNU Affero General Public License v3.0 4 votes vote down vote up
private static void playSound(final Context ctx, final int soundID) {
    final MediaPlayer soundMP = MediaPlayer.create(ctx, soundID);
    soundMP.start();
    soundMP.setOnCompletionListener(MediaPlayer::release);
}
 
Example 20
Source File: LocAlarmService.java    From ownmdm with GNU General Public License v2.0 4 votes vote down vote up
/**
  * ring
  */
 private void ring() { 

 	Util.logDebug("ring()");
 	
 	AudioManager am = (AudioManager) this.getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
 	am.setStreamVolume(AudioManager.STREAM_MUSIC, am.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
 	
 	MediaPlayer mpSound = MediaPlayer.create(getApplicationContext(), R.raw.police); 

 	if (mpSound != null) {
   mpSound.setLooping(false);
   mpSound.start();
}    	
		
 }