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.kiandastream.musicplayer.MusicService.java

void processNextRequest() {
    if (mState == State.Starting) {
        if (song_playlist != null) {
            if ((Integer.parseInt(positionofsong) + 1) < song_playlist.size()) {
                Integer pos = Integer.parseInt(positionofsong) + 1;
                positionofsong = pos.toString();
                createMediaPlayerIfNeeded();
                mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                try {
                    String songurl = "http://api.kiandastream.globusapps.com/static/songs/"
                            + song_playlist.get(Integer.parseInt(positionofsong)).getSong_id() + ".mp3";
                    System.out.println("url of song playing is "
                            + song_playlist.get(Integer.parseInt(positionofsong)).getSongurl());
                    mPlayer.setDataSource(song_playlist.get(Integer.parseInt(positionofsong)).getSongurl());
                    mState = State.Preparing;
                    //Setting title in notification bar

                    mPlayer.prepareAsync();
                    if (!mWifiLock.isHeld())
                        mWifiLock.acquire();
                } catch (NumberFormatException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (SecurityException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }//from ww w  . j  a  v  a 2s.  c  o m
            } else
                relaxResources(true);
        } else
            relaxResources(true);
    } else if (mState == State.Playing) {
        if (song_playlist != null) {
            if ((Integer.parseInt(positionofsong) + 1) < song_playlist.size()) {
                Integer pos = Integer.parseInt(positionofsong) + 1;
                positionofsong = pos.toString();
                if (listener != null)
                    listener.stopUpdating(mPlayer);
                mPlayer.pause();

                mPlayer.reset();

                mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                try {
                    //String songurl="http://api.kiandastream.globusapps.com/static/songs/"+song_playlist.get(Integer.parseInt(positionofsong)).getSong_id()+".mp3";
                    System.out.println("url of song playing is "
                            + song_playlist.get(Integer.parseInt(positionofsong)).getSongurl());
                    mPlayer.setDataSource(song_playlist.get(Integer.parseInt(positionofsong)).getSongurl());
                    setNotification("Loading");
                    mState = State.Preparing;
                    //Setting title in notification bar

                    mPlayer.prepareAsync();
                    if (!mWifiLock.isHeld())
                        mWifiLock.acquire();
                } catch (NumberFormatException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (SecurityException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    if (mState == State.Paused) {
        if (song_playlist != null) {
            if ((Integer.parseInt(positionofsong) + 1) < song_playlist.size()) {
                Integer pos = Integer.parseInt(positionofsong) + 1;
                positionofsong = pos.toString();
                createMediaPlayerIfNeeded();
                mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                try {
                    //String songurl="http://api.kiandastream.globusapps.com/static/songs/"+song_playlist.get(Integer.parseInt(positionofsong)).getSong_id()+".mp3";
                    System.out.println("url of song playing is "
                            + song_playlist.get(Integer.parseInt(positionofsong)).getSongurl());
                    mPlayer.setDataSource(song_playlist.get(Integer.parseInt(positionofsong)).getSongurl());
                    setNotification("Loading");
                    mState = State.Preparing;
                    //Setting title in notification bar

                    mPlayer.prepareAsync();
                    if (!mWifiLock.isHeld())
                        mWifiLock.acquire();
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(getApplicationContext(), "Last Song of Playlist", Toast.LENGTH_LONG).show();
                relaxResources(true);
            }
        }

    }
}

From source file:com.aengbee.android.leanback.ui.PlaybackOverlayCustomFragment.java

private void requestAudioFocus() {
    if (mHasAudioFocus) {
        return;/*from  w  w  w.j av a  2  s  .  co m*/
    }
    int result = mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN);
    if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        mHasAudioFocus = true;
    } else {
        pause();
    }
}

From source file:com.commontime.cordova.audio.AudioPlayer.java

/**
 * load audio file/*w w  w  .  ja  v a 2 s  .c o  m*/
 * @throws IOException
 * @throws IllegalStateException
 * @throws SecurityException
 * @throws IllegalArgumentException
 */
private void loadAudioFile(String file)
        throws IllegalArgumentException, SecurityException, IllegalStateException, IOException {
    if (this.isStreaming(file)) {
        this.player.setDataSource(file);
        this.player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        //if it's a streaming file, play mode is implied
        this.setMode(MODE.PLAY);
        this.setState(STATE.MEDIA_STARTING);
        this.player.setOnPreparedListener(this);
        this.player.prepareAsync();
    } else {
        if (file.startsWith("/android_asset/")) {
            String f = file.substring(15);
            android.content.res.AssetFileDescriptor fd = this.handler.cordova.getActivity().getAssets()
                    .openFd(f);
            this.player.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
        } else {
            File fp = new File(file);
            if (fp.exists()) {
                FileInputStream fileInputStream = new FileInputStream(file);
                this.player.setDataSource(fileInputStream.getFD());
                fileInputStream.close();
            } else {
                this.player.setDataSource(Environment.getExternalStorageDirectory().getPath() + "/" + file);
            }
        }
        this.setState(STATE.MEDIA_STARTING);
        this.player.setOnPreparedListener(this);
        this.player.prepare();

        // Get duration
        this.duration = getDurationInSeconds();
    }
}

From source file:com.mb.android.MainActivity.java

@android.webkit.JavascriptInterface
@org.xwalk.core.JavascriptInterface// w  ww.j  a v a2  s .  c  om
public void playAudioVlc(String path, String itemJson, String mediaSourceJson, String posterUrl) {

    Intent intent = null;

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

        intent = new Intent(this, MediaService.class);
    } else {
        intent = new Intent(this, KitKatMediaService.class);
    }

    intent.setAction(Constants.ACTION_PLAY);
    intent.putExtra("path", path);
    intent.putExtra("item", itemJson);
    intent.putExtra("mediaSource", mediaSourceJson);
    intent.putExtra("posterUrl", posterUrl);

    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    startService(intent);
}

From source file:com.google.android.apps.santatracker.rocketsleigh.RocketSleighActivity.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override//from  ww  w.  ja  va2s.co m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Log.d(LOG_TAG, "onCreate() : " + savedInstanceState);

    setContentView(R.layout.activity_jet_pack_elf);

    // App Invites
    mInvitesFragment = AppInvitesFragment.getInstance(this);

    // App Measurement
    mMeasurement = FirebaseAnalytics.getInstance(this);
    MeasurementManager.recordScreenView(mMeasurement, getString(R.string.analytics_screen_rocket));

    // [ANALYTICS SCREEN]: Rocket Sleigh
    AnalyticsManager.initializeAnalyticsTracker(this);
    AnalyticsManager.sendScreenView(R.string.analytics_screen_rocket);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        ImmersiveModeHelper.setImmersiveSticky(getWindow());
        ImmersiveModeHelper.installSystemUiVisibilityChangeListener(getWindow());
    }

    mIntroVideo = (VideoView) findViewById(R.id.intro_view);
    mIntroControl = findViewById(R.id.intro_control_view);
    if (savedInstanceState == null) {
        String path = "android.resource://" + getPackageName() + "/" + R.raw.jp_background;
        mBackgroundPlayer = new MediaPlayer();
        try {
            mBackgroundPlayer.setDataSource(this, Uri.parse(path));
            mBackgroundPlayer.setLooping(true);
            mBackgroundPlayer.prepare();
            mBackgroundPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

        boolean nomovie = false;
        if (getIntent().getBooleanExtra("nomovie", false)) {
            nomovie = true;
        } else if (Build.MANUFACTURER.toUpperCase().contains("SAMSUNG")) {
            //                nomovie = true;
        }
        if (!nomovie) {
            mIntroControl.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    endIntro();
                }
            });
            path = "android.resource://" + getPackageName() + "/" + R.raw.intro_wipe;
            mIntroVideo.setVideoURI(Uri.parse(path));
            mIntroVideo.setOnCompletionListener(this);
            mIntroVideo.start();
            mMoviePlaying = true;
        } else {
            mIntroControl.setOnClickListener(null);
            mIntroControl.setVisibility(View.GONE);
            mIntroVideo.setVisibility(View.GONE);
        }
    } else {
        mIntroControl.setOnClickListener(null);
        mIntroControl.setVisibility(View.GONE);
        mIntroVideo.setVisibility(View.GONE);
    }

    mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); // For hit indication.

    mHandler = new Handler(); // Get the main UI handler for posting update events

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);

    Log.d(LOG_TAG, "Width: " + dm.widthPixels + " Height: " + dm.heightPixels + " Density: " + dm.density);

    mScreenHeight = dm.heightPixels;
    mScreenWidth = dm.widthPixels;
    mSlotWidth = mScreenWidth / SLOTS_PER_SCREEN;

    // Setup the random number generator
    mRandom = new Random();
    mRandom.setSeed(System.currentTimeMillis()); // This is ok.  We are not looking for cryptographically secure random here!

    mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    // Setup the background/foreground
    mBackgroundLayout = (LinearLayout) findViewById(R.id.background_layout);
    mBackgroundScroll = (HorizontalScrollView) findViewById(R.id.background_scroll);
    mForegroundLayout = (LinearLayout) findViewById(R.id.foreground_layout);
    mForegroundScroll = (HorizontalScrollView) findViewById(R.id.foreground_scroll);

    mBackgrounds = new Bitmap[6];
    mBackgrounds2 = new Bitmap[6];
    mExitTransitions = new Bitmap[6];
    mEntryTransitions = new Bitmap[6];

    // Need to vertically scale background to fit the screen.  Checkthe image size
    // compared to screen size and scale appropriately.  We will also use the matrix to translate
    // as we move through the level.
    Bitmap bmp = BitmapFactory.decodeResource(getResources(), BACKGROUNDS[0]);
    Log.d(LOG_TAG, "Bitmap Width: " + bmp.getWidth() + " Height: " + bmp.getHeight() + " Screen Width: "
            + dm.widthPixels + " Height: " + dm.heightPixels);
    mScaleY = (float) dm.heightPixels / (float) bmp.getHeight();
    mScaleX = (float) (dm.widthPixels * 2) / (float) bmp.getWidth(); // Ensure that a single bitmap is 2 screens worth of time.  (Stock xxhdpi image is 3840x1080)

    if ((mScaleX != 1.0f) || (mScaleY != 1.0f)) {
        Bitmap tmp = Bitmap.createScaledBitmap(bmp, mScreenWidth * 2, mScreenHeight, false);
        if (tmp != bmp) {
            bmp.recycle();
            bmp = tmp;
        }
    }
    BackgroundLoadTask.createTwoBitmaps(bmp, mBackgrounds, mBackgrounds2, 0);

    // Load the initial background view
    addNextImages(0);
    addNextImages(0);

    mWoodObstacles = new TreeMap<Integer, Bitmap>();
    mWoodObstacleList = new ArrayList<Integer>();
    mWoodObstacleIndex = 0;
    // We need the bitmaps, so we do pre-load here synchronously.
    initObstaclesAndPreLoad(WOOD_OBSTACLES, 3, mWoodObstacles, mWoodObstacleList);

    mCaveObstacles = new TreeMap<Integer, Bitmap>();
    mCaveObstacleList = new ArrayList<Integer>();
    mCaveObstacleIndex = 0;
    initObstacles(CAVE_OBSTACLES, 2, mCaveObstacleList);

    mFactoryObstacles = new TreeMap<Integer, Bitmap>();
    mFactoryObstacleList = new ArrayList<Integer>();
    mFactoryObstacleIndex = 0;
    initObstacles(FACTORY_OBSTACLES, 2, mFactoryObstacleList);

    // Setup the elf
    mElf = (ImageView) findViewById(R.id.elf_image);
    mThrust = (ImageView) findViewById(R.id.thrust_image);
    mElfLayout = (LinearLayout) findViewById(R.id.elf_container);
    loadElfImages();
    updateElf(false);
    // Elf should be the same height relative to the height of the screen on any platform.
    Matrix scaleMatrix = new Matrix();
    mElfScale = ((float) dm.heightPixels * 0.123f) / (float) mElfBitmap.getHeight(); // On a 1920x1080 xxhdpi screen, this makes the elf 133 pixels which is the height of the drawable.
    scaleMatrix.preScale(mElfScale, mElfScale);
    mElf.setImageMatrix(scaleMatrix);
    mThrust.setImageMatrix(scaleMatrix);
    mElfPosX = (dm.widthPixels * 15) / 100; // 15% Into the screen
    mElfPosY = (dm.heightPixels - ((float) mElfBitmap.getHeight() * mElfScale)) / 2; // About 1/2 way down.
    mElfVelX = (float) dm.widthPixels / 3000.0f; // We start at 3 seconds for a full screen to scroll.
    mGravityAccelY = (float) (2 * dm.heightPixels) / (float) Math.pow((1.2 * 1000.0), 2.0); // a = 2*d/t^2 Where d = height in pixels and t = 1.2 seconds
    mThrustAccelY = (float) (2 * dm.heightPixels) / (float) Math.pow((0.7 * 1000.0), 2.0); // a = 2*d/t^2 Where d = height in pixels and t = 0.7 seconds

    // Setup the control view
    mControlView = findViewById(R.id.control_view);
    mGestureDetector = new GestureDetector(this, this);
    mGestureDetector.setIsLongpressEnabled(true);
    mGestureDetector.setOnDoubleTapListener(this);

    mScoreLabel = getString(R.string.score);
    mScoreText = (TextView) findViewById(R.id.score_text);
    mScoreText.setText("0");

    mPlayPauseButton = (ImageView) findViewById(R.id.play_pause_button);
    mExit = (ImageView) findViewById(R.id.exit);

    // Is Tv?
    mIsTv = TvUtil.isTv(this);
    if (mIsTv) {
        mScoreText.setText(mScoreLabel + ": 0");
        mPlayPauseButton.setVisibility(View.GONE);
        mExit.setVisibility(View.GONE);
        // move scoreLayout position to the Top-Right corner.
        View scoreLayout = findViewById(R.id.score_layout);
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) scoreLayout.getLayoutParams();
        params.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        params.removeRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);

        final int marginTop = getResources().getDimensionPixelOffset(R.dimen.overscan_margin_top);
        final int marginLeft = getResources().getDimensionPixelOffset(R.dimen.overscan_margin_left);

        params.setMargins(marginLeft, marginTop, 0, 0);
        scoreLayout.setLayoutParams(params);
        scoreLayout.setBackground(null);
        scoreLayout.findViewById(R.id.score_text_seperator).setVisibility(View.GONE);
    } else {
        mPlayPauseButton.setEnabled(false);
        mPlayPauseButton.setOnClickListener(this);
        mExit.setOnClickListener(this);
    }

    mBigPlayButtonLayout = findViewById(R.id.big_play_button_layout);
    mBigPlayButtonLayout.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // No interaction with the screen below this one.
            return true;
        }
    });
    mBigPlayButton = (ImageButton) findViewById(R.id.big_play_button);
    mBigPlayButton.setOnClickListener(this);

    // For showing points when getting presents.
    mPlus100 = (ImageView) findViewById(R.id.plus_100);
    m100Anim = new AlphaAnimation(1.0f, 0.0f);
    m100Anim.setDuration(1000);
    m100Anim.setFillBefore(true);
    m100Anim.setFillAfter(true);
    mPlus500 = (ImageView) findViewById(R.id.plus_500);
    m500Anim = new AlphaAnimation(1.0f, 0.0f);
    m500Anim.setDuration(1000);
    m500Anim.setFillBefore(true);
    m500Anim.setFillAfter(true);

    // Get the obstacle layouts ready.  No obstacles on the first screen of a level.
    // Prime with a screen full of obstacles.
    mObstacleLayout = (LinearLayout) findViewById(R.id.obstacles_layout);
    mObstacleScroll = (HorizontalScrollView) findViewById(R.id.obstacles_scroll);

    // Initialize the present bitmaps.  These are used repeatedly so we keep them loaded.
    mGiftBoxes = new Bitmap[GIFT_BOXES.length];
    for (int i = 0; i < GIFT_BOXES.length; i++) {
        mGiftBoxes[i] = BitmapFactory.decodeResource(getResources(), GIFT_BOXES[i]);
    }

    // Add starting obstacles.  First screen has presents.  Next 3 get obstacles.
    addFirstScreenPresents();
    //        addFinalPresentRun();  // This adds 2 screens of presents
    //        addNextObstacles(0, 1);
    addNextObstacles(0, 3);

    // Setup the sound pool
    mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
    mSoundPool.setOnLoadCompleteListener(this);
    mCrashSound1 = mSoundPool.load(this, R.raw.jp_crash_1, 1);
    mCrashSound2 = mSoundPool.load(this, R.raw.jp_crash_2, 1);
    mCrashSound3 = mSoundPool.load(this, R.raw.jp_crash_3, 1);
    mGameOverSound = mSoundPool.load(this, R.raw.jp_game_over, 1);
    mJetThrustSound = mSoundPool.load(this, R.raw.jp_jet_thrust, 1);
    mLevelUpSound = mSoundPool.load(this, R.raw.jp_level_up, 1);
    mScoreBigSound = mSoundPool.load(this, R.raw.jp_score_big, 1);
    mScoreSmallSound = mSoundPool.load(this, R.raw.jp_score_small, 1);
    mJetThrustStream = 0;

    if (!mMoviePlaying) {
        doCountdown();
    }
}

From source file:com.examples.gg.twitchplayers.MediaBuffer.java

private void playVideo(String streamPath) {
    doCleanUp();//from   ww  w  .  j  av  a2s .  c  o  m
    try {
        // Create a new media player and set the listeners
        mMediaPlayer = new MediaPlayer(this);
        mMediaPlayer.setDataSource(streamPath);
        //         mMediaPlayer.setDisplay(holder);
        mMediaPlayer.prepare();
        mMediaPlayer.setOnCompletionListener(this);
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.setOnVideoSizeChangedListener(this);
        mMediaPlayer.setOnInfoListener(mInfoListener);
        mMediaPlayer.setOnBufferingUpdateListener(mBufferListener);
        mMediaPlayer.getMetadata();
        setVolumeControlStream(AudioManager.STREAM_MUSIC);

    } catch (Exception e) {
        Log.e("debug", "error: " + e.getMessage(), e);
    }
}

From source file:com.iamplus.musicplayer.MusicService.java

/**
 * Starts playing the next song. If manualUrl is null, the next song will be randomly selected
 * from our Media Retriever (that is, it will be a random song in the user's device). If
 * manualUrl is non-null, then it specifies the URL or path to the song that will be played
 * next./* w  ww . j a  v  a2s  .c o  m*/
 */
void playPrevSong(String manualUrl, Boolean userAction) {
    mState = State.Stopped;
    relaxResources(false); // release everything except MediaPlayer

    try {
        MediaItem playingItem = null;
        if (manualUrl != null) {
            // set the source of the media player to a manual URL or path
            createMediaPlayerIfNeeded();
            mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mPlayer.setDataSource(manualUrl);
            mIsStreaming = manualUrl.startsWith("http:") || manualUrl.startsWith("https:");
        } else {
            mIsStreaming = false; // playing a locally available song

            playingItem = MusicRetriever.getInstance().getPrevSong();
            if (playingItem == null) {

                MusicRetriever.getInstance().reset();
                playingItem = MusicRetriever.getInstance().getCurrentSong();
            }

            mCurrentPlayingItem = playingItem;
            // set the source of the media player a a content URI
            createMediaPlayerIfNeeded();
            mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mPlayer.setDataSource(getApplicationContext(), playingItem.getURI());
        }

        // 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!
        mPlayer.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. If, on the other hand,
        // we are *not* streaming, we want to release the lock if we were holding it before.
        //         if (mIsStreaming) mWifiLock.acquire();
        //         else if (mWifiLock.isHeld()) mWifiLock.release();

        updateRemoteControlPlayingState();
    } catch (IOException ex) {
        Log.e("MusicService", "IOException playing next song: " + ex.getMessage());
        ex.printStackTrace();
        Toast.makeText(getApplicationContext(), R.string.invalid_file_track, Toast.LENGTH_LONG).show();
        processStopRequest();
    }
}

From source file:com.wojtechnology.sunami.TheBrain.java

private void registerAudio() {
    if (mHasAudioFocus || !mIsInit) {
        return;//from ww w . j av  a 2  s .c  o m
    }
    mHasAudioFocus = true;

    // Add audio focus change listener
    mAFChangeListener = new AudioManager.OnAudioFocusChangeListener() {
        public void onAudioFocusChange(int focusChange) {
            if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
                pausePlayback();
                setUI(false);
            } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                // Does nothing cause made me play music at work
            } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
                pausePlayback();
                unregisterAudio();
                setUI(false);
            }
        }
    };

    mAudioManager.requestAudioFocus(mAFChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

    // Add headphone out listener
    registerReceiver(mNoisyAudioStreamReceiver, new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY));

    // Add notification and transport controls
    ComponentName eventReceiver = new ComponentName(getPackageName(),
            RemoteControlEventReceiver.class.getName());
    mSession = new MediaSessionCompat(this, "FireSession", eventReceiver, null);
    mSession.setFlags(
            MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS | MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS);
    mSession.setPlaybackToLocal(AudioManager.STREAM_MUSIC);
    mSession.setMetadata(new MediaMetadataCompat.Builder().putString(MediaMetadataCompat.METADATA_KEY_TITLE, "")
            .putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST, "")
            .putLong(MediaMetadata.METADATA_KEY_DURATION, -1).build());

    mSession.setCallback(new MediaSessionCompat.Callback() {

        @Override
        public void onSeekTo(long pos) {
            super.onSeekTo(pos);
            setProgress((int) pos, isPlaying());
        }
    });
    mSession.setActive(true);
}

From source file:com.example.android.leanback.MediaSessionService.java

private void play() {
    // Only when player is not null (meaning the player has been created), the player is
    // prepared (using the mInitialized as the flag to represent it,
    // this boolean variable will only be assigned to true inside of the onPrepared callback)
    // and the media item is not currently playing (!isPlaying()), then the player can be
    // started./*ww  w.j a  va  2  s  .co m*/

    // If the player has not been prepared, but this function is fired, it is an error state
    // from the app side
    if (!mInitialized) {
        PlaybackStateCompat.Builder builder = createPlaybackStateBuilder(PlaybackStateCompat.STATE_ERROR);
        builder.setErrorMessage(PlaybackStateCompat.ERROR_CODE_APP_ERROR, PLAYER_NOT_INITIALIZED);
        mMediaSession.setPlaybackState(builder.build());

        // If the player has is playing, and this function is fired again, it is an error state
        // from the app side
    } else {
        // Request audio focus only when needed
        if (mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener, AudioManager.STREAM_MUSIC,
                AudioManager.AUDIOFOCUS_GAIN) != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
            return;
        }

        if (mPlayer.getPlaybackParams().getSpeed() != NORMAL_SPEED) {
            // Reset to normal speed and play
            resetSpeedAndPlay();
        } else {
            // Continue play.
            mPlayer.start();
            mMediaSession
                    .setPlaybackState(createPlaybackStateBuilder(PlaybackStateCompat.STATE_PLAYING).build());
        }
    }

}

From source file:dev.datvt.cloudtracks.song_player.PlayMusicActivity.java

private void offSound() {
    if (isVolume) {
        volume.setImageResource(R.drawable.custom_sound_off);
        audioManager.setStreamMute(AudioManager.STREAM_MUSIC, true);
        isVolume = false;//from  ww  w . j ava2  s  . co m
        ToolsHelper.toast(getApplicationContext(), getString(R.string.sound_off));
    } else {
        volume.setImageResource(R.drawable.custom_sound_on);
        audioManager.setStreamMute(AudioManager.STREAM_MUSIC, false);
        isVolume = true;
        ToolsHelper.toast(getApplicationContext(), getString(R.string.sound_on));
    }
}