Example usage for android.media MediaPlayer MediaPlayer

List of usage examples for android.media MediaPlayer MediaPlayer

Introduction

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

Prototype

public MediaPlayer() 

Source Link

Document

Default constructor.

Usage

From source file:org.cyanogenmod.theme.chooser.AudiblePreviewFragment.java

private MediaPlayer initAudibleMediaPlayer(AssetFileDescriptor afd, int type) throws IOException {
    MediaPlayer mp = mMediaPlayers.get(type);
    if (mp == null) {
        mp = new MediaPlayer();
        mMediaPlayers.put(type, mp);/* w  w w  . j  a  va  2s.c  o  m*/
    } else {
        mp.reset();
    }
    mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
    mp.prepare();
    mp.setOnCompletionListener(mPlayCompletionListener);
    return mp;
}

From source file:za.co.neilson.alarm.preferences.AlarmPreferencesActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // requestWindowFeature(Window.FEATURE_NO_TITLE);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    setContentView(R.layout.alarm_preferences);

    pref = getSharedPreferences("AppPref", MODE_PRIVATE);
    email = getIntent().getStringExtra("email");
    Log.d("? ???!!! ", "" + email);

    Bundle bundle = getIntent().getExtras();
    if (bundle != null && bundle.containsKey("alarm")) {
        setMathAlarm((Alarm) bundle.getSerializable("alarm"));
    } else {//  w  w  w.j  av a  2 s.  co m
        setMathAlarm(new Alarm());
    }
    if (bundle != null && bundle.containsKey("adapter")) {
        setListAdapter((AlarmPreferenceListAdapter) bundle.getSerializable("adapter"));
    } else {
        setListAdapter(new AlarmPreferenceListAdapter(this, getMathAlarm()));
    }

    getListView().setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> l, View v, int position, long id) {
            final AlarmPreferenceListAdapter alarmPreferenceListAdapter = (AlarmPreferenceListAdapter) getListAdapter();
            final AlarmPreference alarmPreference = (AlarmPreference) alarmPreferenceListAdapter
                    .getItem(position);

            AlertDialog.Builder alert;
            v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
            switch (alarmPreference.getType()) {
            case BOOLEAN:
                CheckedTextView checkedTextView = (CheckedTextView) v;
                boolean checked = !checkedTextView.isChecked();
                ((CheckedTextView) v).setChecked(checked);
                switch (alarmPreference.getKey()) {
                case ALARM_ACTIVE:
                    alarm.setAlarmActive(checked);
                    break;
                case ALARM_VIBRATE:
                    alarm.setVibrate(checked);
                    if (checked) {
                        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
                        vibrator.vibrate(1000);
                    }
                    break;
                }
                alarmPreference.setValue(checked);
                break;
            case STRING:

                alert = new AlertDialog.Builder(AlarmPreferencesActivity.this);

                alert.setTitle(alarmPreference.getTitle());
                // alert.setMessage(message);

                // Set an EditText view to get user input
                final EditText input = new EditText(AlarmPreferencesActivity.this);

                input.setText(alarmPreference.getValue().toString());

                alert.setView(input);
                alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        alarmPreference.setValue(input.getText().toString());

                        if (alarmPreference.getKey() == Key.ALARM_NAME) {
                            alarm.setAlarmName(alarmPreference.getValue().toString());
                        }

                        alarmPreferenceListAdapter.setMathAlarm(getMathAlarm());
                        alarmPreferenceListAdapter.notifyDataSetChanged();
                    }
                });
                alert.show();
                break;
            case LIST:
                alert = new AlertDialog.Builder(AlarmPreferencesActivity.this);

                alert.setTitle(alarmPreference.getTitle());
                // alert.setMessage(message);

                CharSequence[] items = new CharSequence[alarmPreference.getOptions().length];
                for (int i = 0; i < items.length; i++)
                    items[i] = alarmPreference.getOptions()[i];

                alert.setItems(items, new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (alarmPreference.getKey()) {
                        case ALARM_DIFFICULTY:
                            Alarm.Difficulty d = Alarm.Difficulty.values()[which];
                            alarm.setDifficulty(d);
                            break;
                        case ALARM_TONE:
                            alarm.setAlarmTonePath(alarmPreferenceListAdapter.getAlarmTonePaths()[which]);
                            if (alarm.getAlarmTonePath() != null) {
                                if (mediaPlayer == null) {
                                    mediaPlayer = new MediaPlayer();
                                } else {
                                    if (mediaPlayer.isPlaying())
                                        mediaPlayer.stop();
                                    mediaPlayer.reset();
                                }
                                try {
                                    // mediaPlayer.setVolume(1.0f, 1.0f);
                                    mediaPlayer.setVolume(0.2f, 0.2f);
                                    mediaPlayer.setDataSource(AlarmPreferencesActivity.this,
                                            Uri.parse(alarm.getAlarmTonePath()));
                                    mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
                                    mediaPlayer.setLooping(false);
                                    mediaPlayer.prepare();
                                    mediaPlayer.start();

                                    // Force the mediaPlayer to stop after 3
                                    // seconds...
                                    if (alarmToneTimer != null)
                                        alarmToneTimer.cancel();
                                    alarmToneTimer = new CountDownTimer(3000, 3000) {
                                        @Override
                                        public void onTick(long millisUntilFinished) {

                                        }

                                        @Override
                                        public void onFinish() {
                                            try {
                                                if (mediaPlayer.isPlaying())
                                                    mediaPlayer.stop();
                                            } catch (Exception e) {

                                            }
                                        }
                                    };
                                    alarmToneTimer.start();
                                } catch (Exception e) {
                                    try {
                                        if (mediaPlayer.isPlaying())
                                            mediaPlayer.stop();
                                    } catch (Exception e2) {

                                    }
                                }
                            }
                            break;
                        default:
                            break;
                        }
                        alarmPreferenceListAdapter.setMathAlarm(getMathAlarm());
                        alarmPreferenceListAdapter.notifyDataSetChanged();
                    }

                });

                alert.show();
                break;
            case MULTIPLE_LIST:
                alert = new AlertDialog.Builder(AlarmPreferencesActivity.this);

                alert.setTitle(alarmPreference.getTitle());
                // alert.setMessage(message);

                CharSequence[] multiListItems = new CharSequence[alarmPreference.getOptions().length];
                for (int i = 0; i < multiListItems.length; i++)
                    multiListItems[i] = alarmPreference.getOptions()[i];

                boolean[] checkedItems = new boolean[multiListItems.length];
                for (Alarm.Day day : getMathAlarm().getDays()) {
                    checkedItems[day.ordinal()] = true;
                }
                alert.setMultiChoiceItems(multiListItems, checkedItems, new OnMultiChoiceClickListener() {

                    @Override
                    public void onClick(final DialogInterface dialog, int which, boolean isChecked) {

                        Alarm.Day thisDay = Alarm.Day.values()[which];

                        if (isChecked) {
                            alarm.addDay(thisDay);
                        } else {
                            // Only remove the day if there are more than 1
                            // selected
                            if (alarm.getDays().length > 1) {
                                alarm.removeDay(thisDay);
                            } else {
                                // If the last day was unchecked, re-check
                                // it
                                ((AlertDialog) dialog).getListView().setItemChecked(which, true);
                            }
                        }

                    }
                });
                alert.setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        alarmPreferenceListAdapter.setMathAlarm(getMathAlarm());
                        alarmPreferenceListAdapter.notifyDataSetChanged();

                    }
                });
                alert.show();
                break;
            case TIME:
                TimePickerDialog timePickerDialog = new TimePickerDialog(AlarmPreferencesActivity.this,
                        new OnTimeSetListener() {

                            @Override
                            public void onTimeSet(TimePicker timePicker, int hours, int minutes) {
                                Calendar newAlarmTime = Calendar.getInstance();
                                newAlarmTime.set(Calendar.HOUR_OF_DAY, hours);
                                newAlarmTime.set(Calendar.MINUTE, minutes);
                                newAlarmTime.set(Calendar.SECOND, 0);
                                alarm.setAlarmTime(newAlarmTime);
                                alarmPreferenceListAdapter.setMathAlarm(getMathAlarm());
                                alarmPreferenceListAdapter.notifyDataSetChanged();
                            }
                        }, alarm.getAlarmTime().get(Calendar.HOUR_OF_DAY),
                        alarm.getAlarmTime().get(Calendar.MINUTE), true);
                timePickerDialog.setTitle(alarmPreference.getTitle());
                timePickerDialog.show();
            default:
                break;
            }
        }
    });
}

From source file:com.andryr.musicplayer.PlaybackService.java

@Override
public void onCreate() {
    super.onCreate();
    mStatePrefs = getSharedPreferences(STATE_PREFS_NAME, MODE_PRIVATE);

    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    mMediaPlayer = new MediaPlayer();
    mMediaPlayer.setOnCompletionListener(this);
    mMediaPlayer.setOnErrorListener(this);
    mMediaPlayer.setOnPreparedListener(this);
    mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

    Intent i = new Intent(this, AudioEffectsReceiver.class);
    i.setAction(AudioEffectsReceiver.ACTION_OPEN_AUDIO_EFFECT_SESSION);
    i.putExtra(AudioEffectsReceiver.EXTRA_AUDIO_SESSION_ID, mMediaPlayer.getAudioSessionId());
    sendBroadcast(i);//from  w w  w . j  av  a  2  s .c  om

    IntentFilter receiverFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
    registerReceiver(mHeadsetStateReceiver, receiverFilter);

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    mAutoPause = prefs.getBoolean(PREF_AUTO_PAUSE, false);

    initTelephony();

    restoreState();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        setupMediaSession();
    }

}

From source file:com.devwang.logcabin.LogCabinMainActivity.java

@SuppressLint("NewApi")
@Override//from   w  ww.  ja  va  2 s . c  o  m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (D)
        Log.e(TAG, "+++ ON CREATE +++");
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // 
    isFirstInstallApp();
    diyTitle();
    viewInit();

    mTitleLeft.setText(R.string.app_name);//  
    soundMediaPlayer = new MediaPlayer();//  
    autoeditTextView.setAdapter(
            new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, autoedit_items));
    // appid http://open.voicecloud.cn/ appid:54202a57
    rd = new RecognizerDialog(this, getString(R.string.str_devwang_voice_key_appid));
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    isSupportBT();
    isNonConnBt();

    mLogCabinInfo = new LogCabinInfo("", "", "", "", "", "", "", "",
            "", "", "");

}

From source file:com.kasungunathilaka.sarigama.service.PlayerService.java

public void next() {
    try {//from  w w  w.  j a  va 2s .  c  om
        setupNotification(null, HomeActivity.NOTIFICATION_TYPE_DISMISS);
        int position = playerQueue.getCurrentPosition();
        slavePlayer = new MediaPlayer();
        slavePlayer.setOnPreparedListener(this);
        slavePlayer.setOnErrorListener(this);
        slavePlayer.setOnCompletionListener(this);
        if (playerQueue.hasPosition((position + 1))) {
            localBroadcastManager.sendBroadcast(new Intent(HomeActivity.ON_PREPARING));
            playerQueue.setCurrentPosition((position + 1));
            Song currentSong = playerQueue.getSongByPosition((position + 1));
            if (currentSong.getSongSource() == null) {
                getSongData(playerQueue.getCurrentPosition());
            } else {
                slavePlayer.setDataSource(currentSong.getSongSource());
                slavePlayer.prepareAsync();
            }
        } else if (parentLoop) {
            localBroadcastManager.sendBroadcast(new Intent(HomeActivity.ON_PREPARING));
            playerQueue.setCurrentPosition(0);
            Song currentSong = playerQueue.getSongByPosition(0);
            if (currentSong.getSongSource() == null) {
                getSongData(playerQueue.getCurrentPosition());
            } else {
                slavePlayer.setDataSource(currentSong.getSongSource());
                slavePlayer.prepareAsync();
            }
        } else {
            localBroadcastManager.sendBroadcast(new Intent(HomeActivity.ON_COMPLETED));
            localBroadcastManager.sendBroadcast(new Intent(HomeActivity.ON_QUEUE_COMPLETED));
            this.seekTo(0);
            mainPlayer.stop();
            mainPlayer.release();
            mainPlayer = null;
            slavePlayer = null;
            playerQueue.setCurrentPosition(0);
            Toast.makeText(PlayerService.this, "Song queue end reached", Toast.LENGTH_SHORT).show();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:co.shunya.gita.player.MusicService.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.
 *//*from w ww  .  j av  a  2s. c o  m*/
void createMediaPlayerIfNeeded() {
    if (mPlayer == null) {
        mPlayer = 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.
        //
        // Remember that to use this, we have to declare the android.permission.WAKE_LOCK
        // permission in AndroidManifest.xml.
        mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);

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

From source file:org.fdroid.enigtext.notifications.MessageNotifier.java

private static void sendInThreadNotification(Context context) {
    try {//from   w w  w .  j av a  2 s  .  c om
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);

        if (!sp.getBoolean(ApplicationPreferencesActivity.IN_THREAD_NOTIFICATION_PREF, true)) {
            return;
        }

        String ringtone = sp.getString(ApplicationPreferencesActivity.RINGTONE_PREF, null);

        if (ringtone == null)
            return;

        Uri uri = Uri.parse(ringtone);
        MediaPlayer player = new MediaPlayer();
        player.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
        player.setDataSource(context, uri);
        player.setLooping(false);
        player.setVolume(0.25f, 0.25f);
        player.prepare();

        final AudioManager audioManager = ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE));

        audioManager.requestAudioFocus(null, AudioManager.STREAM_NOTIFICATION,
                AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);

        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                audioManager.abandonAudioFocus(null);
            }
        });

        player.start();
    } catch (IOException ioe) {
        Log.w("MessageNotifier", ioe);
    }
}

From source file:com.nd.android.u.square.service.MusicPlaybackService.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.
 *///from  www  .ja v  a 2s  .co  m
void createMediaPlayerIfNeeded() {
    if (mPlayer == null) {
        mPlayer = 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.
        //
        // Remember that to use this, we have to declare the android.permission.WAKE_LOCK
        // permission in AndroidManifest.xml.
        mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);

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

From source file:org.y20k.transistor.PlayerService.java

private void initializeMediaPlayer() {
    mMediaPlayer = new MediaPlayer();
    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mMediaPlayer.setOnPreparedListener(this);
    mMediaPlayer.setOnErrorListener(this);
    mMediaPlayer.setOnInfoListener(this);
    mMediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
        @Override/*from   ww  w.j  a  va2  s .  c  o  m*/
        public void onBufferingUpdate(MediaPlayer mp, int percent) {
            Log.v(LOG_TAG, "Buffering: " + percent);
        }
    });

    try {
        mMediaPlayer.setDataSource(mStreamURL);
        mMediaPlayer.prepareAsync();
        Log.v(LOG_TAG, "setting: " + mStreamURL);
    } catch (IllegalArgumentException | IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.polyvi.xface.extension.capture.MediaType.java

/**
 *  audio  video ./*from  w  ww. jav  a2s  .com*/
 *
 * @param fileAbsPath ?
 * @param obj ?
 * @param isVideo ? video
 * @return ? JSONObject
 * @throws JSONException
 */
private JSONObject getAudioVideoData(String fileAbsPath, JSONObject obj, boolean isVideo) throws JSONException {
    MediaPlayer player = new MediaPlayer();
    try {
        player.setDataSource(fileAbsPath);
        player.prepare();
        obj.put(PROP_DURATION, player.getDuration() / XConstant.MILLISECONDS_PER_SECOND);
        if (isVideo) {
            obj.put(PROP_HEIGHT, player.getVideoHeight());
            obj.put(PROP_WIDTH, player.getVideoWidth());
        }
    } catch (IOException e) {
        XLog.e(CLASS_NAME, "Error: loading video file");
    }
    player.release();
    return obj;
}