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:com.example.android.miwok.activity.NumbersActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.word_list);//  w  w w  . ja v a2 s. c  om

    //Create and setup the {@link AudioManager} to request audio focus
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    // Create a list of words
    //made the arraylist final so that it could be accessed inside the onItemClick method.
    final ArrayList<Word> words = new ArrayList<Word>();
    words.add(new Word("one", "lutti", R.drawable.number_one, R.raw.number_one));
    words.add(new Word("two", "otiiko", R.drawable.number_two, R.raw.number_two));
    words.add(new Word("three", "tolookosu", R.drawable.number_three, R.raw.number_three));
    words.add(new Word("four", "oyyisa", R.drawable.number_four, R.raw.number_four));
    words.add(new Word("five", "massokka", R.drawable.number_five, R.raw.number_five));
    words.add(new Word("six", "temmokka", R.drawable.number_six, R.raw.number_six));
    words.add(new Word("seven", "kenekaku", R.drawable.number_seven, R.raw.number_seven));
    words.add(new Word("eight", "kawinta", R.drawable.number_eight, R.raw.number_eight));
    words.add(new Word("nine", "woe", R.drawable.number_nine, R.raw.number_nine));
    words.add(new Word("ten", "naaacha", R.drawable.number_ten, R.raw.number_ten));

    // 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(R.color.category_numbers);
    listView.setBackgroundColor(Color.parseColor("#FD8E09"));
    // 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:mozilla.voicejam.singwithme.CameraActivity.java

void start() {
    fragment.takePictureAndBlur(0.5f);//ww  w. jav a  2 s.  com

    mediaPlayer = MediaPlayer.create(this, R.raw.music_sample);
    mediaPlayer.start();
    mediaPlayer.getCurrentPosition();
    songDuration = mediaPlayer.getDuration();

    start = System.currentTimeMillis();
    runnable.run();

    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer1) {
            mediaPlayer1.release();
            mediaPlayer = null;
            handler.removeCallbacks(runnable);
        }
    });
}

From source file:net.potterpcs.recipebook.TimerFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    startButton = (Button) getActivity().findViewById(R.id.timerstartbutton);
    stopButton = (Button) getActivity().findViewById(R.id.timerstopbutton);
    display = (TextView) getActivity().findViewById(R.id.timerdisplay);
    minutePicker = (NumberPicker) getActivity().findViewById(R.id.minutepicker);
    secondPicker = (NumberPicker) getActivity().findViewById(R.id.secondpicker);
    timermin = (EditText) getActivity().findViewById(R.id.timerdisplayminutes);
    timersec = (EditText) getActivity().findViewById(R.id.timerdisplayseconds);

    if (minutePicker != null) {
        minutePicker.setMinValue(0);/*  w ww  .  ja  v  a2 s . co m*/
        minutePicker.setMaxValue(99);
        secondPicker.setMinValue(0);
        secondPicker.setMaxValue(59);
        secondPicker.setFormatter(new Formatter() {
            @Override
            public String format(int value) {
                return String.format("%02d", value);
            }
        });
        getActivity().findViewById(R.id.pickerlayout).setVisibility(View.VISIBLE);
        display.setVisibility(View.GONE);
    }

    startButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            int seconds;
            if (minutePicker != null) {
                seconds = minutePicker.getValue() * 60 + secondPicker.getValue();
            } else {
                int m = Integer.parseInt(timermin.getEditableText().toString());
                int s = Integer.parseInt(timersec.getEditableText().toString());
                seconds = m * 60 + s;
                timermin.setText(timermin.getText(), BufferType.NORMAL);
                timersec.setText(timersec.getText(), BufferType.NORMAL);
            }
            startButton.setEnabled(false);
            stopButton.setEnabled(true);

            if (minutePicker == null) {
                timermin.setEnabled(false);
                timersec.setEnabled(false);
            } else {
                minutePicker.setEnabled(false);
                secondPicker.setEnabled(false);
                getActivity().findViewById(R.id.pickerlayout).setVisibility(View.GONE);
                display.setVisibility(View.VISIBLE);
            }

            if (display != null) {
                display.setText(DateUtils.formatElapsedTime(seconds));
            }

            timer = new CountDownTimer(seconds * 1000, 1000) {

                @Override
                public void onTick(long millisUntilFinished) {
                    //                  Log.i(TAG, "tick " + millisUntilFinished);
                    if (display != null) {
                        display.setText(DateUtils.formatElapsedTime(millisUntilFinished / 1000));
                    } else {
                        int totalsec = (int) (millisUntilFinished / 1000);
                        int s = totalsec % 60;
                        int m = totalsec / 60;
                        timermin.setText(String.format("%02d", m));
                        timersec.setText(String.format("%02d", s));
                    }
                }

                @Override
                public void onFinish() {
                    // Play a sound and show a message when the timer ends
                    MediaPlayer mp = MediaPlayer.create(getActivity(), R.raw.ding);
                    mp.setOnCompletionListener(new OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            mp.release();
                        }
                    });
                    mp.setVolume(1.0f, 1.0f);
                    Toast.makeText(getActivity(), "Done!", Toast.LENGTH_LONG).show();
                    mp.start();
                    clearToZero();
                }
            };

            timer.start();
        }
    });

    stopButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            timer.cancel();
            clearToZero();
        }
    });
}

From source file:com.miljin.setminder.TimerService.java

public void broadcastDone() {
    //Activate alarm when timer is finished, depending on settings
    SharedPreferences settingsPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    if (settingsPrefs.getBoolean("enable_alarm_vibrate", false)) {
        vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        long[] vibratePattern = new long[] { 500, 500, 500, 500, 2500, 500, 500, 500, 2500, 500, 500, 500 };
        vibrator.vibrate(vibratePattern, -1);
    }//www  .j  ava 2s.co  m
    if (settingsPrefs.getBoolean("enable_alarm_sound", false)) {
        alarmPlayer = MediaPlayer.create(this, com.miljin.setminder.R.raw.alarm1);
        alarmPlayer.start();
    }

    notificationManager.cancelAll();

    //send broadcast
    Intent tickIntent = new Intent(MainActivity.ACTION_RECEIVE_TIMER_DONE);
    tickIntent.putExtra(EXTRA_TIMER_DONE, true);
    sendBroadcast(tickIntent);

    stopSelf();
}

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

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

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

    // Create a list of words
    final ArrayList<Word> words = new ArrayList<Word>();
    words.add(new Word("father", "p", R.drawable.family_father, R.raw.family_father));
    words.add(new Word("mother", "a", R.drawable.family_mother, R.raw.family_mother));
    words.add(new Word("son", "angsi", R.drawable.family_son, R.raw.family_son));
    words.add(new Word("daughter", "tune", R.drawable.family_daughter, R.raw.family_daughter));
    words.add(new Word("older brother", "taachi", R.drawable.family_older_brother, R.raw.family_older_brother));
    words.add(new Word("younger brother", "chalitti", R.drawable.family_younger_brother,
            R.raw.family_younger_brother));
    words.add(new Word("older sister", "tee", R.drawable.family_older_sister, R.raw.family_older_sister));
    words.add(new Word("younger sister", "kolliti", R.drawable.family_younger_sister,
            R.raw.family_younger_sister));
    words.add(new Word("grandmother ", "ama", R.drawable.family_grandmother, R.raw.family_grandmother));
    words.add(new Word("grandfather", "paapa", R.drawable.family_grandfather, R.raw.family_grandfather));

    // 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("#379237")); //<--this is another way to set the background color is it wasn't in colors.xml
    //listView.setBackgroundColor(R.color.category_family);

    // 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:de.hshannover.f4.trust.ironcontrol.logic.ResultNotificationManager.java

private void ton() {
    //      Field[] fields = R.raw.class.getFields();
    //      for (Field field : fields) {
    //         int rid = 0;
    //         try {
    //            rid = field.getInt(field);
    //         } catch (IllegalArgumentException e) {
    //            e.printStackTrace();
    //         } catch (IllegalAccessException e) {
    //            e.printStackTrace();
    //         }/*from w w w.j a  v  a  2 s .c  om*/
    //
    //         // Use that if you just need the file name
    //         String filename = field.getName();
    //
    //         System.out.println("rid=" + rid +" name=" + filename);
    //      }
    MediaPlayer test = MediaPlayer.create(context, R.raw.star_struck);
    test.start();
    //      get
}

From source file:com.example.android.wearable.speaker.MainActivity.java

/**
 * Plays back the MP3 file embedded in the application
 *///  w  w w  .  j  a  v  a  2  s.  com
private void playMusic() {
    if (mMediaPlayer == null) {
        mMediaPlayer = MediaPlayer.create(this, R.raw.sound);
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                // we need to transition to the READY/Home state
                Log.d(TAG, "Music Finished");
                mUIAnimation.transitionToHome();
            }
        });
    }
    mMediaPlayer.start();
}

From source file:de.escoand.readdaily.PlayerDialogFragment.java

public void setDate(@NonNull final Context context, @NonNull final Date date) {
    this.date = date;

    // image//w ww . j  a  va  2  s  . co m
    switch (date.getMonth()) {
    case 0:
        image = R.mipmap.img_month_01;
        break;
    case 1:
        image = R.mipmap.img_month_02;
        break;
    case 2:
        image = R.mipmap.img_month_03;
        break;
    case 3:
        image = R.mipmap.img_month_04;
        break;
    case 4:
        image = R.mipmap.img_month_05;
        break;
    case 5:
        image = R.mipmap.img_month_06;
        break;
    case 6:
        image = R.mipmap.img_month_07;
        break;
    case 7:
        image = R.mipmap.img_month_08;
        break;
    case 8:
        image = R.mipmap.img_month_09;
        break;
    case 9:
        image = R.mipmap.img_month_10;
        break;
    case 10:
        image = R.mipmap.img_month_11;
        break;
    case 11:
        image = R.mipmap.img_month_12;
        break;
    default: // do nothing
        break;
    }

    final Cursor c = Database.getInstance(context).getDay(date, Database.COLUMN_TYPE + " IN (?,?)",
            new String[] { Database.TYPE_EXEGESIS, Database.TYPE_MEDIA });
    while (c.moveToNext())
        switch (c.getString(c.getColumnIndex(Database.COLUMN_TYPE))) {

        // title
        case Database.TYPE_EXEGESIS:
            title = c.getString(c.getColumnIndex(Database.COLUMN_TITLE));
            break;

        // media
        case Database.TYPE_MEDIA:
            player = MediaPlayer.create(context,
                    Uri.parse(c.getString(c.getColumnIndex(Database.COLUMN_SOURCE))));
            player.setOnCompletionListener(this);
            break;

        // do nothing
        default:
            break;
        }
    c.close();
}

From source file:com.example.android.bangla.NumbersFragment.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(/*from   w  w w . j a  v a  2 s  .com*/
            new Word(R.string.number_one, R.string.bangla_number_one, R.drawable.number_one, R.raw.number_one));
    words.add(
            new Word(R.string.number_two, R.string.bangla_number_two, R.drawable.number_two, R.raw.number_two));
    words.add(new Word(R.string.number_three, R.string.bangla_number_three, R.drawable.number_three,
            R.raw.number_three));
    words.add(new Word(R.string.number_four, R.string.bangla_number_four, R.drawable.number_four,
            R.raw.number_four));
    words.add(new Word(R.string.number_five, R.string.bangla_number_five, R.drawable.number_five,
            R.raw.number_five));
    words.add(
            new Word(R.string.number_six, R.string.bangla_number_six, R.drawable.number_six, R.raw.number_six));
    words.add(new Word(R.string.number_seven, R.string.bangla_number_seven, R.drawable.number_seven,
            R.raw.number_seven));
    words.add(new Word(R.string.number_eight, R.string.bangla_number_eight, R.drawable.number_eight,
            R.raw.number_eight));
    words.add(new Word(R.string.number_nine, R.string.bangla_number_nine, R.drawable.number_nine,
            R.raw.number_nine));
    words.add(
            new Word(R.string.number_ten, R.string.bangla_number_ten, R.drawable.number_ten, R.raw.number_ten));

    // Create an  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(getActivity(), words, R.color.category_numbers);
    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:com.example.android.bangla.PhrasesFragment.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.phrase_where_are_you_going, R.string.bangla_phrase_where_are_you_going,
            R.raw.phrase_where_are_you_going));
    words.add(new Word(R.string.phrase_what_is_your_name, R.string.bangla_phrase_what_is_your_name,
            R.raw.phrase_what_is_your_name));
    words.add(new Word(R.string.phrase_my_name_is, R.string.bangla_phrase_my_name_is, R.raw.phrase_my_name));
    words.add(new Word(R.string.phrase_how_are_you_feeling, R.string.bangla_phrase_how_are_you_feeling,
            R.raw.phrase_how_are_you_feeling));
    words.add(new Word(R.string.phrase_im_feeling_good, R.string.bangla_phrase_im_feeling_good,
            R.raw.phrase_i_am_feeling_good));
    words.add(new Word(R.string.phrase_are_you_coming, R.string.bangla_phrase_are_you_coming,
            R.raw.phrase_are_you_coming));
    words.add(new Word(R.string.phrase_yes_im_coming, R.string.bangla_phrase_yes_im_coming,
            R.raw.phrase_yes_i_am_coming));
    words.add(new Word(R.string.phrase_im_coming, R.string.bangla_phrase_im_coming, R.raw.phrase_i_am_coming));
    words.add(new Word(R.string.phrase_lets_go, R.string.bangla_phrase_lets_go, R.raw.phrase_lets_go));
    words.add(new Word(R.string.phrase_come_here, R.string.bangla_phrase_come_here, R.raw.phrase_come_here));

    // Create an 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(getActivity(), words, R.color.category_phrases);
    ListView listView = (ListView) rootView.findViewById(R.id.list);
    listView.setAdapter(adapter);/*w  ww .  j a v a2 s.  c o m*/

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