Example usage for android.media MediaPlayer create

List of usage examples for android.media MediaPlayer create

Introduction

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

Prototype

public static MediaPlayer create(Context context, int resid) 

Source Link

Document

Convenience method to create a MediaPlayer for a given resource id.

Usage

From source file:de.baumann.thema.FragmentSound.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.sound, container, false);

    setHasOptionsMenu(true);/*from   w  w  w  . j a v a  2  s. c om*/

    final String[] itemTITLE = {
            "Ouverture - Hymne" + " (Steven Testelin)" + " | " + getString(R.string.duration) + " 01:49",
            "Canon and Gigue in D major" + " | " + getString(R.string.duration) + "  00:45",
            "Epic" + " (Alexey Anisimov)" + " | " + getString(R.string.duration) + "  01:53",
            "Isn't it" + " | " + getString(R.string.duration) + " 00:01",
            "Jingle Bells Sms" + " | " + getString(R.string.duration) + " 00:04",
            "Wet" + " | " + getString(R.string.duration) + " 00:01", };

    final String[] itemURL = {
            Environment.getExternalStorageDirectory() + "/Android/data/de.baumann.thema/hymne.mp3",
            Environment.getExternalStorageDirectory() + "/Android/data/de.baumann.thema/canon.mp3",
            Environment.getExternalStorageDirectory() + "/Android/data/de.baumann.thema/epic.mp3",
            Environment.getExternalStorageDirectory() + "/Android/data/de.baumann.thema/isnt_it.mp3",
            Environment.getExternalStorageDirectory() + "/Android/data/de.baumann.thema/jingle_bells_sms.mp3",
            Environment.getExternalStorageDirectory() + "/Android/data/de.baumann.thema/wet.mp3", };

    final String[] itemDES = { "CC license: https://www.jamendo.com/track/1004091/ouverture-hymne",
            "CC license: https://musopen.org/music/2672/johann-pachelbel/canon-and-gigue-in-d-major/",
            "CC license: https://www.jamendo.com/track/1344095/epic",
            "CC license: https://notificationsounds.com/standard-ringtones/isnt-it-524",
            "CC license: https://notificationsounds.com/message-tones/jingle-bells-sms-523",
            "CC license: https://notificationsounds.com/notification-sounds/wet-431", };

    final String[] itemFN = { "hymne.mp3", "canon.mp3", "epic.mp3", "isnt_it.mp3", "jingle_bells_sms.mp3",
            "wet.mp3", };

    CustomListAdapter_Sound adapter = new CustomListAdapter_Sound(getActivity(), itemTITLE, itemURL, itemDES,
            itemDES);
    listView = (ListView) rootView.findViewById(R.id.bookmarks);
    listView.setAdapter(adapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // TODO Auto-generated method stub
            String Selecteditem = itemURL[+position];
            final MediaPlayer mp = MediaPlayer.create(getActivity(), Uri.parse(Selecteditem));
            mp.start();

            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    mp.stop();
                }
            }, 5000);
        }
    });

    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

            final String SelecteditemMes = itemTITLE[+position];
            final String Selecteditem = itemURL[+position];
            final String SelecteditemTitle = itemFN[+position];
            final String SelecteditemUrl = itemDES[+position].substring(12);
            final CharSequence[] options = { getString(R.string.set_ringtone),
                    getString(R.string.set_notification), getString(R.string.set_alarm),
                    getString(R.string.play), getString(R.string.open) };

            new AlertDialog.Builder(getActivity())
                    .setPositiveButton(R.string.cancel, new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int whichButton) {
                            dialog.cancel();
                        }
                    }).setItems(options, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int item) {

                            if (options[item].equals(getString(R.string.set_ringtone))) {

                                File directory_al = new File(
                                        Environment.getExternalStorageDirectory() + "/Ringtones/");
                                if (!directory_al.exists()) {
                                    directory_al.mkdirs();
                                }

                                try {

                                    InputStream in;
                                    OutputStream out;
                                    in = new FileInputStream(Selecteditem);
                                    out = new FileOutputStream(Environment.getExternalStorageDirectory()
                                            + "/Ringtones/" + SelecteditemTitle);

                                    byte[] buffer = new byte[1024];
                                    int read;
                                    while ((read = in.read(buffer)) != -1) {
                                        out.write(buffer, 0, read);
                                    }
                                    in.close();

                                    // write the output file
                                    out.flush();
                                    out.close();

                                    MediaScannerConnection.scanFile(getActivity(),
                                            new String[] { Environment.getExternalStorageDirectory()
                                                    + "/Ringtones/" + SelecteditemTitle },
                                            null, new MediaScannerConnection.OnScanCompletedListener() {
                                                @Override
                                                public void onScanCompleted(String path, Uri uri) {
                                                    Intent intent2 = new Intent(Settings.ACTION_SOUND_SETTINGS);
                                                    intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                                    getActivity().startActivity(intent2);
                                                }
                                            });

                                } catch (Exception e) {
                                    Log.e("tag", e.getMessage());
                                }

                            } else if (options[item].equals(getString(R.string.set_notification))) {

                                File directory_al = new File(
                                        Environment.getExternalStorageDirectory() + "/Notifications/");
                                if (!directory_al.exists()) {
                                    directory_al.mkdirs();
                                }

                                try {

                                    InputStream in;
                                    OutputStream out;
                                    in = new FileInputStream(Selecteditem);
                                    out = new FileOutputStream(Environment.getExternalStorageDirectory()
                                            + "/Notifications/" + SelecteditemTitle);

                                    byte[] buffer = new byte[1024];
                                    int read;
                                    while ((read = in.read(buffer)) != -1) {
                                        out.write(buffer, 0, read);
                                    }
                                    in.close();

                                    // write the output file
                                    out.flush();
                                    out.close();

                                    MediaScannerConnection.scanFile(getActivity(),
                                            new String[] { Environment.getExternalStorageDirectory()
                                                    + "/Notifications/" + SelecteditemTitle },
                                            null, new MediaScannerConnection.OnScanCompletedListener() {
                                                @Override
                                                public void onScanCompleted(String path, Uri uri) {
                                                    Intent intent2 = new Intent(Settings.ACTION_SOUND_SETTINGS);
                                                    intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                                    getActivity().startActivity(intent2);
                                                }
                                            });

                                } catch (Exception e) {
                                    Log.e("tag", e.getMessage());
                                }

                            } else if (options[item].equals(getString(R.string.set_alarm))) {

                                File directory_al = new File(
                                        Environment.getExternalStorageDirectory() + "/Alarms/");
                                if (!directory_al.exists()) {
                                    directory_al.mkdirs();
                                }

                                try {

                                    InputStream in;
                                    OutputStream out;
                                    in = new FileInputStream(Selecteditem);
                                    out = new FileOutputStream(Environment.getExternalStorageDirectory()
                                            + "/Alarms/" + SelecteditemTitle);

                                    byte[] buffer = new byte[1024];
                                    int read;
                                    while ((read = in.read(buffer)) != -1) {
                                        out.write(buffer, 0, read);
                                    }
                                    in.close();

                                    // write the output file
                                    out.flush();
                                    out.close();

                                    MediaScannerConnection.scanFile(getActivity(),
                                            new String[] { Environment.getExternalStorageDirectory()
                                                    + "/Alarms/" + SelecteditemTitle },
                                            null, new MediaScannerConnection.OnScanCompletedListener() {
                                                @Override
                                                public void onScanCompleted(String path, Uri uri) {
                                                    Snackbar.make(listView, R.string.set_alarm_suc,
                                                            Snackbar.LENGTH_LONG).show();
                                                }
                                            });

                                } catch (Exception e) {
                                    Log.e("tag", e.getMessage());
                                }

                                Snackbar.make(listView, getString(R.string.set_alarm_suc), Snackbar.LENGTH_LONG)
                                        .show();

                            } else if (options[item].equals(getString(R.string.play))) {
                                final MediaPlayer mp = MediaPlayer.create(getActivity(),
                                        Uri.parse(Selecteditem));

                                new AlertDialog.Builder(getActivity()).setTitle(getString(R.string.play))
                                        .setMessage(SelecteditemMes).setPositiveButton(R.string.cancel,
                                                new DialogInterface.OnClickListener() {

                                                    public void onClick(DialogInterface dialog,
                                                            int whichButton) {
                                                        mp.stop();
                                                        dialog.cancel();
                                                    }
                                                })
                                        .setOnCancelListener(new DialogInterface.OnCancelListener() {
                                            @Override
                                            public void onCancel(DialogInterface dialog) {
                                                mp.stop();
                                                dialog.cancel();
                                            }
                                        }).show();
                                mp.start();
                            } else if (options[item].equals(getString(R.string.open))) {
                                Uri uri = Uri.parse(SelecteditemUrl); // missing 'http://' will cause crashed
                                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                                startActivity(intent);
                            }
                        }
                    }).show();
            return true;
        }
    });

    return rootView;
}

From source file:com.cypress.cysmart.BLEServiceFragments.CapsenseServiceProximity.java

@Override
public void onResume() {
    super.onResume();

    player = MediaPlayer.create(getActivity(), R.raw.beep);
    valueIncreased = true;
}

From source file:at.wada811.app.fragment.VideoFragment.java

private void initMediaPlayer() {
    LogUtils.i();/*from w  w w .j  a v a  2 s. com*/
    if (getArguments().keySet().contains(KEY_RES_ID)) {
        mMediaPlayer = MediaPlayer.create(getActivity(), getArguments().getInt(KEY_RES_ID));
    } else {
        mMediaPlayer = new MediaPlayer();
    }
    mMediaPlayer.setOnVideoSizeChangedListener(this);
    mMediaPlayer.setOnBufferingUpdateListener(this);
    mMediaPlayer.setOnPreparedListener(this);
    mMediaPlayer.setOnCompletionListener(this);
    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mMediaPlayer.setOnInfoListener(new OnInfoListener() {
        @Override
        public boolean onInfo(MediaPlayer mp, int what, int extra) {
            switch (what) {
            case MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING:
                LogUtils.i("MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING");
                break;
            case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                LogUtils.i("MediaPlayer.MEDIA_INFO_BUFFERING_END");
                break;
            case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                LogUtils.i("MediaPlayer.MEDIA_INFO_BUFFERING_START");
                break;
            case MediaPlayer.MEDIA_INFO_METADATA_UPDATE:
                LogUtils.i("MediaPlayer.MEDIA_INFO_METADATA_UPDATE");
                break;
            case MediaPlayer.MEDIA_INFO_NOT_SEEKABLE:
                LogUtils.i("MediaPlayer.MEDIA_INFO_NOT_SEEKABLE");
                break;
            case MediaPlayer.MEDIA_INFO_SUBTITLE_TIMED_OUT:
                LogUtils.i("MediaPlayer.MEDIA_INFO_SUBTITLE_TIMED_OUT");
                break;
            case MediaPlayer.MEDIA_INFO_UNSUPPORTED_SUBTITLE:
                LogUtils.i("MediaPlayer.MEDIA_INFO_UNSUPPORTED_SUBTITLE");
                break;
            case MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:
                LogUtils.i("MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START");
                break;
            case MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING:
                LogUtils.i("MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING");
                break;
            case MediaPlayer.MEDIA_INFO_UNKNOWN:
            default:
                LogUtils.i("MediaPlayer.MEDIA_INFO_UNKNOWN");
                break;
            }
            LogUtils.d("extra: " + extra);
            return false;
        }
    });
    mMediaPlayer.setOnErrorListener(new OnErrorListener() {
        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            switch (what) {
            case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
                LogUtils.e("MediaPlayer.MEDIA_ERROR_SERVER_DIED");
                break;
            case MediaPlayer.MEDIA_ERROR_UNKNOWN:
            default:
                LogUtils.e("MediaPlayer.MEDIA_ERROR_UNKNOWN");
                break;
            }
            switch (extra) {
            case MediaPlayer.MEDIA_ERROR_IO:
                LogUtils.e("MediaPlayer.MEDIA_ERROR_IO");
                break;
            case MediaPlayer.MEDIA_ERROR_MALFORMED:
                LogUtils.e("MediaPlayer.MEDIA_ERROR_MALFORMED");
                break;
            case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
                LogUtils.e("MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK");
                break;
            case MediaPlayer.MEDIA_ERROR_TIMED_OUT:
                LogUtils.e("MediaPlayer.MEDIA_ERROR_TIMED_OUT");
                break;
            case MediaPlayer.MEDIA_ERROR_UNSUPPORTED:
                LogUtils.e("MediaPlayer.MEDIA_ERROR_UNSUPPORTED");
                break;
            default:
                LogUtils.e("extra: " + extra);
                break;
            }
            return false;
        }
    });
    mCallback.onActivityCreated(this);
}

From source file:de.quadrillenschule.azocamsynca.job.JobProcessor.java

public void processingLoop() {

    if (getRequestStatus() == ProcessorStatus.PAUSED) {
        setStatus(ProcessorStatus.PAUSED);
        return;//from w w  w  . j  a v a  2  s.  c  om
    }
    setStatus(ProcessorStatus.PROCESSING);
    TriggerPhotoSerie currentJobT = null;
    for (TriggerPhotoSerie j : jobs) {
        if (j.getTriggerStatus() != TriggerPhotoSerie.TriggerJobStatus.FINISHED_TRIGGERING) {
            currentJobT = j;
            if ((j.getTriggerStatus() == PhotoSerie.TriggerJobStatus.WAITFORUSER)
                    && ((alertDialog != null) && (alertDialog.isShowing()))) {
                return;
            }
            if ((j.getTriggerStatus() == PhotoSerie.TriggerJobStatus.WAITFORUSER)) {
                currentJobT.setTriggerStatus(PhotoSerie.TriggerJobStatus.NEW);
            }
            break;
        }
    }
    if (currentJobT == null) {
        setStatus(ProcessorStatus.PAUSED);
        return;
    }

    final TriggerPhotoSerie currentJob = currentJobT;
    final NikonIR camera = ((AzoTriggerServiceApplication) getActivity().getApplication()).getCamera();

    if (currentJob.getTriggerStatus() == PhotoSerie.TriggerJobStatus.NEW) {
        currentJob.setTriggerStatus(PhotoSerie.TriggerJobStatus.WAITFORUSER);
        if (currentJob.getSeriesName().equals(PhotoSerie.TESTSHOTS)) {
            doTestShots(currentJob);
            return;
        }
        AlertDialog.Builder ad = new AlertDialog.Builder(getActivity(), R.style.dialog);
        ad.setTitle(currentJob.getProject() + ": " + currentJob.getSeriesName());
        ad.setMessage(
                currentJob.getNumber() + " x " + (int) (currentJob.getExposure() / 1000) + "s\n\n"
                        + "Delay after each exposure:" + currentJob.getDelayAfterEachExposure() / 1000 + "s\n"
                        + "Camera controls time: " + camera.isExposureSetOnCamera(currentJob.getExposure())
                        + "\n" + "Total time: "
                        + ((currentJob.getNumber()
                                * (currentJob.getExposure() + currentJob.getDelayAfterEachExposure())) / 1000)
                        + "s");

        ad.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface arg0, int arg1) {
                currentJob.setTriggerStatus(PhotoSerie.TriggerJobStatus.PREPARED);
                processingLoop();
            }
        });
        ad.setNegativeButton("Pause", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface arg0, int arg1) {
                currentJob.setTriggerStatus(PhotoSerie.TriggerJobStatus.NEW);
                pause();
            }
        });

        MediaPlayer mediaPlayer = MediaPlayer.create(activity, R.raw.oida_peda);
        mediaPlayer.start();
        ad.create();
        alertDialog = ad.show();

    }

    final Handler handler = new Handler();

    if ((currentJob.getTriggerStatus() == PhotoSerie.TriggerJobStatus.PREPARED
            || currentJob.getTriggerStatus() == PhotoSerie.TriggerJobStatus.RUNNING)) {
        handler.postDelayed(new Runnable() {

            public void run() {
                if ((((AzoTriggerServiceApplication) getActivity().getApplication()).getJobProcessor()
                        .getStatus() == ProcessorStatus.PAUSED) && (!currentJob.isToggleIsOpen())) {

                    return;
                }
                camera.trigger();
                for (JobProgressListener j : jobProgressListeners) {
                    j.jobProgressed(currentJob);
                }
                if (currentJob.getFirstTriggerTime() == 0) {
                    currentJob.setFirstTriggerTime(System.currentTimeMillis());
                }
                currentJob.setTriggerStatus(PhotoSerie.TriggerJobStatus.RUNNING);

                if (!camera.isExposureSetOnCamera(currentJob.getExposure())) {
                    if (!currentJob.isToggleIsOpen()) {
                        currentJob.setToggleIsOpen(!currentJob.isToggleIsOpen());

                        currentJob.setLastTriggerTime(System.currentTimeMillis());
                    } else {
                        currentJob.setToggleIsOpen(!currentJob.isToggleIsOpen());
                        currentJob.setTriggered(currentJob.getTriggered() + 1);

                    }
                } else {

                    currentJob.setTriggered(currentJob.getTriggered() + 1);

                }
                if (currentJob.getTriggered() < currentJob.getNumber()) {
                    long time;
                    if (camera.isExposureSetOnCamera(currentJob.getExposure())) {
                        time = currentJob.getExposure() + currentJob.getDelayAfterEachExposure();
                    } else {
                        if (currentJob.isToggleIsOpen()) {
                            time = currentJob.getExposure();
                        } else {
                            time = currentJob.getDelayAfterEachExposure();
                        }
                    }
                    handler.postDelayed(this, time);
                } else {
                    currentJob.setTriggerStatus(PhotoSerie.TriggerJobStatus.FINISHED_TRIGGERING);
                    processingLoop();
                }
            }
        }, currentJob.getInitialDelay());
    } else {
    }

}

From source file:io.github.meness.easyintro.EasyIntroCarouselFragment.java

@CallSuper
protected void onSlideChanged(Fragment fragment) {
    if (mSoundRes != -1) {
        MediaPlayer.create(getContext(), mSoundRes).start();
    }//www  .  j a  v  a 2 s. c  o m
    if (mVibrate) {
        mVibrator.vibrate(mVibrateIntensity);
    }

    // disable left indicator for specific slide
    for (int i = 0; i < mDisableLeftIndicatorOn.size(); i++) {
        if (fragment.getClass().getName().equalsIgnoreCase(mDisableLeftIndicatorOn.get(i).getName())) {
            mLeftIndicator.withDisabled(true);
            mPager.setAllowedSwipeDirection(SwipeDirection.LEFT);
            break;
        } else {
            mLeftIndicator.withDisabled(false);
            withSwipeDirection(mSwipeDirection);
        }
    }
    // disable right indicator for specific slide
    for (int i = 0; i < mDisableRightIndicatorOn.size(); i++) {
        if (fragment.getClass().getName().equalsIgnoreCase(mDisableRightIndicatorOn.get(i).getName())) {
            mRightIndicator.withDisabled(true);
            mPager.setAllowedSwipeDirection(SwipeDirection.RIGHT);
            break;
        } else {
            mRightIndicator.withDisabled(false);
            withSwipeDirection(mSwipeDirection);
        }
    }

    updateToggleIndicators();
}

From source file:com.gelakinetic.mtgfam.fragments.LifeCounterFragment.java

/**
 * When the fragment is created, set up the TTS engine, AudioManager, and MediaPlayer for life total vocalization
 *
 * @param savedInstanceState If the fragment is being re-created from a previous saved state, this is the state.
 *//*  w w w  . j a v a 2s .co m*/
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mTtsInit = false;
    mTts = new TextToSpeech(getActivity(), this);
    mTts.setOnUtteranceCompletedListener(this);

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

    m9000Player = MediaPlayer.create(getActivity(), R.raw.over_9000);
    if (m9000Player != null) {
        m9000Player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            public void onCompletion(MediaPlayer mp) {
                onUtteranceCompleted(LIFE_ANNOUNCE);
            }
        });
    }
}

From source file:com.example.android.miwok.activity.ColorsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.word_list);/*from   w  w w . j  a  v a 2  s  .  c  om*/

    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    // Create a list of words
    final ArrayList<Word> words = new ArrayList<Word>();
    words.add(new Word("red", "weei", R.drawable.color_red, R.raw.color_red));
    words.add(new Word("mustard yellow", "chiwii", R.drawable.color_mustard_yellow,
            R.raw.color_mustard_yellow));
    words.add(new Word("dusty yellow", "opiis", R.drawable.color_dusty_yellow, R.raw.color_dusty_yellow));
    words.add(new Word("green", "chokokki", R.drawable.color_green, R.raw.color_green));
    words.add(new Word("brown", "akaakki", R.drawable.color_brown, R.raw.color_brown));
    words.add(new Word("gray", "opoppi", R.drawable.color_gray, R.raw.color_gray));
    words.add(new Word("black", "kululli", R.drawable.color_black, R.raw.color_black));
    words.add(new Word("white", "kelelli", R.drawable.color_white, R.raw.color_white));

    // Create an {@link WordAdapter}, whose data source is a list of {@link Word}s. The
    // adapter knows how to create list items for each item in the list.
    WordAdapter adapter = new WordAdapter(this, words);

    // Find the {@link ListView} object in the view hierarchy of the {@link Activity}.
    // There should be a {@link ListView} with the view ID called list, which is declared in the
    // word_list.xml layout file.
    ListView listView = (ListView) findViewById(R.id.list);
    listView.setBackgroundColor(Color.parseColor("#8800A0"));
    //listView.setBackgroundColor(R.color.category_colors);

    // Make the {@link ListView} use the {@link WordAdapter} we created above, so that the
    // {@link ListView} will display list items for each {@link Word} in the list.
    listView.setAdapter(adapter);

    //plays the audio for number one when any item in the list is clicked click
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            //release current resources being used for media player if it currently exists
            //because we are about to play a different sound file.
            releaseMediaPlayer();

            //get the word located in the list that is at same position as the item clicked in the list
            Word currentWord = words.get(position);

            // Request audio focus for playback
            int result = mAudioManager.requestAudioFocus(mAudioFocusChangeListener,
                    // Use the music stream.
                    AudioManager.STREAM_MUSIC,
                    // Request temporary focus.
                    AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);

            if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {

                //create the medial player with the audio file that is stored in the list for that word.
                mMediaPlayer = MediaPlayer.create(getApplicationContext(), currentWord.getmMiwokAudio());
                //play the file
                mMediaPlayer.start();

                //listener to stop and release the media player and resources being used
                // once the sounds has finished playing
                mMediaPlayer.setOnCompletionListener(mCompletionListener);
            }

        }
    });
}

From source file:com.example.android.miwok.activity.PhrasesActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.word_list);/*from   w ww. j  ava2 s. c o m*/

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

    // Create a list of words
    final ArrayList<Word> words = new ArrayList<Word>();
    words.add(new Word("Where are you going?", "minto wuksus", R.raw.phrase_where_are_you_going));
    words.add(new Word("What is your name?", "tinn oyaase'n", R.raw.phrase_what_is_your_name));
    words.add(new Word("My name is...", "oyaaset...", R.raw.phrase_my_name_is));
    words.add(new Word("How are you feeling?", "michkss?", R.raw.phrase_how_are_you_feeling));
    words.add(new Word("Im feeling good.", "kuchi achit", R.raw.phrase_im_feeling_good));
    words.add(new Word("Are you coming?", "ns'aa?", R.raw.phrase_are_you_coming));
    words.add(new Word("Yes, Im coming.", "h nm", R.raw.phrase_yes_im_coming));
    words.add(new Word("Im coming.", "nm", R.raw.phrase_im_coming));
    words.add(new Word("Lets go.", "yoowutis", R.raw.phrase_lets_go));
    words.add(new Word("Come here.", "nni'nem", R.raw.phrase_come_here));

    // Create an {@link WordAdapter}, whose data source is a list of {@link Word}s. The
    // adapter knows how to create list items for each item in the list.
    WordAdapter adapter = new WordAdapter(this, words);

    // Find the {@link ListView} object in the view hierarchy of the {@link Activity}.
    // There should be a {@link ListView} with the view ID called list, which is declared in the
    // word_list.xml layout file.
    ListView listView = (ListView) findViewById(R.id.list);
    listView.setBackgroundColor(Color.parseColor("#16AFCA"));
    //listView.setBackgroundColor(R.color.category_phrases);

    // Make the {@link ListView} use the {@link WordAdapter} we created above, so that the
    // {@link ListView} will display list items for each {@link Word} in the list.
    listView.setAdapter(adapter);

    //plays the audio for number one when any item in the list is clicked click
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            //release current resources being used for media player if it currently exists
            //because we are about to play a different sound file.
            releaseMediaPlayer();

            //get the word located in the list that is at same position as the item clicked in the list
            Word currentWord = words.get(position);

            /// Request audio focus for playback
            int result = mAudioManager.requestAudioFocus(mAudioFocusChangeListener,
                    // Use the music stream.
                    AudioManager.STREAM_MUSIC,
                    // Request temporary focus.
                    AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);

            if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {

                //create the medial player with the audio file that is stored in the list for that word.
                mMediaPlayer = MediaPlayer.create(getApplicationContext(), currentWord.getmMiwokAudio());
                //play the file
                mMediaPlayer.start();

                //listener to stop and release the media player and resources being used
                // once the sounds has finished playing
                mMediaPlayer.setOnCompletionListener(mCompletionListener);
            }
        }
    });
}

From source file:com.example.android.bangla.ColorsFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.word_list, container, false);

    // Create and setup the AudioManager to request audio focus
    mAudioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);

    // Create a list of words
    final ArrayList<Word> words = new ArrayList<Word>();
    words.add(new Word(R.string.color_red, R.string.bangla_color_red, R.drawable.color_red, R.raw.color_red));
    words.add(new Word(R.string.color_mustard_yellow, R.string.bangla_color_mustard_yellow,
            R.drawable.color_mustard_yellow, R.raw.color_mustard_yellow));
    words.add(new Word(R.string.color_dusty_yellow, R.string.bangla_color_dusty_yellow,
            R.drawable.color_dusty_yellow, R.raw.color_dusty_yellow));
    words.add(new Word(R.string.color_green, R.string.bangla_color_green, R.drawable.color_green,
            R.raw.color_green));//from   www .  ja v  a 2  s . co m
    words.add(new Word(R.string.color_brown, R.string.bangla_color_brown, R.drawable.color_brown,
            R.raw.color_brown));
    words.add(
            new Word(R.string.color_gray, R.string.bangla_color_gray, R.drawable.color_gray, R.raw.color_gray));
    words.add(new Word(R.string.color_black, R.string.bangla_color_black, R.drawable.color_black,
            R.raw.color_black));
    words.add(new Word(R.string.color_white, R.string.bangla_color_white, R.drawable.color_white,
            R.raw.color_white));

    WordAdapter adapter = new WordAdapter(getActivity(), words, R.color.category_colors);
    ListView listView = (ListView) rootView.findViewById(R.id.list);
    listView.setAdapter(adapter);

    // Set a click listener to play the audio when the list item is clicked on
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            releaseMediaPlayer();
            Word word = words.get(position);
            int result = mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener, AudioManager.STREAM_MUSIC,
                    AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);

            if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                mMediaPlayer = MediaPlayer.create(getActivity(), word.getAudioResourceId());
                mMediaPlayer.start();
                mMediaPlayer.setOnCompletionListener(mCompletionListener);
            }
        }
    });

    return rootView;
}

From source file:jvm.ncatz.netbour.ActivityAbout.java

@NonNull
@Override/*from w  w w . j a va2  s.com*/
protected MaterialAboutList getMaterialAboutList(@NonNull Context context) {
    count = 0;

    MaterialAboutCard.Builder builderCardApp = new MaterialAboutCard.Builder();
    builderCardApp.title(R.string.aboutApp);
    MaterialAboutCard.Builder builderCardAuthor = new MaterialAboutCard.Builder();
    builderCardAuthor.title(R.string.aboutAuthor);
    MaterialAboutCard.Builder builderCardSocial = new MaterialAboutCard.Builder();
    builderCardSocial.title(R.string.aboutSocial);
    MaterialAboutCard.Builder builderCardOther = new MaterialAboutCard.Builder();
    builderCardOther.title(R.string.aboutOther);

    IconicsDrawable iconAppVersion = new IconicsDrawable(this).icon(MaterialDesignIconic.Icon.gmi_info_outline)
            .color(ContextCompat.getColor(this, R.color.grey_800)).sizeDp(20);
    IconicsDrawable iconAppRepository = new IconicsDrawable(this).icon(MaterialDesignIconic.Icon.gmi_github_box)
            .color(ContextCompat.getColor(this, R.color.grey_800)).sizeDp(20);
    IconicsDrawable iconAppLicenses = new IconicsDrawable(this).icon(MaterialDesignIconic.Icon.gmi_file)
            .color(ContextCompat.getColor(this, R.color.grey_800)).sizeDp(20);
    IconicsDrawable iconAuthorEmail = new IconicsDrawable(this).icon(MaterialDesignIconic.Icon.gmi_email)
            .color(ContextCompat.getColor(this, R.color.grey_800)).sizeDp(20);
    IconicsDrawable iconAuthorWeb = new IconicsDrawable(this).icon(MaterialDesignIconic.Icon.gmi_view_web)
            .color(ContextCompat.getColor(this, R.color.grey_800)).sizeDp(20);
    IconicsDrawable iconSocialGithub = new IconicsDrawable(this).icon(MaterialDesignIconic.Icon.gmi_github_alt)
            .color(ContextCompat.getColor(this, R.color.grey_800)).sizeDp(20);
    IconicsDrawable iconSocialLinkedin = new IconicsDrawable(this).icon(MaterialDesignIconic.Icon.gmi_linkedin)
            .color(ContextCompat.getColor(this, R.color.grey_800)).sizeDp(20);
    IconicsDrawable iconSocialStack = new IconicsDrawable(this)
            .icon(MaterialDesignIconic.Icon.gmi_stackoverflow)
            .color(ContextCompat.getColor(this, R.color.grey_800)).sizeDp(20);
    IconicsDrawable iconSocialTwitter = new IconicsDrawable(this).icon(MaterialDesignIconic.Icon.gmi_twitter)
            .color(ContextCompat.getColor(this, R.color.grey_800)).sizeDp(20);
    IconicsDrawable iconOtherBugs = new IconicsDrawable(this).icon(MaterialDesignIconic.Icon.gmi_bug)
            .color(ContextCompat.getColor(this, R.color.grey_800)).sizeDp(20);

    MaterialAboutTitleItem itemAppName = new MaterialAboutTitleItem(getString(R.string.app_name),
            ContextCompat.getDrawable(this, R.drawable.logo160));
    MaterialAboutActionItem itemAppVersion = new MaterialAboutActionItem(getString(R.string.app_version_title),
            getString(R.string.app_version_sub), iconAppVersion, new MaterialAboutItemOnClickListener() {
                @Override
                public void onClick(boolean b) {
                    count++;
                    if (count == 7) {
                        try {
                            stopPlaying();
                            player = MediaPlayer.create(ActivityAbout.this, R.raw.easteregg);
                            player.start();
                            count = 0;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
    MaterialAboutActionItem itemAppRepository = new MaterialAboutActionItem(
            getString(R.string.app_repository_title), getString(R.string.app_repository_sub), iconAppRepository,
            new MaterialAboutItemOnClickListener() {
                @Override
                public void onClick(boolean b) {
                    String url = "https://github.com/JMedinilla/Netbour";
                    openUrl(url);
                }
            });
    MaterialAboutActionItem itemAppLicenses = new MaterialAboutActionItem(
            getString(R.string.app_licenses_title), getString(R.string.app_licenses_sub), iconAppLicenses,
            new MaterialAboutItemOnClickListener() {
                @Override
                public void onClick(boolean b) {
                    DialogPlus dialogPlus = DialogPlus.newDialog(ActivityAbout.this).setGravity(Gravity.BOTTOM)
                            .setContentHolder(new ViewHolder(R.layout.licenses_dialog)).setCancelable(true)
                            .setExpanded(true, 600).create();

                    View view = dialogPlus.getHolderView();
                    FButton apacheButton = (FButton) view.findViewById(R.id.apacheButton);
                    FButton mitButton = (FButton) view.findViewById(R.id.mitButton);
                    WebView webView = (WebView) view.findViewById(R.id.licensesWeb);
                    apacheButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            try {
                                AssetManager am = getAssets();
                                InputStream is = am.open("apache");

                                Scanner s = new Scanner(is).useDelimiter("\\A");
                                String apache = s.hasNext() ? s.next() : "";

                                AlertDialog.Builder builder = new AlertDialog.Builder(ActivityAbout.this);
                                builder.setTitle(R.string.apache_title);
                                builder.setMessage(apache);
                                builder.create().show();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                    mitButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            try {
                                AssetManager am = getAssets();
                                InputStream is = am.open("mit");

                                Scanner s = new Scanner(is).useDelimiter("\\A");
                                String mit = s.hasNext() ? s.next() : "";

                                AlertDialog.Builder builder = new AlertDialog.Builder(ActivityAbout.this);
                                builder.setTitle(R.string.mit_title);
                                builder.setMessage(mit);
                                builder.create().show();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                    try {
                        AssetManager am = getAssets();
                        InputStream is = am.open("licenses.html");

                        webView.loadData(inputStreamToString(is), "text/html", "UTF-8");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    dialogPlus.show();
                }
            });
    MaterialAboutTitleItem itemAuthorName = new MaterialAboutTitleItem(getString(R.string.author_name),
            ContextCompat.getDrawable(this, R.drawable.favicon));
    MaterialAboutActionItem itemAuthorEmail = new MaterialAboutActionItem(
            getString(R.string.author_email_title), getString(R.string.author_email_sub), iconAuthorEmail,
            new MaterialAboutItemOnClickListener() {
                @Override
                public void onClick(boolean b) {
                    sendEmail(getString(R.string.author_email_subject));
                }
            });
    MaterialAboutActionItem itemAuthorWeb = new MaterialAboutActionItem(getString(R.string.author_web_title),
            getString(R.string.author_web_sub), iconAuthorWeb, new MaterialAboutItemOnClickListener() {
                @Override
                public void onClick(boolean b) {
                    String url = "https://jvmedinilla.ncatz.com/";
                    openUrl(url);
                }
            });
    MaterialAboutActionItem itemSocialGithub = new MaterialAboutActionItem(
            getString(R.string.social_github_title), getString(R.string.social_github_sub), iconSocialGithub,
            new MaterialAboutItemOnClickListener() {
                @Override
                public void onClick(boolean b) {
                    String url = "https://github.com/JMedinilla";
                    openUrl(url);
                }
            });
    MaterialAboutActionItem itemSocialLinkedin = new MaterialAboutActionItem(
            getString(R.string.social_linkedin_title), getString(R.string.social_linkedin_sub),
            iconSocialLinkedin, new MaterialAboutItemOnClickListener() {
                @Override
                public void onClick(boolean b) {
                    String url = "https://www.linkedin.com/in/javier-medinilla-ag%C3%BCera-951749121/";
                    openUrl(url);
                }
            });
    MaterialAboutActionItem itemSocialStackoverflow = new MaterialAboutActionItem(
            getString(R.string.social_stack_title), getString(R.string.social_stack_sub), iconSocialStack,
            new MaterialAboutItemOnClickListener() {
                @Override
                public void onClick(boolean b) {
                    String url = "http://stackoverflow.com/users/7426526/jmedinilla?tab=profile";
                    openUrl(url);
                }
            });
    MaterialAboutActionItem itemSocialTwitter = new MaterialAboutActionItem(
            getString(R.string.social_twitter_title), getString(R.string.social_twitter_sub), iconSocialTwitter,
            new MaterialAboutItemOnClickListener() {
                @Override
                public void onClick(boolean b) {
                    String url = "https://twitter.com/JMedinillaDev";
                    openUrl(url);
                }
            });
    MaterialAboutActionItem itemOtherBugs = new MaterialAboutActionItem(getString(R.string.other_bug_title),
            getString(R.string.other_bug_sub), iconOtherBugs, new MaterialAboutItemOnClickListener() {
                @Override
                public void onClick(boolean b) {
                    sendEmail(getString(R.string.other_bug_subject));
                }
            });

    builderCardApp.addItem(itemAppName);
    builderCardApp.addItem(itemAppVersion);
    builderCardApp.addItem(itemAppRepository);
    builderCardApp.addItem(itemAppLicenses);
    builderCardAuthor.addItem(itemAuthorName);
    builderCardAuthor.addItem(itemAuthorEmail);
    builderCardAuthor.addItem(itemAuthorWeb);
    builderCardSocial.addItem(itemSocialGithub);
    builderCardSocial.addItem(itemSocialLinkedin);
    builderCardSocial.addItem(itemSocialStackoverflow);
    builderCardSocial.addItem(itemSocialTwitter);
    builderCardOther.addItem(itemOtherBugs);

    MaterialAboutList.Builder builderList = new MaterialAboutList.Builder();
    builderList.addCard(builderCardApp.build());
    builderList.addCard(builderCardAuthor.build());
    builderList.addCard(builderCardSocial.build());
    builderList.addCard(builderCardOther.build());

    return builderList.build();
}