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:org.mariotaku.harmony.MusicPlaybackService.java

/**
 * Starts playback of a previously opened file.
 *//*from   w ww  .  j  av  a  2s. co m*/
public void play() {
    final TrackInfo track = getTrackInfo();
    if (track == null)
        return;

    if (mTelephonyManager.getCallState() == TelephonyManager.CALL_STATE_OFFHOOK)
        return;

    mAudioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN);
    mAudioManager.registerMediaButtonEventReceiver(
            new ComponentName(getPackageName(), MediaButtonIntentReceiver.class.getName()));

    mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);

    if (mPlayer.isInitialized()) {
        // if we are at the end of the song, go to the next song first
        long duration = mPlayer.getDuration();
        if (mRepeatMode != REPEAT_MODE_CURRENT && duration > 2000 && mPlayer.getPosition() >= duration - 2000) {
            next(true);
        }

        mPlayer.start();

        // make sure we fade in, in case a previous fadein was stopped
        // because
        // of another focus loss
        mMediaplayerHandler.removeMessages(FADEDOWN);
        mMediaplayerHandler.sendEmptyMessage(FADEUP);

        final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        final NotificationCompat.Style style = new NotificationCompat.BigPictureStyle();
        builder.setSmallIcon(R.drawable.ic_stat_playback);
        builder.setContentTitle(track.title);
        if (!TrackInfo.isUnknownArtist(track)) {
            builder.setContentText(track.artist);
        } else if (!TrackInfo.isUnknownAlbum(track)) {
            builder.setContentText(track.album);
        } else {
            builder.setContentText(getString(R.string.unknown_artist));
        }
        final AlbumInfo album = AlbumInfo.getAlbumInfo(this, track);
        builder.setLargeIcon(getAlbumArtForNotification(album != null ? album.album_art : null));
        builder.setStyle(style);
        builder.setOngoing(true);
        builder.setOnlyAlertOnce(true);
        builder.setWhen(0);
        builder.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(INTENT_PLAYBACK_VIEWER), 0));

        startForeground(ID_NOTIFICATION_PLAYBACK, builder.getNotification());

        if (!mIsSupposedToBePlaying) {
            mIsSupposedToBePlaying = true;
            notifyChange(BROADCAST_PLAY_STATE_CHANGED);
        }

    } else if (mPlayListLen <= 0) {
        // This is mostly so that if you press 'play' on a bluetooth headset
        // without every having played anything before, it will still play
        // something.
        setShuffleMode(SHUFFLE_MODE_ALL);
    }
}

From source file:io.puzzlebox.orbit.ui.OrbitFragment.java

public void maximizeAudioVolume() {

    AudioManager audio = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
    int currentVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);

    if (currentVolume < audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC)) {

        Log.v(TAG, "Previous volume:" + currentVolume);

        Toast.makeText(getActivity().getApplicationContext(), "Automatically setting volume to maximum",
                Toast.LENGTH_SHORT).show();

        AudioManager audioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC), AudioManager.FLAG_SHOW_UI);

    }//from  w w w.  j  a  va  2  s  .c  o  m

}

From source file:com.ichi2.anki2.Reviewer.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Themes.applyTheme(this);
    super.onCreate(savedInstanceState);
    Log.i(AnkiDroidApp.TAG, "Reviewer - onCreate");

    // Remove the status bar and title bar
    if (mPrefFullscreenReview) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        // Do not hide the title bar in Honeycomb, since it contains the action bar.
        if (AnkiDroidApp.SDK_VERSION <= 11) {
            requestWindowFeature(Window.FEATURE_NO_TITLE);
        }/*www . ja  v  a2  s.c  om*/
    }

    mChangeBorderStyle = Themes.getTheme() == Themes.THEME_ANDROID_LIGHT
            || Themes.getTheme() == Themes.THEME_ANDROID_DARK;

    // The hardware buttons should control the music volume while reviewing.
    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    Collection col = AnkiDroidApp.getCol();
    if (col == null) {
        reloadCollection(savedInstanceState);
        return;
    } else {
        mSched = col.getSched();
        mCollectionFilename = col.getPath();

        mBaseUrl = Utils.getBaseUrl(col.getMedia().getDir());
        restorePreferences();
        setFullScreen(mPrefFullscreenReview);

        registerExternalStorageListener();

        if (mNightMode) {
            mCurrentBackgroundColor = Themes.getNightModeCardBackground(this);
        } else {
            mCurrentBackgroundColor = Color.WHITE;
        }

        mRefreshWebview = getRefreshWebviewAndInitializeWebviewVariables();

        initLayout(R.layout.flashcard);

        try {
            String[] title = mSched.getCol().getDecks().current().getString("name").split("::");
            AnkiDroidApp.getCompat().setTitle(this, title[title.length - 1], mInvertedColors);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        AnkiDroidApp.getCompat().setSubtitle(this, "", mInvertedColors);

        if (mPrefTextSelection) {
            clipboardSetText("");
        }

        // Load the template for the card
        try {
            mCardTemplate = Utils.convertStreamToString(getAssets().open("card_template.html"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Initialize text-to-speech. This is an asynchronous operation.
        if (mSpeakText) {
            ReadText.initializeTts(this);
        }

        // Initialize answer recorder
        if (mPrefRecord) {
            Recorder.initialize(this);
        }

        // Get last whiteboard state
        if (mPrefWhiteboard && mCurrentCard != null
                && MetaDB.getWhiteboardState(this, mCurrentCard.getDid()) == 1) {
            mShowWhiteboard = true;
            mWhiteboard.setVisibility(View.VISIBLE);
        }

        // Load the first card and start reviewing. Uses the answer card
        // task to load a card, but since we send null
        // as the card to answer, no card will be answered.
        DeckTask.launchDeckTask(DeckTask.TASK_TYPE_ANSWER_CARD, mAnswerCardHandler,
                new DeckTask.TaskData(mSched, null, 0));

        // Since we aren't actually answering a card, decrement the rep count
        mSched.setReps(mSched.getReps() - 1);
    }
}

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

/**
 * Build a LinkedList of all the things to say, which can include TTS calls and MediaPlayer calls. Then call
 * onUtteranceCompleted to start running through the LinkedList, even though no utterance was spoken.
 */// ww  w. j a v  a2s . co  m
private void announceLifeTotals() {
    if (mTtsInit) {
        mVocalizations.clear();
        for (LcPlayer p : mPlayers) {
            switch (mStatDisplaying) {
            case STAT_LIFE:
                if (p.mLife > 9000) {
                    /* If the life is over 9000, split the string on an IMPROBABLE_NUMBER, and insert a call to
                       the m9000Player */
                    String tmp = getResources().getQuantityString(R.plurals.life_counter_spoken_life,
                            IMPROBABLE_NUMBER, p.mName, IMPROBABLE_NUMBER);
                    String parts[] = tmp.split(Integer.toString(IMPROBABLE_NUMBER));
                    mVocalizations.add(parts[0]);
                    mVocalizations.add(OVER_9000_KEY);
                    mVocalizations.add(parts[1]);
                } else {
                    mVocalizations.add(getResources().getQuantityString(R.plurals.life_counter_spoken_life,
                            p.mLife, p.mName, p.mLife));
                }
                break;
            case STAT_POISON:
                mVocalizations.add(getResources().getQuantityString(R.plurals.life_counter_spoken_poison,
                        p.mPoison, p.mName, p.mPoison));
                break;
            }

        }

        if (mVocalizations.size() > 0) {
            /* Get the audio focus, and tell everyone else to be quiet for a moment */
            int res = mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
                    AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
            if (res == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                onUtteranceCompleted(LIFE_ANNOUNCE);
            }
        }
    }
}

From source file:com.hichinaschool.flashcards.anki.Reviewer.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Themes.applyTheme(this);
    super.onCreate(savedInstanceState);
    // Log.i(AnkiDroidApp.TAG, "Reviewer - onCreate");

    // Remove the status bar and title bar
    if (mPrefFullscreenReview) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        // Do not hide the title bar in Honeycomb, since it contains the action bar.
        if (AnkiDroidApp.SDK_VERSION <= 11) {
            requestWindowFeature(Window.FEATURE_NO_TITLE);
        }/*  w  ww.  j a  v a2s  .c o m*/
    }

    mChangeBorderStyle = Themes.getTheme() == Themes.THEME_ANDROID_LIGHT
            || Themes.getTheme() == Themes.THEME_ANDROID_DARK;

    // The hardware buttons should control the music volume while reviewing.
    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    Collection col = AnkiDroidApp.getCol();
    if (col == null) {
        reloadCollection(savedInstanceState);
        return;
    } else {
        mSched = col.getSched();
        mCollectionFilename = col.getPath();

        mBaseUrl = Utils.getBaseUrl(col.getMedia().getDir());
        restorePreferences();
        setFullScreen(mPrefFullscreenReview);

        registerExternalStorageListener();

        if (mNightMode) {
            mCurrentBackgroundColor = Themes.getNightModeCardBackground(this);
        } else {
            mCurrentBackgroundColor = Color.WHITE;
        }

        mUseQuickUpdate = shouldUseQuickUpdate();

        initLayout(R.layout.flashcard);

        try {
            String[] title = mSched.getCol().getDecks().current().getString("name").split("::");
            AnkiDroidApp.getCompat().setTitle(this, title[title.length - 1], mInvertedColors);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        AnkiDroidApp.getCompat().setSubtitle(this, "", mInvertedColors);

        if (mPrefTextSelection) {
            clipboardSetText("");
        }

        // Load the template for the card
        try {
            mCardTemplate = Utils.convertStreamToString(getAssets().open("card_template.html"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Initialize text-to-speech. This is an asynchronous operation.
        if (mSpeakText) {
            ReadText.initializeTts(this);
        }

        // Get last whiteboard state
        if (mPrefWhiteboard && mCurrentCard != null
                && MetaDB.getWhiteboardState(this, mCurrentCard.getDid()) == 1) {
            mShowWhiteboard = true;
            mWhiteboard.setVisibility(View.VISIBLE);
        }

        // Load the first card and start reviewing. Uses the answer card
        // task to load a card, but since we send null
        // as the card to answer, no card will be answered.
        DeckTask.launchDeckTask(DeckTask.TASK_TYPE_ANSWER_CARD, mAnswerCardHandler,
                new DeckTask.TaskData(mSched, null, 0));

        // Since we aren't actually answering a card, decrement the rep count
        mSched.setReps(mSched.getReps() - 1);
    }
}

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

@Override
protected void onResume() {
    if (DEBUG)/*  ww w .j  a v  a2 s. c  o  m*/
        Log.d(TAG, "onResume()");
    super.onResume();
    if (!PermissionUtils.hasAccessAllEpg(this)
            && checkSelfPermission(PERMISSION_READ_TV_LISTINGS) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[] { PERMISSION_READ_TV_LISTINGS }, PERMISSIONS_REQUEST_READ_TV_LISTINGS);
    }
    mTracker.sendScreenView(SCREEN_NAME);

    SystemProperties.updateSystemProperties();
    mNeedShowBackKeyGuide = true;
    mActivityResumed = true;
    mShowNewSourcesFragment = true;
    mOtherActivityLaunched = false;
    int result = mAudioManager.requestAudioFocus(MainActivity.this, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN);
    mAudioFocusStatus = (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) ? AudioManager.AUDIOFOCUS_GAIN
            : AudioManager.AUDIOFOCUS_LOSS;
    setVolumeByAudioFocusStatus();

    if (mTvView.isPlaying()) {
        // Every time onResume() is called the activity will be assumed to not have requested
        // visible behind.
        requestVisibleBehind(true);
    }
    if (mChannelTuner.areAllChannelsLoaded()) {
        SetupUtils.getInstance(this).markNewChannelsBrowsable();
        resumeTvIfNeeded();
        resumePipIfNeeded();
    }
    mOverlayManager.showMenuWithTimeShiftPauseIfNeeded();

    // Note: The following codes are related to pop up an overlay UI after resume.
    // When the following code is changed, please check the variable
    // willShowOverlayUiAfterResume in updateChannelBannerAndShowIfNeeded.
    if (mInputToSetUp != null) {
        startSetupActivity(mInputToSetUp, false);
        mInputToSetUp = null;
    } else if (mShowProgramGuide) {
        mShowProgramGuide = false;
        mHandler.post(new Runnable() {
            // This will delay the start of the animation until after the Live Channel app is
            // shown. Without this the animation is completed before it is actually visible on
            // the screen.
            @Override
            public void run() {
                mOverlayManager.showProgramGuide();
            }
        });
    } else if (mShowSelectInputView) {
        mShowSelectInputView = false;
        mHandler.post(new Runnable() {
            // mShowSelectInputView is true when the activity is started/resumed because the
            // TV_INPUT button was pressed in a different app.
            // This will delay the start of the animation until after the Live Channel app is
            // shown. Without this the animation is completed before it is actually visible on
            // the screen.
            @Override
            public void run() {
                mOverlayManager.showSelectInputView();
            }
        });
    }
}

From source file:com.android.talkback.SpeechController.java

/**
 * Called when transitioning from an idle state to a speaking state, e.g.
 * the queue was empty, there was no current speech, and a speech item was
 * added to the queue./*from w  w  w  .j a  va2  s  .  c  o  m*/
 *
 * @see #handleSpeechCompleted()
 */
private void handleSpeechStarting() {
    // Always enable the proximity sensor when speaking.
    setProximitySensorState(true);

    boolean useAudioFocus = mUseAudioFocus;
    if (BuildCompat.isAtLeastN()) {
        List<AudioRecordingConfiguration> recordConfigurations = mAudioManager
                .getActiveRecordingConfigurations();
        if (recordConfigurations.size() != 0)
            useAudioFocus = false;
    }

    if (useAudioFocus) {
        mAudioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC,
                AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
    }

    if (mIsSpeaking) {
        LogUtils.log(this, Log.ERROR, "Started speech while already speaking!");
    }

    mIsSpeaking = true;
}

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

/**
 * This is called every time an utterance is completed, as well as when the m9000Player finishes shouting.
 * It polls an item out of the LinkedList and speaks it, or returns audio focus to the system.
 *
 * @param key A key to determine what was just uttered. This is ignored
 *///w  w w. jav  a  2  s.  c  o  m
@Override
public void onUtteranceCompleted(String key) {
    if (mVocalizations.size() > 0) {
        String toSpeak = mVocalizations.poll();
        if (toSpeak.equals(OVER_9000_KEY)) {
            try {
                m9000Player.stop();
                m9000Player.prepare();
                m9000Player.start();
            } catch (IOException e) {
                /* If the media was not played, fall back to TTSing "over 9000" */
                HashMap<String, String> ttsParams = new HashMap<>();
                ttsParams.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_MUSIC));
                ttsParams.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, LIFE_ANNOUNCE);
                if (mTts.speak(getString(R.string.life_counter_over_9000), TextToSpeech.QUEUE_FLUSH,
                        ttsParams) == TextToSpeech.ERROR) {
                    FamiliarActivity activity = getFamiliarActivity();
                    if (activity != null) {
                        activity.showTtsDialog();
                    }
                }
            }
        } else {
            HashMap<String, String> ttsParams = new HashMap<>();
            ttsParams.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_MUSIC));
            ttsParams.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, LIFE_ANNOUNCE);

            if (mTts.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, ttsParams) == TextToSpeech.ERROR) {
                FamiliarActivity activity = getFamiliarActivity();
                if (activity != null) {
                    activity.showTtsDialog();
                }
            }
        }
    } else {
        mAudioManager.abandonAudioFocus(this);
    }
}

From source file:ac.robinson.paperchains.PaperChainsActivity.java

private void streamAudio(String audioPath) {
    resetAudioPlayer();//w  w w.  j  ava 2  s.  c om

    mPlayButton.setVisibility(View.VISIBLE); // undo invisible by resetAudioPlayer();
    mPlayButton.setImageResource(R.drawable.ic_refresh_white_24dp);
    mPlayButton.startAnimation(mRotateAnimation);

    mAudioPlayer = new MediaPlayer();
    mAudioPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

    try {
        try {
            // slightly hacky way of detecting whether the path is a url or a file, and handling appropriately
            new URL(audioPath); // only for the exception it throws
            mAudioPlayer.setDataSource(audioPath);
        } catch (MalformedURLException e) {
            FileInputStream inputStream = new FileInputStream(audioPath);
            mAudioPlayer.setDataSource(inputStream.getFD());
            inputStream.close();
        }
        mAudioPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.start();
                mPlayButton.clearAnimation();
                mPlayButton.setImageResource(R.drawable.ic_pause_white_24dp);
            }
        });
        mAudioPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mPlayButton.clearAnimation();
                mPlayButton.setImageResource(R.drawable.ic_play_arrow_white_24dp);
            }
        });
        mAudioPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                streamAudioLoadFailed(R.string.hint_soundcloud_load_failed);
                return true;
            }
        });
        mAudioPlayer.prepareAsync();
    } catch (IOException e) {
        streamAudioLoadFailed(R.string.hint_soundcloud_load_failed);
    }
}

From source file:github.daneren2005.dsub.service.DownloadServiceImpl.java

private synchronized void setupNext(final DownloadFile downloadFile) {
    try {//from   w w w.  ja  v  a2  s. c  om
        final File file = downloadFile.isCompleteFileAvailable() ? downloadFile.getCompleteFile()
                : downloadFile.getPartialFile();
        if (nextMediaPlayer != null) {
            nextMediaPlayer.setOnCompletionListener(null);
            nextMediaPlayer.release();
            nextMediaPlayer = null;
        }
        nextMediaPlayer = new MediaPlayer();
        nextMediaPlayer.setWakeMode(DownloadServiceImpl.this, PowerManager.PARTIAL_WAKE_LOCK);
        try {
            nextMediaPlayer.setAudioSessionId(mediaPlayer.getAudioSessionId());
        } catch (Throwable e) {
            nextMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        }
        nextMediaPlayer.setDataSource(file.getPath());
        setNextPlayerState(PREPARING);

        nextMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            public void onPrepared(MediaPlayer mp) {
                try {
                    setNextPlayerState(PREPARED);

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
                            && (playerState == PlayerState.STARTED || playerState == PlayerState.PAUSED)) {
                        mediaPlayer.setNextMediaPlayer(nextMediaPlayer);
                        nextSetup = true;
                    }
                } catch (Exception x) {
                    handleErrorNext(x);
                }
            }
        });

        nextMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            public boolean onError(MediaPlayer mediaPlayer, int what, int extra) {
                Log.w(TAG, "Error on playing next " + "(" + what + ", " + extra + "): " + downloadFile);
                return true;
            }
        });

        nextMediaPlayer.prepareAsync();
    } catch (Exception x) {
        handleErrorNext(x);
    }
}