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

The following examples show how to use android.media.MediaPlayer#setOnCompletionListener() . 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: OBAudioPlayer.java    From GLEXP-Team-onebillion with Apache License 2.0 6 votes vote down vote up
public void startPlaying (AssetFileDescriptor afd)
{
    synchronized (this)
    {
        if (isPlaying())
            stopPlaying(true);
        fromTime = -1;
        player = new MediaPlayer();
        player.setOnPreparedListener(this);
        player.setOnCompletionListener(this);
        try
        {
            state = OBAP_PREPARING;
            player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            player.prepareAsync();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            setState(OBAP_IDLE);
            return;
        }
    }
}
 
Example 2
Source File: AudioPlayerService.java    From Dashchan with Apache License 2.0 6 votes vote down vote up
private void initAndPlayAudio(File file) {
	audioFile = file;
	pausedByTransientLossOfFocus = false;
	mediaPlayer = new MediaPlayer();
	mediaPlayer.setLooping(false);
	mediaPlayer.setOnCompletionListener(this);
	mediaPlayer.setOnErrorListener(this);
	try {
		mediaPlayer.setDataSource(file.getPath());
		mediaPlayer.prepare();
	} catch (Exception e) {
		audioFile.delete();
		CacheManager.getInstance().handleDownloadedFile(audioFile, false);
		ToastUtils.show(context, R.string.message_playback_error);
		cleanup();
		stopSelf();
		sendToActivity(ACTION_CANCEL);
		return;
	}
	play(true);
	refreshPlaybackNotification(true);
}
 
Example 3
Source File: BeepManager.java    From qrcode_android with GNU Lesser General Public License v3.0 6 votes vote down vote up
private MediaPlayer buildMediaPlayer(Context activity) {
    MediaPlayer mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setOnCompletionListener(this);
    mediaPlayer.setOnErrorListener(this);
    try {
        AssetFileDescriptor file = activity.getResources().openRawResourceFd(R.raw.beep);
        try {
            mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
        } finally {
            file.close();
        }
        mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
        mediaPlayer.prepare();
        return mediaPlayer;
    } catch (IOException ioe) {
        Log.w(TAG, ioe);
        mediaPlayer.release();
        return null;
    }
}
 
Example 4
Source File: MNViderPlayer.java    From MNVideoPlayer with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void surfaceCreated(SurfaceHolder holder) {
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setDisplay(holder); // 添加到容器中
    //播放完成的监听
    mediaPlayer.setOnCompletionListener(this);
    // 异步准备的一个监听函数,准备好了就调用里面的方法
    mediaPlayer.setOnPreparedListener(this);
    //播放错误的监听
    mediaPlayer.setOnErrorListener(this);
    mediaPlayer.setOnBufferingUpdateListener(this);
    //第一次初始化需不需要主动播放
    if (isFirstPlay) {
        playVideo(videoPath, videoTitle);
    }
    isFirstPlay = true;
}
 
Example 5
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 6
Source File: VideoViewerActivity.java    From CameraV with GNU General Public License v3.0 6 votes vote down vote up
private void playVideo(Uri uri) {
doCleanUp();
try {


  // Create a new media player and set the listeners
  mMediaPlayer = new MediaPlayer();
  mMediaPlayer.setDataSource(this, uri);
  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);
}
}
 
Example 7
Source File: MediaPlayerImpl.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
public MediaPlayerImpl(Context context, PlayerAttributes attributes) {
    super(context, attributes);
    synchronized (LOCK) {
        mPlayer = new MediaPlayer();
    }
    mContext = context.getApplicationContext();
    mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

    mPlayer.setOnCompletionListener(this);
    mPlayer.setOnErrorListener(this);
    mPlayer.setOnInfoListener(this);
    mPlayer.setOnPreparedListener(this);
    mPlayer.setOnSeekCompleteListener(this);
    mPlayer.setOnVideoSizeChangedListener(this);
    mPlayer.setOnBufferingUpdateListener(this);
}
 
Example 8
Source File: AudioPlayer.java    From GSYRecordWave with Apache License 2.0 6 votes vote down vote up
/**
 * 音频播放器
 *
 * @param context 上下文
 * @param handler 音频状态handler
 */
public AudioPlayer(Context context, Handler handler) {
    super();
    this.mRemoteHandler = handler;
    try {
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);// 设置媒体流类型
        mMediaPlayer.setOnBufferingUpdateListener(this);
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.setOnCompletionListener(this);
        mMediaPlayer.setOnErrorListener(this);
        mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 9
Source File: BeepManager.java    From android-apps with MIT License 6 votes vote down vote up
private static MediaPlayer buildMediaPlayer(Context activity) {
  MediaPlayer mediaPlayer = new MediaPlayer();
  mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
  // When the beep has finished playing, rewind to queue up another one.
  mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    
    public void onCompletion(MediaPlayer player) {
      player.seekTo(0);
    }
  });

  AssetFileDescriptor file = activity.getResources().openRawResourceFd(R.raw.beep);
  try {
    mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
    file.close();
    mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
    mediaPlayer.prepare();
  } catch (IOException ioe) {
    Log.w(TAG, ioe);
    mediaPlayer = null;
  }
  return mediaPlayer;
}
 
Example 10
Source File: MusicService.java    From mobile-manager-tool with MIT License 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    try {
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnCompletionListener(this);
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);// 设置媒体流类型
        mediaPlayer.setOnBufferingUpdateListener(this);
        mediaPlayer.setOnPreparedListener(this);
    } catch (Exception e) {
        e.printStackTrace();
    }
    IntentFilter commandFilter = new IntentFilter();
    commandFilter.addAction(ActionManager.ACTION_MUSIC_PLAY);
    commandFilter.addAction(ActionManager.ACTION_MUSIC_PAUSE);
    commandFilter.addAction(ActionManager.ACTION_MUSIC_PREVIOUS_PLAY);
    commandFilter.addAction(ActionManager.ACTION_MUSIC_NEXT_PLAY);
    commandFilter.addAction(ActionManager.ACTION_MUSIC_STOP_TRACKING);
    commandFilter.addAction(ActionManager.ACTION_MUSIC_CLOSE_NOTIFICATION);

    registerReceiver(musicPlayReceiver, commandFilter);

    // 每一秒触发一次
    mTimer.schedule(timerTask, 0, 1000);

    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    musicService = this;
}
 
Example 11
Source File: OBAudioPlayer.java    From GLEXP-Team-onebillion with Apache License 2.0 5 votes vote down vote up
public OBAudioPlayer ()
{
    player = new MediaPlayer();
    playerLock = new ReentrantLock();
    condition = playerLock.newCondition();
    player.setOnPreparedListener(this);
    player.setOnCompletionListener(this);
    setState(OBAP_IDLE);
}
 
Example 12
Source File: FFmpegPreviewActivity.java    From FFmpegRecorder with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_ffmpeg_preview);

	cancelBtn = (Button) findViewById(R.id.play_cancel);
	cancelBtn.setOnClickListener(this);
	
	DisplayMetrics displaymetrics = new DisplayMetrics();
	getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
	surfaceView = (TextureView) findViewById(R.id.preview_video);
	
	RelativeLayout preview_video_parent = (RelativeLayout)findViewById(R.id.preview_video_parent);
	LayoutParams layoutParams = (LayoutParams) preview_video_parent
			.getLayoutParams();
	layoutParams.width = displaymetrics.widthPixels;
	layoutParams.height = displaymetrics.widthPixels;
	preview_video_parent.setLayoutParams(layoutParams);
	
	surfaceView.setSurfaceTextureListener(this);
	surfaceView.setOnClickListener(this);
	
	path = getIntent().getStringExtra("path");
	
	imagePlay = (ImageView) findViewById(R.id.previre_play);
	imagePlay.setOnClickListener(this);
	
	mediaPlayer = new MediaPlayer();
	mediaPlayer.setOnCompletionListener(this);
}
 
Example 13
Source File: GPlayer.java    From DroidDLNA with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.gplayer);
    mAudioManager = (AudioManager) getSystemService(Service.AUDIO_SERVICE);

    surfaceView = (SurfaceView) findViewById(R.id.gplayer_surfaceview);
    surfaceHolder = surfaceView.getHolder();
    surfaceHolder.addCallback(this);
    surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    mMediaPlayer = new MediaPlayer();

    mMediaPlayer.setOnCompletionListener(this);
    mMediaPlayer.setOnErrorListener(this);
    mMediaPlayer.setOnInfoListener(this);
    mMediaPlayer.setOnPreparedListener(this);
    mMediaPlayer.setOnSeekCompleteListener(this);
    mMediaPlayer.setOnVideoSizeChangedListener(this);

    initControl();

    Intent intent = getIntent();
    playURI = intent.getStringExtra("playURI");
    if (!TextUtils.isEmpty(playURI)) {
        setUri(playURI);
    }

    setTitle(intent);
    currentDisplay = getWindowManager().getDefaultDisplay();

    registerBrocast();
}
 
Example 14
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 15
Source File: VideoPlayTextureView.java    From FFmpegRecorder with GNU General Public License v3.0 5 votes vote down vote up
/**
 * ��ʼ������
 * @param context
 */
private void init(Context context) {
	mediaPlayer = new MediaPlayer();
	setSurfaceTextureListener(this);
	mediaPlayer.setOnCompletionListener(this);
	mediaPlayer.setOnPreparedListener(this);
}
 
Example 16
Source File: MediaManager.java    From a with GNU General Public License v3.0 5 votes vote down vote up
public static void playSilentSound(Context mContext) {
    try {
        // Stupid Android 8 "Oreo" hack to make media buttons work
        MediaPlayer mMediaPlayer = MediaPlayer.create(mContext, R.raw.silent_sound);
        mMediaPlayer.setOnCompletionListener(MediaPlayer::release);
        mMediaPlayer.start();
    } catch (Exception ignored) {
    }
}
 
Example 17
Source File: FragmentNotificationAndSoundViewModel.java    From iGap-Android with GNU Affero General Public License v3.0 4 votes vote down vote up
private void playSound(int which) {

        int musicId = R.raw.igap;

        switch (which) {
            case 0:
                musicId = R.raw.igap;
                break;
            case 1:
                musicId = R.raw.aooow;
                break;
            case 2:
                musicId = R.raw.bbalert;
                break;
            case 3:
                musicId = R.raw.boom;
                break;
            case 4:
                musicId = R.raw.bounce;
                break;
            case 5:
                musicId = R.raw.doodoo;
                break;
            case 6:
                musicId = R.raw.jing;
                break;
            case 7:
                musicId = R.raw.lili;
                break;
            case 8:
                musicId = R.raw.msg;
                break;
            case 9:
                musicId = R.raw.newa;
                break;
            case 10:
                musicId = R.raw.none;
                break;
            case 11:
                musicId = R.raw.onelime;
                break;
            case 12:
                musicId = R.raw.tone;
                break;
            case 13:
                musicId = R.raw.woow;
                break;
        }


        MediaPlayer mediaPlayer = MediaPlayer.create(G.fragmentActivity, musicId);
        mediaPlayer.start();

        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            public void onCompletion(MediaPlayer mp) {
                mp.release();
            }

            ;
        });

    }
 
Example 18
Source File: EaseChatRowVoicePlayClickListener.java    From nono-android with GNU General Public License v3.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: 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 20
Source File: MediaPlayerDemo_Video.java    From codeexamples-android with Eclipse Public License 1.0 4 votes vote down vote up
private void playVideo(Integer Media) {
    doCleanUp();
    try {

        switch (Media) {
            case LOCAL_VIDEO:
                /*
                 * TODO: Set the path variable to a local media file path.
                 */
                path = "";
                if (path == "") {
                    // Tell the user to provide a media file URL.
                    Toast
                            .makeText(
                                    MediaPlayerDemo_Video.this,
                                    "Please edit MediaPlayerDemo_Video Activity, "
                                            + "and set the path variable to your media file path."
                                            + " Your media file must be stored on sdcard.",
                                    Toast.LENGTH_LONG).show();

                }
                break;
            case STREAM_VIDEO:
                /*
                 * 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.
                 * 
                 */
                path = "";
                if (path == "") {
                    // Tell the user to provide a media file URL.
                    Toast
                            .makeText(
                                    MediaPlayerDemo_Video.this,
                                    "Please edit MediaPlayerDemo_Video Activity,"
                                            + " and set the path variable to your media file URL.",
                                    Toast.LENGTH_LONG).show();

                }

                break;


        }

        // 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);
    }
}