Example usage for android.media MediaPlayer setOnCompletionListener

List of usage examples for android.media MediaPlayer setOnCompletionListener

Introduction

In this page you can find the example usage for android.media MediaPlayer setOnCompletionListener.

Prototype

public void setOnCompletionListener(OnCompletionListener listener) 

Source Link

Document

Register a callback to be invoked when the end of a media source has been reached during playback.

Usage

From source file:com.android.onemedia.playback.LocalRenderer.java

private boolean preparePlayer(final MediaPlayer player, boolean current) {
    player.setOnPreparedListener(this);
    player.setOnBufferingUpdateListener(this);
    player.setOnCompletionListener(this);
    player.setOnErrorListener(this);
    try {//  w  w w  . j  a  v a2  s.co m
        player.prepareAsync();
        if (current) {
            setState(STATE_PREPARING);
        }
    } catch (IllegalStateException e) {
        if (current) {
            setError(Listener.ERROR_PREPARE_ERROR, 0, null, e);
        }
        return false;
    }
    return true;
}

From source file:hku.fyp14017.blencode.ui.controller.SoundController.java

public void handlePlaySoundButton(View view, ArrayList<SoundInfo> soundInfoList, MediaPlayer mediaPlayer,
        final SoundBaseAdapter adapter) {
    final int position = (Integer) view.getTag();
    final SoundInfo soundInfo = soundInfoList.get(position);

    stopSound(mediaPlayer, soundInfoList);
    if (!soundInfo.isPlaying) {
        startSound(soundInfo, mediaPlayer);
        adapter.notifyDataSetChanged();//from   w  w  w. java2  s.co  m
    }

    mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaplayer) {
            soundInfo.isPlaying = false;
            adapter.notifyDataSetChanged();
        }
    });
}

From source file:com.yohpapa.research.simplemusicplayer.PlaybackService.java

private MediaPlayer initializePlayer() {
    MediaPlayer player = new MediaPlayer();
    player.setAudioStreamType(AudioManager.STREAM_MUSIC);
    player.setOnPreparedListener(this);
    player.setOnCompletionListener(this);
    player.setOnErrorListener(this);
    player.setOnSeekCompleteListener(this);
    player.setWakeMode(this, PowerManager.PARTIAL_WAKE_LOCK);

    IntentFilter filter = new IntentFilter();
    filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    filter.addAction(Intent.ACTION_HEADSET_PLUG);
    filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
    filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
    registerReceiver(audioOutputChangedEventReceiver, filter);

    return player;
}

From source file:de.dcja.prettygreatmusicplayer.MusicPlaybackService.java

@Override
public synchronized void onCreate() {
    Log.i(TAG, "Music Playback Service Created!");
    isRunning = true;/*  ww  w.jav  a 2  s .co m*/
    sharedPref = PreferenceManager.getDefaultSharedPreferences(this);

    powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "PGMPWakeLock");

    random = new Random();

    mp = new MediaPlayer();
    mReadaheadThread = new ReadaheadThread();

    mp.setOnCompletionListener(new OnCompletionListener() {

        @Override
        public void onCompletion(MediaPlayer mp) {
            Log.i(TAG, "Song complete");
            next();
        }

    });

    onDemandMediaMetadataRetriever = new OnDemandMediaMetadataRetriever();

    // https://developer.android.com/training/managing-audio/audio-focus.html
    audioFocusListener = new PrettyGoodAudioFocusChangeListener();

    // Get permission to play audio
    am = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);

    HandlerThread thread = new HandlerThread("ServiceStartArguments");
    thread.start();

    // Get the HandlerThread's Looper and use it for our Handler
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);

    // https://stackoverflow.com/questions/19474116/the-constructor-notification-is-deprecated
    // https://stackoverflow.com/questions/6406730/updating-an-ongoing-notification-quietly/15538209#15538209
    Intent resultIntent = new Intent(this, NowPlaying.class);
    resultIntent.putExtra("From_Notification", true);

    // Use the FLAG_ACTIVITY_CLEAR_TOP to prevent launching a second
    // NowPlaying if one already exists.
    resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, resultIntent, 0);

    Builder builder = new NotificationCompat.Builder(this.getApplicationContext());

    String contentText = getResources().getString(R.string.ticker_text);
    if (songFile != null) {
        contentText = Utils.getPrettySongName(songFile);
    }

    Notification notification = builder.setContentText(contentText).setSmallIcon(R.drawable.ic_pgmp_launcher)
            .setWhen(System.currentTimeMillis()).setContentIntent(pendingIntent)
            .setContentTitle(getResources().getString(R.string.notification_title)).build();

    startForeground(uniqueid, notification);

    timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            onTimerTick();
        }
    }, 0, 500L);

    Log.i(TAG, "Registering event receiver");
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    // Apparently audio registration is persistent across lots of things...
    // restarts, installs, etc.
    mAudioManager.registerMediaButtonEventReceiver(cn);
    // I tried to register this in the manifest, but it doesn't seen to
    // accept it, so I'll do it this way.
    getApplicationContext().registerReceiver(receiver, filter);

    headphoneReceiver = new HeadphoneBroadcastReceiver();
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("android.intent.action.HEADSET_PLUG");
    registerReceiver(headphoneReceiver, filter);
}

From source file:com.smithdtyler.prettygoodmusicplayer.MusicPlaybackService.java

@Override
public synchronized void onCreate() {
    Log.i(TAG, "Music Playback Service Created!");
    isRunning = true;// w w  w  .j a v  a  2 s  .c  o  m
    sharedPref = PreferenceManager.getDefaultSharedPreferences(this);

    powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "PGMPWakeLock");

    random = new Random();

    mp = new MediaPlayer();
    mReadaheadThread = new ReadaheadThread();

    mp.setOnCompletionListener(new OnCompletionListener() {

        @Override
        public void onCompletion(MediaPlayer mp) {
            Log.i(TAG, "Song complete");
            next();
        }

    });

    // https://developer.android.com/training/managing-audio/audio-focus.html
    audioFocusListener = new PrettyGoodAudioFocusChangeListener();

    // Get permission to play audio
    am = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);

    HandlerThread thread = new HandlerThread("ServiceStartArguments");
    thread.start();

    // Get the HandlerThread's Looper and use it for our Handler
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);

    // https://stackoverflow.com/questions/19474116/the-constructor-notification-is-deprecated
    // https://stackoverflow.com/questions/6406730/updating-an-ongoing-notification-quietly/15538209#15538209
    Intent resultIntent = new Intent(this, NowPlaying.class);
    resultIntent.putExtra("From_Notification", true);
    resultIntent.putExtra(AlbumList.ALBUM_NAME, album);
    resultIntent.putExtra(ArtistList.ARTIST_NAME, artist);
    resultIntent.putExtra(ArtistList.ARTIST_ABS_PATH_NAME, artistAbsPath);

    // Use the FLAG_ACTIVITY_CLEAR_TOP to prevent launching a second
    // NowPlaying if one already exists.
    resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, resultIntent, 0);

    Builder builder = new NotificationCompat.Builder(this.getApplicationContext());

    String contentText = getResources().getString(R.string.ticker_text);
    if (songFile != null) {
        contentText = Utils.getPrettySongName(songFile);
    }

    Notification notification = builder.setContentText(contentText).setSmallIcon(R.drawable.ic_pgmp_launcher)
            .setWhen(System.currentTimeMillis()).setContentIntent(pendingIntent)
            .setContentTitle(getResources().getString(R.string.notification_title)).build();

    startForeground(uniqueid, notification);

    timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            onTimerTick();
        }
    }, 0, 500L);

    Log.i(TAG, "Registering event receiver");
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    // Apparently audio registration is persistent across lots of things...
    // restarts, installs, etc.
    mAudioManager.registerMediaButtonEventReceiver(cn);
    // I tried to register this in the manifest, but it doesn't seen to
    // accept it, so I'll do it this way.
    getApplicationContext().registerReceiver(receiver, filter);

    headphoneReceiver = new HeadphoneBroadcastReceiver();
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("android.intent.action.HEADSET_PLUG");
    registerReceiver(headphoneReceiver, filter);
}

From source file:com.eggwall.SoundSleep.AudioService.java

/**
 * Try getting music from the [sdcard]/music/sleeping
 * @return a valid media player if we can play from it. Returns null if we didn't find music, or we can't play
 * custom music for any reason./*w w w. ja va  2 s  .co  m*/
 */
private MediaPlayer tryStartingMusic() {
    final MediaPlayer player = getGenericMediaPlayer();
    // Try to open the SD card and read from there. If nothing is found, play the
    // default music.
    final int nextPosition = nextTrackFromCard();
    if (nextPosition == INVALID_POSITION) {
        return null;
    }
    // Play files, not resources. Play the music file given here.
    final String file = mMusicDir.getAbsolutePath() + File.separator + mFilenames[nextPosition];
    Log.d(TAG, "Now playing " + file);
    try {
        player.setDataSource(file);
    } catch (IOException e) {
        Log.e(TAG, "Could not create a media player instance. Full error below.");
        e.printStackTrace();
        return null;
    }
    player.setOnCompletionListener(this);
    // Play this song, and a different one when done.
    player.setLooping(false);
    return player;
}

From source file:de.bogutzky.psychophysiocollector.app.MainActivity.java

private void playSound(int soundID) {
    MediaPlayer mediaPlayer = MediaPlayer.create(this, soundID);
    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override//from w ww.j a  v  a 2 s . co m
        public void onCompletion(MediaPlayer mp) {
            mp.release();
        }
    });
    mediaPlayer.start();
}

From source file:com.bayapps.android.robophish.playback.LocalPlayback.java

/**
 * Makes sure the media player exists and has been reset. This will create
 * the media player if needed, or reset the existing media player if one
 * already exists./* w ww  .j a  v  a  2s . c  om*/
 */
private MediaPlayer createMediaPlayer(MediaPlayer player) {
    LogHelper.d(TAG, "createMediaPlayerIfNeeded. needed? ", (player == null));
    if (player == null) {
        player = new MediaPlayer();

        // Make sure the media player will acquire a wake-lock while
        // playing. If we don't do that, the CPU might go to sleep while the
        // song is playing, causing playback to stop.
        player.setWakeMode(mContext.getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);

        // we want the media player to notify us when it's ready preparing,
        // and when it's done playing:
        player.setOnPreparedListener(this);
        player.setOnCompletionListener(this);
        player.setOnErrorListener(this);
        player.setOnSeekCompleteListener(this);
    } else {
        player.reset();
    }

    return player;
}

From source file:com.squalala.talkiewalkie.ui.activities.TalkActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_talk);
    ButterKnife.bind(this);

    connectedUserFragment = new ConnectedUserFragment();
    settingsFragment = new SettingsFragment();

    messageAdapter = new MessageAdapter(messages, new OnClickMessageListener() {
        @Override/*from  w w  w  . jav a 2 s .  c  o m*/
        public void onClickMessage(Message message) {
            message.setRead(false);
            recyclerView.getAdapter().notifyDataSetChanged();
            mMessages.add(message);
            playAudios();
        }
    });

    linearLayoutManager = new LinearLayoutManager(this);
    linearLayoutManager.setStackFromEnd(true);
    recyclerView.setLayoutManager(linearLayoutManager);
    recyclerView.setAdapter(messageAdapter);

    progressView.setVisibility(View.VISIBLE);
    btnUserOnline.setVisibility(View.GONE);
    txtWhatHappen.setVisibility(View.GONE);
    //    txtNumberUsers.setVisibility(View.GONE);
    txtWhoSpeak.setVisibility(View.GONE);

    session = ((App) getApplication()).getSession();
    mSocket = ((App) getApplication()).getSocket();
    mSocket.on(Socket.EVENT_CONNECT, onConnect);
    mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect);
    mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
    mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
    mSocket.on(KEY_NEW_MESSAGE, onNewMessage);
    mSocket.on(KEY_JOIN_ROOM, onJoinRoom);
    mSocket.on(KEY_LEFT_ROOM, onLeftRoom);
    mSocket.on(KEY_NUMBER_USERS, onNumberUsers);
    mSocket.on(KEY_CONNECTED_USERS, onConnectedUsers);

    mSocket.connect();
    /*
            if (session.isBeep())
    iconBeep.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_volume_up_black_48dp));
            else
    iconBeep.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_volume_off_black_48dp));  */

    amanager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);

    //   int maxVolume = amanager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);

    //  System.out.println("Max volume " + maxVolume);
    //  System.out.println("session Max volume " + session.getSoundVolume());
    amanager.setStreamVolume(AudioManager.STREAM_MUSIC, session.getSoundVolume(amanager), 0);

    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayerForBeep.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);

    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @DebugLog
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            viewAvatar.setVisibility(View.GONE);
            //  pulsator.stop();

            if (session.isAutomaticPlay())
                playAudios();
        }
    });

    mIvVoiceIndicators = new ArrayList<>();
    mIvVoiceIndicators.add(ButterKnife.<ImageView>findById(this, R.id.mIvVoiceIndicator1));
    mIvVoiceIndicators.add(ButterKnife.<ImageView>findById(this, R.id.mIvVoiceIndicator2));
    mIvVoiceIndicators.add(ButterKnife.<ImageView>findById(this, R.id.mIvVoiceIndicator3));
    mIvVoiceIndicators.add(ButterKnife.<ImageView>findById(this, R.id.mIvVoiceIndicator4));
    mIvVoiceIndicators.add(ButterKnife.<ImageView>findById(this, R.id.mIvVoiceIndicator5));
    mIvVoiceIndicators.add(ButterKnife.<ImageView>findById(this, R.id.mIvVoiceIndicator6));
    mIvVoiceIndicators.add(ButterKnife.<ImageView>findById(this, R.id.mIvVoiceIndicator7));

    mAudioRecorder = AudioRecorder.getInstance();
    mRxAudioPlayer = RxAudioPlayer.getInstance();
    mAudioRecorder.setOnErrorListener(this);

    btnSpeak.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                press2Record();
                break;
            case MotionEvent.ACTION_UP:
                release2Send();
                break;
            case MotionEvent.ACTION_CANCEL:
                release2Send();
                break;
            default:
                break;
            }

            return true;
        }
    });
}

From source file:org.sirimangalo.meditationplus.ActivityMain.java

private void populateChat(JSONArray chats, boolean admin) {
    if (findViewById(R.id.chat_list) == null)
        return;/*from   w w w .j ava 2s.  c o m*/
    chatList = (ListView) findViewById(R.id.chat_list);

    int newChatNo = 0;

    int latestChatTime = 0;
    ArrayList<JSONObject> chatArray = new ArrayList<JSONObject>();

    if (chats.length() < lastChatArray.size()) { // prepend old chats
        for (int i = chats.length(); i < lastChatArray.size(); i++) {
            chatArray.add(lastChatArray.get(i));
        }
    }

    for (int i = 0; i < chats.length(); i++) {
        try {
            JSONObject chat = chats.getJSONObject(i);
            latestChatTime = Integer.parseInt(chat.getString("time"));
            if (latestChatTime > lastChatTime)
                newChatNo++;

            chatArray.add(chat);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    lastChatArray = chatArray;

    if (latestChatTime < lastChatTime)
        newChatNo = -1;

    if (admin)
        chatList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                String cid = (String) view.findViewById(R.id.message).getTag();
                ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
                doSubmit("delchat_" + cid, nvp, true);
                return true;
            }
        });

    // save index and top position
    int index = chatList.getFirstVisiblePosition();
    View v = chatList.getChildAt(0);
    int top = (v == null) ? 0 : v.getTop();

    AdapterChat adapter = new AdapterChat(this, R.layout.list_item_chat, chatArray);
    chatList.setAdapter(adapter);

    // restore index and position

    if (doChatScroll) {
        chatList.setSelection(adapter.getCount() - 1);
        doChatScroll = false;
    } else
        chatList.setSelectionFromTop(index, top);

    if (newChatNo > 0) {
        if (currentPosition != 1 && lastChatTime > 0) {
            final MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.tick);
            mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    mp.release();
                }
            });
            mp.start();
            newChats = true;
            ActionBar actionBar = getSupportActionBar();
            if (actionBar.getTabAt(1) != null)
                actionBar.getTabAt(1).setText(
                        Html.fromHtml(getString(R.string.title_section2).toUpperCase(Locale.getDefault()) + " ("
                                + newChatNo + ")"));
        }
    }
    lastChatTime = latestChatTime;
}