Example usage for android.media AudioManager STREAM_MUSIC

List of usage examples for android.media AudioManager STREAM_MUSIC

Introduction

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

Prototype

int STREAM_MUSIC

To view the source code for android.media AudioManager STREAM_MUSIC.

Click Source Link

Document

Used to identify the volume of audio streams for music playback

Usage

From source file:com.android.app.MediaPlaybackActivity.java

/**
 * Called when the activity is first created.
 */// w  ww .  j a  v  a2 s. c  o  m
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    mAlbumArtWorker = new Worker("album art worker");
    mAlbumArtHandler = new AlbumArtHandler(mAlbumArtWorker.getLooper());

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.audio_player);

    mCurrentTime = (TextView) findViewById(R.id.currenttime);
    mTotalTime = (TextView) findViewById(R.id.totaltime);
    mProgress = (SeekBar) findViewById(R.id.seekbar_playback);
    mAlbum = (ImageView) findViewById(R.id.album);
    mArtistName = (TextView) findViewById(R.id.artistname);
    mAlbumName = (TextView) findViewById(R.id.albumname);
    mTrackName = (TextView) findViewById(R.id.trackname);

    View v = (View) mArtistName.getParent();
    v.setOnTouchListener(this);
    v.setOnLongClickListener(this);

    v = (View) mAlbumName.getParent();
    v.setOnTouchListener(this);
    v.setOnLongClickListener(this);

    v = (View) mTrackName.getParent();
    v.setOnTouchListener(this);
    v.setOnLongClickListener(this);

    mPrevButton = (RepeatingImageButton) findViewById(R.id.prev);
    mPrevButton.setOnClickListener(mPrevListener);
    mPrevButton.setRepeatListener(mRewListener, 260);
    mPauseButton = (ImageButton) findViewById(R.id.pause);
    mPauseButton.requestFocus();
    mPauseButton.setOnClickListener(mPauseListener);
    mNextButton = (RepeatingImageButton) findViewById(R.id.next);
    mNextButton.setOnClickListener(mNextListener);
    mNextButton.setRepeatListener(mFfwdListener, 260);
    seekmethod = 1;

    mDeviceHasDpad = (getResources().getConfiguration().navigation == Configuration.NAVIGATION_DPAD);

    mQueueButton = (ImageButton) findViewById(R.id.curplaylist);
    mQueueButton.setOnClickListener(mQueueListener);
    mShuffleButton = ((ImageButton) findViewById(R.id.shuffle));
    mShuffleButton.setOnClickListener(mShuffleListener);
    mRepeatButton = ((ImageView) findViewById(R.id.repeat));
    mRepeatButton.setOnClickListener(mRepeatListener);

    mIndicator_left = (ImageView) findViewById(R.id.indicator_circle_1);
    mIndicator_right = (ImageView) findViewById(R.id.indicator_circle_2);
    mIndicator_right.setEnabled(false);
    mTitleBack = (ImageButton) findViewById(R.id.title_back);
    mTitleBack.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    });
    mTitlePlaylist = (ImageButton) findViewById(R.id.title_playlist);
    mTitlePlaylist.setOnClickListener(mQueueListener);
    mTitlePlaying = (TextView) findViewById(R.id.title_playing);

    playlistPlayback = (ImageView) findViewById(R.id.playlist_iv_playback);
    playlistPlayback.setOnClickListener(mShowPlaylistListener);

    if (mProgress instanceof SeekBar) {
        SeekBar seeker = (SeekBar) mProgress;
        seeker.setOnSeekBarChangeListener(mSeekListener);
    }
    mProgress.setMax(1000);

    mTouchSlop = ViewConfiguration.get(this).getScaledTouchSlop();

    mViewPager = (ViewPager) findViewById(R.id.vp_play_container);
    initViewPagerContent();
    //        mViewPager.setPageTransformer(true, new PlayPageTransformer());
    //        mPagerIndicator.create(mViewPagerContent.size());
    mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            if (position == 0) {
                mIndicator_left.setEnabled(true);
                mIndicator_right.setEnabled(false);
            } else if (position == 1) {
                mIndicator_left.setEnabled(false);
                mIndicator_right.setEnabled(true);
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });
    mViewPager.setAdapter(mPagerAdapter);
}

From source file:com.example.android.camera2video.CameraActivity.java

public static void logEvent(String text) {
    ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_MUSIC, 100);
    //        tg.startTone(ToneGenerator.TONE_CDMA_PIP,150);
    tg.startTone(ToneGenerator.TONE_CDMA_ONE_MIN_BEEP, 300);

    logText(text);//w w w . ja  va2s  . com
}

From source file:com.allthatseries.RNAudioPlayer.Playback.java

public void playFromUri(Uri uri, Bundle bundle) {
    mPlayOnFocusGain = true;//from  ww w.  j a  v a2  s  .  co m
    tryToGetAudioFocus();
    registerAudioNoisyReceiver();

    mState = PlaybackStateCompat.STATE_STOPPED;
    relaxResources(true);

    try {
        createMediaPlayerIfNeeded();

        mState = PlaybackStateCompat.STATE_BUFFERING;
        mCurrentPosition = 0;

        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setDataSource(uri.toString());

        // Starts preparing the media player in the background. When
        // it's done, it will call our OnPreparedListener (that is,
        // the onPrepared() method on this class, since we set the
        // listener to 'this'). Until the media player is prepared,
        // we *cannot* call start() on it!
        mMediaPlayer.prepareAsync();

        // If we are streaming from the internet, we want to hold a
        // Wifi lock, which prevents the Wifi radio from going to
        // sleep while the song is playing.
        mWifiLock.acquire();

        if (mCallback != null) {
            mCallback.onPlaybackStateChanged(mState);

            MediaMetadataCompat.Builder metaBuilder = new MediaMetadataCompat.Builder();
            metaBuilder.putString(MediaMetadataCompat.METADATA_KEY_ARTIST,
                    bundle.getString(MediaMetadataCompat.METADATA_KEY_ARTIST));
            metaBuilder.putString(MediaMetadataCompat.METADATA_KEY_TITLE,
                    bundle.getString(MediaMetadataCompat.METADATA_KEY_TITLE));
            metaBuilder.putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI,
                    bundle.getString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI));
            mCallback.onMediaMetadataChanged(metaBuilder.build());
        }

    } catch (IOException ex) {
        Log.e(TAG, ex + "Exception playing song");
        if (mCallback != null) {
            mCallback.onError(ex.getMessage());
        }
    }
}

From source file:hku.fyp14017.blencode.ui.ScriptActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(hku.fyp14017.blencode.R.layout.activity_script);
    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    currentFragmentPosition = FRAGMENT_SCRIPTS;

    if (savedInstanceState == null) {
        Bundle bundle = this.getIntent().getExtras();

        if (bundle != null) {
            currentFragmentPosition = bundle.getInt(EXTRA_FRAGMENT_POSITION, FRAGMENT_SCRIPTS);
        }/*from w  ww  .  j  a v a2s. c om*/
    }

    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    updateCurrentFragment(currentFragmentPosition, fragmentTransaction);
    fragmentTransaction.commit();

    setupActionBar();
    setupBottomBar();

    buttonAdd = (ImageButton) findViewById(hku.fyp14017.blencode.R.id.button_add);
    updateHandleAddButtonClickListener();
}

From source file:org.catrobat.catroid.ui.ScriptActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_script);
    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    currentFragmentPosition = FRAGMENT_SCRIPTS;

    if (savedInstanceState == null) {
        Bundle bundle = this.getIntent().getExtras();

        if (bundle != null) {
            currentFragmentPosition = bundle.getInt(EXTRA_FRAGMENT_POSITION, FRAGMENT_SCRIPTS);
        }// w  w w. j  a  va2  s .c om
    }

    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    updateCurrentFragment(currentFragmentPosition, fragmentTransaction);
    fragmentTransaction.commit();

    setupActionBar();
    setupBottomBar();

    buttonAdd = (ImageButton) findViewById(R.id.button_add);
    updateHandleAddButtonClickListener();
}

From source file:com.racoon.ampdroid.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);//from   w ww.j ava 2  s.  co  m

    controller = Controller.getInstance(getResources().getStringArray(R.array.menu_array));
    mNavItems = getResources().getStringArray(R.array.menu_array);
    mDrawerTitle = getResources().getString(R.string.app_name);
    mTitle = controller.getFragmentsNames()[0];

    getActionBar().setDisplayHomeAsUpEnabled(true);
    getActionBar().setHomeButtonEnabled(true);
    getActionBar().setTitle(mTitle);

    mProgress = (ProgressBar) findViewById(R.id.load_progressbar);
    mProgress.setVisibility(ProgressBar.GONE);
    loadingText = (TextView) findViewById(R.id.load_progressbar_text);
    loadingText.setVisibility(TextView.GONE);
    progressLinearLayout = (LinearLayout) findViewById(R.id.progressbar_layout);
    progressLinearLayout.setVisibility(LinearLayout.GONE);
    contentFrame = (FrameLayout) findViewById(R.id.content_frame);

    /** Media Control **/
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
    /** Connection established **/
    if (controller.getServerConfig(this) != null
            && controller.getServer().isConnected(controller.isOnline(getApplicationContext()))) {
        Log.d("bug", controller.getServer().getAmpacheConnection().getAuth());
        FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
        tx.replace(R.id.content_frame, Fragment.instantiate(MainActivity.this, controller.getFragments()[0]),
                controller.getFragmentsNames()[0]);
        activeFragment = 0;
        // tx.addToBackStack(null);
        clearBackStack();
        tx.commit();
        showToast(getResources().getString(R.string.toastServerConnected), Toast.LENGTH_LONG);
        controller.loadCachedFiles();
        /** Sync Files **/
        synchronize(false);

    } else if (controller.getServerConfig(this) != null
            && !controller.getServer().isConnected(controller.isOnline(getApplicationContext()))) {
        FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
        tx.replace(R.id.content_frame, Fragment.instantiate(MainActivity.this, controller.getFragments()[5]),
                controller.getFragmentsNames()[5]);
        activeFragment = 5;
        // tx.addToBackStack(null);
        clearBackStack();
        tx.commit();
        mTitle = controller.getFragmentsNames()[5];
        getActionBar().setTitle(mTitle);
        showToast(getResources().getString(R.string.toastServerConnectionRefused), Toast.LENGTH_LONG);
    } else {
        FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
        tx.replace(R.id.content_frame, Fragment.instantiate(MainActivity.this, controller.getFragments()[5]),
                controller.getFragmentsNames()[5]);
        activeFragment = 5;
        // tx.addToBackStack(null);
        clearBackStack();
        tx.commit();
        mTitle = controller.getFragmentsNames()[5];
        getActionBar().setTitle(mTitle);
        showToast(getResources().getString(R.string.toastSettingsNotSet), Toast.LENGTH_LONG);
    }

    // just styling option add shadow the right edge of the drawer
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open,
            R.string.drawer_close) {

        /** Called when a drawer has settled in a completely open state. */
        @Override
        public void onDrawerOpened(View drawerView) {
            getActionBar().setTitle(mDrawerTitle);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }

        @Override
        public void onDrawerClosed(View drawerView) {
            getActionBar().setTitle(mTitle);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }
    };

    // Set the drawer toggle as the DrawerListener
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    mDrawerList = (ListView) findViewById(R.id.left_drawer);
    // Set the adapter for the list view
    mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mNavItems));
    // Set the list's click listener
    mDrawerList.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, final int pos, long id) {
            FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
            tx.replace(R.id.content_frame,
                    Fragment.instantiate(MainActivity.this, controller.getFragments()[pos]),
                    controller.getFragmentsNames()[pos]);
            activeFragment = pos;
            // tx.addToBackStack(null);
            clearBackStack();
            tx.commit();
            mTitle = controller.getFragmentsNames()[pos];
            getActionBar().setTitle(controller.getFragmentsNames()[pos]);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            mDrawerLayout.closeDrawer(mDrawerList);
        }
    });
    handleIntent(getIntent());
}

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(// w ww. jav a  2s.c  o  m
            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.android.music.TrackBrowserFragment.java

/** Called when the activity is first created. */

@Override/*w w w.  j av a 2 s  .com*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View view = inflater.inflate(R.layout.media_picker_activity, null);

    Intent intent = getActivity().getIntent();
    /*if (intent != null) {
     if (intent.getBooleanExtra("withtabs", false)) {
        getActivity().requestWindowFeature(Window.FEATURE_NO_TITLE);
     }
    }*/
    getActivity().setVolumeControlStream(AudioManager.STREAM_MUSIC);
    if (savedInstanceState != null) {
        mSelectedId = savedInstanceState.getLong("selectedtrack");
        mAlbumId = savedInstanceState.getString("album");
        mArtistId = savedInstanceState.getString("artist");
        mPlaylist = savedInstanceState.getString("playlist");
        mGenre = savedInstanceState.getString("genre");
        mEditMode = savedInstanceState.getBoolean("editmode", false);
    } else {
        mAlbumId = intent.getStringExtra("album");
        // If we have an album, show everything on the album, not just stuff
        // by a particular artist.
        mArtistId = intent.getStringExtra("artist");
        mPlaylist = intent.getStringExtra("playlist");
        mGenre = intent.getStringExtra("genre");
        mEditMode = intent.getAction().equals(Intent.ACTION_EDIT);
    }

    mCursorCols = new String[] { MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE,
            MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.ARTIST,
            MediaStore.Audio.Media.ARTIST_ID, MediaStore.Audio.Media.DURATION };
    mPlaylistMemberCols = new String[] { MediaStore.Audio.Playlists.Members._ID, MediaStore.Audio.Media.TITLE,
            MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.ARTIST,
            MediaStore.Audio.Media.ARTIST_ID, MediaStore.Audio.Media.DURATION,
            MediaStore.Audio.Playlists.Members.PLAY_ORDER, MediaStore.Audio.Playlists.Members.AUDIO_ID,
            MediaStore.Audio.Media.IS_MUSIC };

    //mUseLastListPos = MusicUtils.updateButtonBar(getActivity(), R.id.songtab);
    mTrackList = (ListView) view.findViewById(android.R.id.list);
    mTrackList.setOnCreateContextMenuListener(this);
    mTrackList.setCacheColorHint(0);
    if (mEditMode) {
        ((TouchInterceptor) mTrackList).setDropListener(mDropListener);
        ((TouchInterceptor) mTrackList).setRemoveListener(mRemoveListener);
        mTrackList.setDivider(null);
        mTrackList.setSelector(R.drawable.list_selector_background);
    } else {
        mTrackList.setTextFilterEnabled(true);
    }
    mAdapter = (TrackListAdapter) getActivity().getLastNonConfigurationInstance();

    if (mAdapter != null) {
        mAdapter.setActivity(this);
        mTrackList.setAdapter(mAdapter);
    }
    mToken = MusicUtils.bindToService(getActivity(), this);

    // don't set the album art until after the view has been layed out
    mTrackList.post(new Runnable() {

        public void run() {
            setAlbumArtBackground();
        }
    });

    // mTrackList.dispatchKeyEvent();

    mTrackList.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // TODO Auto-generated method stub
            if (mTrackCursor.getCount() == 0) {
                return;
            }
            // When selecting a track from the queue, just jump there instead of
            // reloading the queue. This is both faster, and prevents accidentally
            // dropping out of party shuffle.
            if (mTrackCursor instanceof NowPlayingCursor) {
                if (MusicUtils.sService != null) {
                    try {
                        MusicUtils.sService.setQueuePosition(position);
                        return;
                    } catch (RemoteException ex) {
                    }
                }
            }
            MusicUtils.playAll(getActivity(), mTrackCursor, position);

        }
    });

    return view;
}

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 . ja va2  s .co  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;
}

From source file:com.example.android.bangla.FamilyFragment.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.family_father, R.string.bangla_family_father, R.drawable.family_father,
            R.raw.family_father));// w w w.  ja  va  2s . c o m
    words.add(new Word(R.string.family_mother, R.string.bangla_family_mother, R.drawable.family_mother,
            R.raw.family_mother));
    words.add(
            new Word(R.string.family_son, R.string.bangla_family_son, R.drawable.family_son, R.raw.family_son));
    words.add(new Word(R.string.family_daughter, R.string.bangla_family_daughter, R.drawable.family_daughter,
            R.raw.family_daughter));
    words.add(new Word(R.string.family_older_brother, R.string.bangla_family_older_brother,
            R.drawable.family_older_brother, R.raw.family_older_brother));
    words.add(new Word(R.string.family_younger_brother, R.string.bangla_family_younger_brother,
            R.drawable.family_younger_brother, R.raw.family_younger_brother));
    words.add(new Word(R.string.family_older_sister, R.string.bangla_family_older_sister,
            R.drawable.family_older_sister, R.raw.family_older_sister));
    words.add(new Word(R.string.family_younger_sister, R.string.bangla_family_younger_sister,
            R.drawable.family_younger_sister, R.raw.family_younger_sister));
    words.add(new Word(R.string.family_grandmother, R.string.bangla_family_grandmother,
            R.drawable.family_grandmother, R.raw.family_grandmother));
    words.add(new Word(R.string.family_grandfather, R.string.bangla_family_grandfather,
            R.drawable.family_grandfather, R.raw.family_grandfather));

    WordAdapter adapter = new WordAdapter(getActivity(), words, R.color.category_family);
    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;
}