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.example.android.gft.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 {@link 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(//ww w  .j a  va  2  s  .  c om
            new Word(R.string.number_one, R.string.miwok_number_one, R.drawable.number_one, R.raw.number_one));
    words.add(
            new Word(R.string.number_two, R.string.miwok_number_two, R.drawable.number_two, R.raw.number_two));
    words.add(new Word(R.string.number_three, R.string.miwok_number_three, R.drawable.number_three,
            R.raw.number_three));
    words.add(new Word(R.string.number_four, R.string.miwok_number_four, R.drawable.number_four,
            R.raw.number_four));
    words.add(new Word(R.string.number_five, R.string.miwok_number_five, R.drawable.number_five,
            R.raw.number_five));
    words.add(
            new Word(R.string.number_six, R.string.miwok_number_six, R.drawable.number_six, R.raw.number_six));
    words.add(new Word(R.string.number_seven, R.string.miwok_number_seven, R.drawable.number_seven,
            R.raw.number_seven));
    words.add(new Word(R.string.number_eight, R.string.miwok_number_eight, R.drawable.number_eight,
            R.raw.number_eight));
    words.add(new Word(R.string.number_nine, R.string.miwok_number_nine, R.drawable.number_nine,
            R.raw.number_nine));
    words.add(
            new Word(R.string.number_ten, R.string.miwok_number_ten, 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(getActivity(), words, R.color.category_numbers);

    // 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) rootView.findViewById(R.id.list);

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

    // 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) {
            // Release the media player if it currently exists because we are about to
            // play a different sound file
            releaseMediaPlayer();

            // Get the {@link Word} object at the given position the user clicked on
            Word word = words.get(position);

            // Request audio focus so in order to play the audio file. The app needs to play a
            // short audio file, so we will request audio focus with a short amount of time
            // with AUDIOFOCUS_GAIN_TRANSIENT.
            int result = mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener, AudioManager.STREAM_MUSIC,
                    AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);

            if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                // We have audio focus now.

                // Create and setup the {@link MediaPlayer} for the audio resource associated
                // with the current word
                mMediaPlayer = MediaPlayer.create(getActivity(), word.getAudioResourceId());

                // Start the audio file
                mMediaPlayer.start();

                // Setup a listener on the media player, so that we can stop and release the
                // media player once the sound has finished playing.
                mMediaPlayer.setOnCompletionListener(mCompletionListener);
            }
        }
    });

    return rootView;
}

From source file:com.ezio.multiwii.Main.MainMultiWiiActivity.java

/** Called when the activity is first created. */
@Override//from  w w w . j a va 2s.c  o  m
public void onCreate(Bundle savedInstanceState) {
    app = (App) getApplication();

    app.commMW.SetHandler(mHandler1);
    app.commFrsky.SetHandler(mHandler1);

    Log.d("aaa", "MAIN ON CREATE");
    requestWindowFeature(Window.FEATURE_PROGRESS);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.multiwii_main_layout3);

    ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
    adapter = new MyPagerAdapter(this);

    adapter.SetTitles(
            new String[] { getString(R.string.page1), getString(R.string.page2), getString(R.string.page3) });
    final LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    adapter.AddView(inflater.inflate(R.layout.multiwii_main_layout3_1, (ViewGroup) null, false));
    adapter.AddView(inflater.inflate(R.layout.multiwii_main_layout3_2, (ViewGroup) null, false));
    adapter.AddView(inflater.inflate(R.layout.multiwii_main_layout3_3, (ViewGroup) null, false));

    TVInfo = (TextView) adapter.views.get(0).findViewById(R.id.textViewInfoFirstPage);

    if (!app.FrskySupport) {
        ((Button) adapter.views.get(1).findViewById(R.id.buttonFrsky)).setVisibility(View.GONE);
    }

    viewPager.setAdapter(adapter);

    TitlePageIndicator titleIndicator = (TitlePageIndicator) findViewById(R.id.indicator);
    titleIndicator.setViewPager(viewPager);

    getSupportActionBar().setDisplayShowTitleEnabled(false);

    app.AppStartCounter++;
    app.SaveSettings(true);

    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    if (app.AppStartCounter == 1)
        startActivity(new Intent(getApplicationContext(), ConfigActivity.class));

}

From source file:com.hang.exoplayer.PlayService.java

private boolean requestFocus() {
    // Request audio focus for playback
    int result = mAm.requestAudioFocus(mOnAudioFocusChangeListener,
            // Use the music stream.
            AudioManager.STREAM_MUSIC,
            // Request permanent focus.
            AudioManager.AUDIOFOCUS_GAIN);
    return result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
}

From source file:com.example.lzhang.stockchartt.media.playback.LocalPlayback.java

@Override
public void play(MediaSessionCompat.QueueItem item) {
    mPlayOnFocusGain = true;/* w  w w. j av  a  2 s.c  o m*/
    tryToGetAudioFocus();
    registerAudioNoisyReceiver();
    String mediaId = item.getDescription().getMediaId();
    boolean mediaHasChanged = !TextUtils.equals(mediaId, mCurrentMediaId);
    if (mediaHasChanged) {
        mCurrentPosition = 0;
        mCurrentMediaId = mediaId;
    }

    if (mState == PlaybackStateCompat.STATE_PAUSED && !mediaHasChanged && mMediaPlayer != null) {
        configMediaPlayerState();
    } else {
        mState = PlaybackStateCompat.STATE_STOPPED;
        relaxResources(false); // release everything except MediaPlayer
        //            MediaMetadataCompat track = mMusicProvider.getMusic(
        //                    MediaIDHelper.extractMusicIDFromMediaID(item.getDescription().getMediaId()));

        //noinspection ResourceType
        String source = item.getDescription().getMediaUri().toString();//track.getString(MusicProviderSource.CUSTOM_METADATA_TRACK_SOURCE);
        if (source != null) {
            source = source.replaceAll(" ", "%20"); // Escape spaces for URLs
        }

        try {
            createMediaPlayerIfNeeded();

            mState = PlaybackStateCompat.STATE_BUFFERING;

            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mMediaPlayer.setDataSource(source);

            // 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.onPlaybackStatusChanged(mState);
            }

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

From source file:com.shinymayhem.radiopresets.ActivityMain.java

protected void onResume() {
    super.onResume();
    if (LOCAL_LOGV)
        log("resuming main activity", "v");
    //while app is visible, volume buttons should adjust music stream volume
    if (LOCAL_LOGV)
        log("setting volume control stream", "v");
    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    registerDetailsReceiver();//from   ww w  .ja  va 2  s.com

    //update player details
    //if (mService == null)
    //{
    //          if (LOCAL_LOGV) log("Service not bound yet", "e");
    //  }
    //mService.updateDetails();
}

From source file:com.whitecloud.ron.musicplayer.LocalPlayback.java

@Override
public void play(QueueItem item) {
    mPlayOnFocusGain = true;//from   w  w  w .  j  a v  a 2s.c o  m
    tryToGetAudioFocus();
    registerAudioNoisyReceiver();
    String mediaId = item.getDescription().getMediaId();
    boolean mediaHasChanged = !TextUtils.equals(mediaId, mCurrentMediaId);
    if (mediaHasChanged) {
        mCurrentPosition = 0;
        mCurrentMediaId = mediaId;
    }

    if (mState == PlaybackStateCompat.STATE_PAUSED && !mediaHasChanged && mMediaPlayer != null) {
        configMediaPlayerState();
    } else {
        mState = PlaybackStateCompat.STATE_STOPPED;
        relaxResources(false); // release everything except MediaPlayer
        MediaMetadataCompat track = mMusicProvider
                .getMusic(MediaIDHelper.extractMusicIDFromMediaID(item.getDescription().getMediaId()));

        String source = MusicProvider
                .getTrackSource(track.getString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID));

        try {
            createMediaPlayerIfNeeded();

            mState = PlaybackStateCompat.STATE_BUFFERING;

            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mMediaPlayer.setDataSource(source);

            // 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.onPlaybackStatusChanged(mState);
            }

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

From source file:com.radiofarda.istgah.playback.LocalPlayback.java

@Override
public void play(QueueItem item) {
    mPlayOnFocusGain = true;/*from   w ww  . ja v  a  2  s  . co  m*/
    tryToGetAudioFocus();
    registerAudioNoisyReceiver();
    String mediaId = item.getDescription().getMediaId();
    boolean mediaHasChanged = !TextUtils.equals(mediaId, mCurrentMediaId);
    if (mediaHasChanged) {
        mCurrentPosition = 0;
        mCurrentMediaId = mediaId;
    }

    if (mState == PlaybackStateCompat.STATE_PAUSED && !mediaHasChanged && mMediaPlayer != null) {
        configMediaPlayerState();
    } else {
        mState = PlaybackStateCompat.STATE_STOPPED;
        relaxResources(false); // release everything except MediaPlayer
        MediaMetadataCompat track = mMusicProvider.getMusic(item.getDescription().getMediaId());

        Uri mediaUri = track.getDescription().getMediaUri();
        try {
            if (mediaUri == null) {
                throw new IOException("The file is not downloaded yet!");
            }
            createMediaPlayerIfNeeded();

            mState = PlaybackStateCompat.STATE_BUFFERING;

            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mMediaPlayer.setDataSource(mediaUri.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.onPlaybackStatusChanged(mState);
            }

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

From source file:com.example.android.AudioArchive.playback.LocalPlayback.java

@Override
public void play(QueueItem item) {
    mPlayOnFocusGain = true;/* w  w  w.  ja v  a 2  s.  c  o  m*/
    tryToGetAudioFocus();
    registerAudioNoisyReceiver();
    String mediaId = item.getDescription().getMediaId();
    boolean mediaHasChanged = !TextUtils.equals(mediaId, mCurrentMediaId);
    if (mediaHasChanged) {
        mCurrentPosition = 0;
        mCurrentMediaId = mediaId;
    }

    if (mState == PlaybackStateCompat.STATE_PAUSED && !mediaHasChanged && mMediaPlayer != null) {
        configMediaPlayerState();
    } else {
        mState = PlaybackStateCompat.STATE_STOPPED;
        relaxResources(false); // release everything except MediaPlayer
        MediaMetadataCompat track = mMusicProvider
                .getMusic(MediaIDHelper.extractMusicIDFromMediaID(item.getDescription().getMediaId()));

        //noinspection ResourceType
        String source = track.getString(MusicProviderSource.CUSTOM_METADATA_TRACK_SOURCE);

        try {
            createMediaPlayerIfNeeded();

            mState = PlaybackStateCompat.STATE_BUFFERING;

            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mMediaPlayer.setDataSource(source);

            // 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.onPlaybackStatusChanged(mState);
            }

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

From source file:com.example.android.gft.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 {@link 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.miwok_family_father, R.drawable.family_father,
            R.raw.family_father));//w w w. j a  va 2 s .  c o  m
    words.add(new Word(R.string.family_mother, R.string.miwok_family_mother, R.drawable.family_mother,
            R.raw.family_mother));
    words.add(
            new Word(R.string.family_son, R.string.miwok_family_son, R.drawable.family_son, R.raw.family_son));
    words.add(new Word(R.string.family_daughter, R.string.miwok_family_daughter, R.drawable.family_daughter,
            R.raw.family_daughter));
    words.add(new Word(R.string.family_older_brother, R.string.miwok_family_older_brother,
            R.drawable.family_older_brother, R.raw.family_older_brother));
    words.add(new Word(R.string.family_younger_brother, R.string.miwok_family_younger_brother,
            R.drawable.family_younger_brother, R.raw.family_younger_brother));
    words.add(new Word(R.string.family_older_sister, R.string.miwok_family_older_sister,
            R.drawable.family_older_sister, R.raw.family_older_sister));
    words.add(new Word(R.string.family_younger_sister, R.string.miwok_family_younger_sister,
            R.drawable.family_younger_sister, R.raw.family_younger_sister));
    words.add(new Word(R.string.family_grandmother, R.string.miwok_family_grandmother,
            R.drawable.family_grandmother, R.raw.family_grandmother));
    words.add(new Word(R.string.family_grandfather, R.string.miwok_family_grandfather,
            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(getActivity(), words, R.color.category_family);

    // 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) rootView.findViewById(R.id.list);

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

    // 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) {
            // Release the media player if it currently exists because we are about to
            // play a different sound file
            releaseMediaPlayer();

            // Get the {@link Word} object at the given position the user clicked on
            Word word = words.get(position);

            // Request audio focus so in order to play the audio file. The app needs to play a
            // short audio file, so we will request audio focus with a short amount of time
            // with AUDIOFOCUS_GAIN_TRANSIENT.
            int result = mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener, AudioManager.STREAM_MUSIC,
                    AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);

            if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                // We have audio focus now.

                // Create and setup the {@link MediaPlayer} for the audio resource associated
                // with the current word
                mMediaPlayer = MediaPlayer.create(getActivity(), word.getAudioResourceId());

                // Start the audio file
                mMediaPlayer.start();

                // Setup a listener on the media player, so that we can stop and release the
                // media player once the sound has finished playing.
                mMediaPlayer.setOnCompletionListener(mCompletionListener);
            }
        }
    });

    return rootView;
}

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

public boolean playNext(QueueItem item) {
    MediaPlayer nextPlayer;// www  .  j a  v  a 2  s. c  om
    if (mMediaPlayer == mMediaPlayerA) {
        nextPlayer = mMediaPlayerB;
    } else
        nextPlayer = mMediaPlayerA;

    String mediaId = item.getDescription().getMediaId();
    boolean mediaHasChanged = !TextUtils.equals(mediaId, mCurrentMediaId);
    if (mediaHasChanged) {
        mNextMediaId = mediaId;
    }

    MediaMetadataCompat track = mMusicProvider
            .getMusic(MediaIDHelper.extractMusicIDFromMediaID(item.getDescription().getMediaId()));

    //noinspection ResourceType
    String source = track.getString(MusicProviderSource.CUSTOM_METADATA_TRACK_SOURCE);

    nextPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

    try {
        nextPlayer.setDataSource(source);
    } catch (IOException ex) {
        LogHelper.e(TAG, ex, "Exception playing song");
        if (mCallback != null) {
            mCallback.onError(ex.getMessage());
        }
    }

    // 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!
    nextPlayer.prepareAsync();

    mMediaPlayersSwapping = true;
    return true;
}