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:github.daneren2005.dsub.util.Util.java

@TargetApi(8)
public static void requestAudioFocus(final Context context) {
    if (Build.VERSION.SDK_INT >= 8 && focusListener == null) {
        final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        audioManager.requestAudioFocus(focusListener = new OnAudioFocusChangeListener() {
            public void onAudioFocusChange(int focusChange) {
                DownloadService downloadService = (DownloadService) context;
                if ((focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT
                        || focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK)
                        && !downloadService.isRemoteEnabled()) {
                    if (downloadService.getPlayerState() == PlayerState.STARTED) {
                        Log.i(TAG, "Temporary loss of focus");
                        SharedPreferences prefs = getPreferences(context);
                        int lossPref = Integer
                                .parseInt(prefs.getString(Constants.PREFERENCES_KEY_TEMP_LOSS, "1"));
                        if (lossPref == 2 || (lossPref == 1
                                && focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK)) {
                            lowerFocus = true;
                            downloadService.setVolume(0.1f);
                        } else if (lossPref == 0
                                || (lossPref == 1 && focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT)) {
                            pauseFocus = true;
                            downloadService.pause(true);
                        }//from w w  w .  j  a  v  a 2  s  .  c  o  m
                    }
                } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                    if (pauseFocus) {
                        pauseFocus = false;
                        downloadService.start();
                    } else if (lowerFocus) {
                        lowerFocus = false;
                        downloadService.setVolume(1.0f);
                    }
                } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS && !downloadService.isRemoteEnabled()) {
                    Log.i(TAG, "Permanently lost focus");
                    focusListener = null;
                    downloadService.pause();
                    audioManager.abandonAudioFocus(this);
                }
            }
        }, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    }
}

From source file:com.andrew.apolloMod.service.ApolloService.java

/**
 * Starts playback of a previously opened file.
 *///from ww  w  .  j av a  2s  .  c o  m
public void play() {
    mAudioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN);
    mAudioManager.registerMediaButtonEventReceiver(
            new ComponentName(getPackageName(), MediaButtonIntentReceiver.class.getName()));

    if (mPlayer.isInitialized()) {
        // if we are at the end of the song, go to the next song first

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

        updateNotification();
        if (!mIsSupposedToBePlaying) {
            mIsSupposedToBePlaying = true;
            notifyChange(PLAYSTATE_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_AUTO);
    }
}

From source file:github.madmarty.madsonic.util.Util.java

@TargetApi(8)
public static void requestAudioFocus(final Context context) {
    if (Build.VERSION.SDK_INT >= 8 && !hasFocus) {
        final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        hasFocus = true;// w  w w .  j a v a 2 s . com
        audioManager.requestAudioFocus(new OnAudioFocusChangeListener() {
            public void onAudioFocusChange(int focusChange) {
                DownloadServiceImpl downloadService = (DownloadServiceImpl) context;
                if ((focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT
                        || focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK)
                        && !downloadService.isJukeboxEnabled()) {
                    if (downloadService.getPlayerState() == PlayerState.STARTED) {
                        SharedPreferences prefs = getPreferences(context);
                        int lossPref = Integer
                                .parseInt(prefs.getString(Constants.PREFERENCES_KEY_AUDIO_FOCUS, "1"));
                        if (lossPref == 2 || (lossPref == 1
                                && focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK)) {
                            lowerFocus = true;
                            downloadService.setVolume(0.1f);
                        } else if (lossPref == 0
                                || (lossPref == 1 && focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT)) {
                            pauseFocus = true;
                            downloadService.pause();
                        }
                    }
                } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                    if (pauseFocus) {
                        pauseFocus = false;
                        downloadService.start();
                    } else if (lowerFocus) {
                        lowerFocus = false;
                        downloadService.setVolume(1.0f);
                    }
                } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS && !downloadService.isJukeboxEnabled()) {
                    hasFocus = false;
                    downloadService.pause();
                    audioManager.abandonAudioFocus(this);
                }
            }
        }, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    }
}

From source file:net.czlee.debatekeeper.DebatingActivity.java

/**
 * Gets the preferences from the shared preferences file and applies them.
 *///from ww  w. j ava  2 s.  c  o  m
private void applyPreferences() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean silentMode, vibrateMode, overtimeBellsEnabled;
    boolean poiBuzzerEnabled, poiVibrateEnabled, prepTimerEnabled;
    int firstOvertimeBell, overtimeBellPeriod;
    String userCountDirectionValue, userPrepTimeCountDirectionValue, poiFlashScreenModeValue,
            backgroundColourAreaValue;
    FlashScreenMode flashScreenMode, poiFlashScreenMode;

    Resources res = getResources();

    final String TAG = "applyPreferences";

    try {

        // The boolean preferences
        silentMode = prefs.getBoolean(res.getString(R.string.pref_silentMode_key),
                res.getBoolean(R.bool.prefDefault_silentMode));
        vibrateMode = prefs.getBoolean(res.getString(R.string.pref_vibrateMode_key),
                res.getBoolean(R.bool.prefDefault_vibrateMode));
        overtimeBellsEnabled = prefs.getBoolean(res.getString(R.string.pref_overtimeBellsEnable_key),
                res.getBoolean(R.bool.prefDefault_overtimeBellsEnable));

        mSpeechKeepScreenOn = prefs.getBoolean(res.getString(R.string.pref_keepScreenOn_key),
                res.getBoolean(R.bool.prefDefault_keepScreenOn));
        mPrepTimeKeepScreenOn = prefs.getBoolean(res.getString(R.string.pref_prepTimer_keepScreenOn_key),
                res.getBoolean(R.bool.prefDefault_prepTimer_keepScreenOn));

        mPoiTimerEnabled = prefs.getBoolean(res.getString(R.string.pref_poiTimer_enable_key),
                res.getBoolean(R.bool.prefDefault_poiTimer_enable));
        poiBuzzerEnabled = prefs.getBoolean(res.getString(R.string.pref_poiTimer_buzzerEnable_key),
                res.getBoolean(R.bool.prefDefault_poiTimer_buzzerEnable));
        poiVibrateEnabled = prefs.getBoolean(res.getString(R.string.pref_poiTimer_vibrateEnable_key),
                res.getBoolean(R.bool.prefDefault_poiTimer_vibrateEnable));

        prepTimerEnabled = prefs.getBoolean(res.getString(R.string.pref_prepTimer_enable_key),
                res.getBoolean(R.bool.prefDefault_prepTimer_enable));

        // Overtime bell integers
        if (overtimeBellsEnabled) {
            firstOvertimeBell = prefs.getInt(res.getString(R.string.pref_firstOvertimeBell_key),
                    res.getInteger(R.integer.prefDefault_firstOvertimeBell));
            overtimeBellPeriod = prefs.getInt(res.getString(R.string.pref_overtimeBellPeriod_key),
                    res.getInteger(R.integer.prefDefault_overtimeBellPeriod));
        } else {
            firstOvertimeBell = 0;
            overtimeBellPeriod = 0;
        }

        // List preference: POI flash screen mode
        poiFlashScreenModeValue = prefs.getString(res.getString(R.string.pref_poiTimer_flashScreenMode_key),
                res.getString(R.string.prefDefault_poiTimer_flashScreenMode));
        poiFlashScreenMode = FlashScreenMode.toEnum(poiFlashScreenModeValue);

        // List preference: Count direction
        //  - Backwards compatibility measure
        // This changed in version 0.9, to remove the generallyUp and generallyDown options.
        // Therefore, if we find either of those, we need to replace it with alwaysUp or
        // alwaysDown, respectively.
        userCountDirectionValue = prefs.getString(res.getString(R.string.pref_countDirection_key),
                res.getString(R.string.prefDefault_countDirection));
        if (userCountDirectionValue.equals("generallyUp") || userCountDirectionValue.equals("generallyDown")) {
            // Replace the preference with alwaysUp or alwaysDown, respectively.
            SharedPreferences.Editor editor = prefs.edit();
            String newValue = (userCountDirectionValue.equals("generallyUp")) ? "alwaysUp" : "alwaysDown";
            editor.putString(res.getString(R.string.pref_countDirection_key), newValue);
            editor.apply();
            Log.i(TAG, "countDirection: replaced " + userCountDirectionValue + " with " + newValue);
            userCountDirectionValue = newValue;
        }
        mCountDirection = CountDirection.toEnum(userCountDirectionValue);

        // List preference: Count direction for prep time
        userPrepTimeCountDirectionValue = prefs.getString(
                res.getString(R.string.pref_prepTimer_countDirection_key),
                res.getString(R.string.prefDefault_prepTimer_countDirection));
        mPrepTimeCountDirection = CountDirection.toEnum(userPrepTimeCountDirectionValue);

        // List preference: Background colour area
        BackgroundColourArea oldBackgroundColourArea = mBackgroundColourArea;
        backgroundColourAreaValue = prefs.getString(res.getString(R.string.pref_backgroundColourArea_key),
                res.getString(R.string.prefDefault_backgroundColourArea));
        mBackgroundColourArea = BackgroundColourArea.toEnum(backgroundColourAreaValue);
        if (oldBackgroundColourArea != mBackgroundColourArea) {
            Log.v(TAG, "background colour preference changed - refreshing");
            resetBackgroundColoursToTransparent();
            ((DebateTimerDisplayPagerAdapter) mViewPager.getAdapter()).refreshBackgroundColours();
        }

        // List preference: Flash screen mode
        //  - Backwards compatibility measure
        // This changed from a boolean to a list preference in version 0.6, so there is
        // backwards compatibility to take care of.  Backwards compatibility applies if
        // (a) the list preference is NOT present AND (b) the boolean preference IS present.
        // In this case, retrieve the boolean preference, delete it and write the corresponding
        // list preference.  In all other cases, just take the list preference (using the
        // normal default mechanism if it isn't present, i.e. neither are present).

        if (!prefs.contains(res.getString(R.string.pref_flashScreenMode_key))
                && prefs.contains(res.getString(R.string.pref_flashScreenBool_key))) {
            // Boolean preference.
            // First, get the string and convert it to an enum.
            boolean flashScreenModeBool = prefs.getBoolean(res.getString(R.string.pref_flashScreenBool_key),
                    false);
            flashScreenMode = (flashScreenModeBool) ? FlashScreenMode.SOLID_FLASH : FlashScreenMode.OFF;

            // Then, convert that enum to the list preference value (a string) and write that
            // back to the preferences.  Also, remove the old boolean preference.
            String flashStringModePrefValue = flashScreenMode.toPrefValue();
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString(res.getString(R.string.pref_flashScreenMode_key), flashStringModePrefValue);
            editor.remove(res.getString(R.string.pref_flashScreenBool_key));
            editor.apply();
            Log.i(TAG, "flashScreenMode: replaced boolean preference with list preference: "
                    + flashStringModePrefValue);

        } else {
            // List preference.
            // Get the string and convert it to an enum.
            String flashScreenModeValue;
            flashScreenModeValue = prefs.getString(res.getString(R.string.pref_flashScreenMode_key),
                    res.getString(R.string.prefDefault_flashScreenMode));
            flashScreenMode = FlashScreenMode.toEnum(flashScreenModeValue);
        }

    } catch (ClassCastException e) {
        Log.e(TAG, "caught ClassCastException!");
        return;
    }

    if (mDebateManager != null) {
        mDebateManager.setOvertimeBells(firstOvertimeBell, overtimeBellPeriod);
        mDebateManager.setPrepTimeEnabled(prepTimerEnabled);
        applyPrepTimeBells();

        // This is necessary if the debate structure has changed, i.e. if prep time has been
        // enabled or disabled.
        mViewPager.getAdapter().notifyDataSetChanged();

    } else {
        Log.v(TAG, "Couldn't restore overtime bells, mDebateManager doesn't yet exist");
    }

    if (mBinder != null) {
        AlertManager am = mBinder.getAlertManager();

        // Volume control stream is linked to silent mode
        am.setSilentMode(silentMode);
        setVolumeControlStream((silentMode) ? AudioManager.STREAM_RING : AudioManager.STREAM_MUSIC);

        am.setVibrateMode(vibrateMode);
        am.setFlashScreenMode(flashScreenMode);

        am.setPoiBuzzerEnabled(poiBuzzerEnabled);
        am.setPoiVibrateEnabled(poiVibrateEnabled);
        am.setPoiFlashScreenMode(poiFlashScreenMode);

        this.updateKeepScreenOn();

        Log.v(TAG, "successfully applied");
    } else {
        Log.v(TAG, "Couldn't restore AlertManager preferences; mBinder doesn't yet exist");
    }

}

From source file:org.drrickorang.loopback.LoopbackActivity.java

/** Save a .txt file of various test results. */
void saveReport(Uri uri) {
    ParcelFileDescriptor parcelFileDescriptor = null;
    FileOutputStream outputStream;
    try {//  w  w w.  ja va2s  .co  m
        parcelFileDescriptor = getApplicationContext().getContentResolver().openFileDescriptor(uri, "w");

        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
        outputStream = new FileOutputStream(fileDescriptor);

        log("Done creating output stream");

        String endline = "\n";
        final int stringLength = 300;
        StringBuilder sb = new StringBuilder(stringLength);
        sb.append("DateTime = " + mCurrentTime + endline);
        sb.append(INTENT_SAMPLING_FREQUENCY + " = " + getApp().getSamplingRate() + endline);
        sb.append(INTENT_RECORDER_BUFFER + " = "
                + getApp().getRecorderBufferSizeInBytes() / Constant.BYTES_PER_FRAME + endline);
        sb.append(INTENT_PLAYER_BUFFER + " = "
                + getApp().getPlayerBufferSizeInBytes() / Constant.BYTES_PER_FRAME + endline);
        sb.append(INTENT_AUDIO_THREAD + " = " + getApp().getAudioThreadType() + endline);
        int micSource = getApp().getMicSource();

        String audioType = "unknown";
        switch (getApp().getAudioThreadType()) {
        case Constant.AUDIO_THREAD_TYPE_JAVA:
            audioType = "JAVA";
            break;
        case Constant.AUDIO_THREAD_TYPE_NATIVE:
            audioType = "NATIVE";
            break;
        }
        sb.append(INTENT_AUDIO_THREAD + "_String = " + audioType + endline);

        sb.append(INTENT_MIC_SOURCE + " = " + micSource + endline);
        sb.append(INTENT_MIC_SOURCE + "_String = " + getApp().getMicSourceString(micSource) + endline);
        AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

        int currentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        sb.append(INTENT_AUDIO_LEVEL + " = " + currentVolume + endline);

        switch (mTestType) {
        case Constant.LOOPBACK_PLUG_AUDIO_THREAD_TEST_TYPE_LATENCY:
            if (mCorrelation.mEstimatedLatencyMs > 0.0001) {
                sb.append(String.format("LatencyMs = %.2f", mCorrelation.mEstimatedLatencyMs) + endline);
            } else {
                sb.append(String.format("LatencyMs = unknown") + endline);
            }

            sb.append(String.format("LatencyConfidence = %.2f", mCorrelation.mEstimatedLatencyConfidence)
                    + endline);
            break;
        case Constant.LOOPBACK_PLUG_AUDIO_THREAD_TEST_TYPE_BUFFER_PERIOD:
            sb.append("Buffer Test Duration (s) = " + mBufferTestDuration + endline);

            // report expected recorder buffer period
            int expectedRecorderBufferPeriod = mRecorderBufferSizeInBytes / Constant.BYTES_PER_FRAME
                    * Constant.MILLIS_PER_SECOND / mSamplingRate;
            sb.append("Expected Recorder Buffer Period (ms) = " + expectedRecorderBufferPeriod + endline);

            // report recorder results
            int recorderBufferSize = mRecorderBufferSizeInBytes / Constant.BYTES_PER_FRAME;
            int[] recorderBufferData = null;
            int recorderBufferDataMax = 0;
            switch (mAudioThreadType) {
            case Constant.AUDIO_THREAD_TYPE_JAVA:
                recorderBufferData = mRecorderBufferPeriod.getBufferPeriodArray();
                recorderBufferDataMax = mRecorderBufferPeriod.getMaxBufferPeriod();
                break;
            case Constant.AUDIO_THREAD_TYPE_NATIVE:
                recorderBufferData = mNativeRecorderBufferPeriodArray;
                recorderBufferDataMax = mNativeRecorderMaxBufferPeriod;
                break;
            }
            if (recorderBufferData != null) {
                // this is the range of data that actually has values
                int usefulDataRange = Math.min(recorderBufferDataMax + 1, recorderBufferData.length);
                int[] usefulBufferData = Arrays.copyOfRange(recorderBufferData, 0, usefulDataRange);
                PerformanceMeasurement measurement = new PerformanceMeasurement(recorderBufferSize,
                        mSamplingRate, usefulBufferData);
                boolean isBufferSizesMismatch = measurement.determineIsBufferSizesMatch();
                double benchmark = measurement.computeWeightedBenchmark();
                int outliers = measurement.countOutliers();
                sb.append("Recorder Buffer Sizes Mismatch = " + isBufferSizesMismatch + endline);
                sb.append("Recorder Benchmark = " + benchmark + endline);
                sb.append("Recorder Number of Outliers = " + outliers + endline);
            } else {
                sb.append("Cannot Find Recorder Buffer Period Data!" + endline);
            }

            // report player results
            int playerBufferSize = mPlayerBufferSizeInBytes / Constant.BYTES_PER_FRAME;
            int[] playerBufferData = null;
            int playerBufferDataMax = 0;
            switch (mAudioThreadType) {
            case Constant.AUDIO_THREAD_TYPE_JAVA:
                playerBufferData = mPlayerBufferPeriod.getBufferPeriodArray();
                playerBufferDataMax = mPlayerBufferPeriod.getMaxBufferPeriod();
                break;
            case Constant.AUDIO_THREAD_TYPE_NATIVE:
                playerBufferData = mNativePlayerBufferPeriodArray;
                playerBufferDataMax = mNativePlayerMaxBufferPeriod;
                break;
            }
            if (playerBufferData != null) {
                // this is the range of data that actually has values
                int usefulDataRange = Math.min(playerBufferDataMax + 1, playerBufferData.length);
                int[] usefulBufferData = Arrays.copyOfRange(playerBufferData, 0, usefulDataRange);
                PerformanceMeasurement measurement = new PerformanceMeasurement(playerBufferSize, mSamplingRate,
                        usefulBufferData);
                boolean isBufferSizesMismatch = measurement.determineIsBufferSizesMatch();
                double benchmark = measurement.computeWeightedBenchmark();
                int outliers = measurement.countOutliers();
                sb.append("Player Buffer Sizes Mismatch = " + isBufferSizesMismatch + endline);
                sb.append("Player Benchmark = " + benchmark + endline);
                sb.append("Player Number of Outliers = " + outliers + endline);

            } else {
                sb.append("Cannot Find Player Buffer Period Data!" + endline);
            }

            // report expected player buffer period
            int expectedPlayerBufferPeriod = mPlayerBufferSizeInBytes / Constant.BYTES_PER_FRAME
                    * Constant.MILLIS_PER_SECOND / mSamplingRate;
            if (audioType.equals("JAVA")) {
                // javaPlayerMultiple depends on the samples written per AudioTrack.write()
                int javaPlayerMultiple = 2;
                expectedPlayerBufferPeriod *= javaPlayerMultiple;
            }
            sb.append("Expected Player Buffer Period (ms) = " + expectedPlayerBufferPeriod + endline);

            // report estimated number of glitches
            int numberOfGlitches = estimateNumberOfGlitches(mGlitchesData);
            sb.append("Estimated Number of Glitches = " + numberOfGlitches + endline);

            // report if the total glitching interval is too long
            sb.append("Total glitching interval too long: " + mGlitchingIntervalTooLong + endline);
        }

        String info = getApp().getSystemInfo();
        sb.append("SystemInfo = " + info + endline);

        outputStream.write(sb.toString().getBytes());
        parcelFileDescriptor.close();
    } catch (Exception e) {
        log("Failed to open text file " + e);
    } finally {
        try {
            if (parcelFileDescriptor != null) {
                parcelFileDescriptor.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log("Error closing ParcelFile Descriptor");
        }
    }

}

From source file:net.sourceforge.servestream.service.MediaPlaybackService.java

/**
 * Starts playback of a previously opened file.
 *///from   w  ww  .ja va 2 s  .  c o m
public void play() {
    mAudioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN);
    MediaButtonHelper.registerMediaButtonEventReceiverCompat(mAudioManager, mMediaButtonReceiverComponent);

    if (mPlayer.isInitialized()) {
        // if we are at the end of the song, go to the next song first
        /*long duration = mPlayer.duration();
        if (mRepeatMode != REPEAT_CURRENT && duration > 2000 &&
        mPlayer.position() >= duration - 2000) {
        gotoNext(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);

        updateNotification(false);
        if (!mIsSupposedToBePlaying) {
            mIsSupposedToBePlaying = true;
            notifyChange(PLAYSTATE_CHANGED);
        }

    } else {
        openCurrentAndNext();
    }
}

From source file:com.example.chu.myvideodemo.MusicService.java

public void play(boolean createNewNextTrack) {
    int status = mAudioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN);

    if (D)/*from w w w.  j  av a 2 s . c  om*/
        Log.d(TAG, "Starting playback: audio focus request status = " + status);

    if (status != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        return;
    }

    final Intent intent = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
    intent.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, getAudioSessionId());
    intent.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
    sendBroadcast(intent);

    mAudioManager.registerMediaButtonEventReceiver(
            new ComponentName(getPackageName(), MediaButtonIntentReceiver.class.getName()));
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        mSession.setActive(true);

    if (createNewNextTrack) {
        setNextTrack();
    } else {
        setNextTrack(mNextPlayPos);
    }

    if (mPlayer.isInitialized()) {
        final long duration = mPlayer.duration();
        if (mRepeatMode != REPEAT_CURRENT && duration > 2000 && mPlayer.position() >= duration - 2000) {
            gotoNext(true);
        }

        mPlayer.start();
        mPlayerHandler.removeMessages(FADEDOWN);
        mPlayerHandler.sendEmptyMessage(FADEUP);

        setIsSupposedToBePlaying(true, true);

        cancelShutdown();
        //updateNotification();
        notifyChange(META_CHANGED);
    } else if (mPlaylist.size() <= 0) {
        setShuffleMode(SHUFFLE_AUTO);
    }
}

From source file:de.rosche.spectraTelemetry.SpectraTelemetry.java

public void readPrefs() {
    String valueTmp = "";
    try {//from   w w  w. j  ava2  s.c o m
        voltage_speech_alert = mPrefs.getString("voltage_speech_alert", voltage_speech_alert);
        height_speech_alert = mPrefs.getString("height_speech_alert", height_speech_alert);
        current_speech_alert = mPrefs.getString("current_speech_alert", current_speech_alert);
        used_speech_alert = mPrefs.getString("used_speech_alert", used_speech_alert);
        temp_speech_alert = mPrefs.getString("temp_speech_alert", temp_speech_alert);
        rpm_speech_alert = mPrefs.getString("rpm_speech_alert", rpm_speech_alert);
        speed_speech_alert = mPrefs.getString("speed_speech_alert", speed_speech_alert);
        mVoltageAlarm = getDouble("voltage", mVoltageAlarm);
        mUsedCap = getDouble("used_cap", mUsedCap);
        mCurrentAlarm = getDouble("current", mCurrentAlarm);
        mPowerAlarm = getDouble("power", mPowerAlarm);
        mSpeedAlarm = tools.getInteger("speed", mSpeedAlarm, mPrefs);
        // mSpeedAlarm = getInteger("speed", mSpeedAlarm);
        mRpmAlarm = getInteger("rpm", mRpmAlarm);
        mAltitudeAlarm = getInteger("altitude", mAltitudeAlarm);
        mFuelAlarm = getInteger("fuel", mFuelAlarm);
        voltage_hysteresis = getInteger("voltage_hysteresis", voltage_hysteresis);
        current_hysteresis = getInteger("current_hysteresis", current_hysteresis);
        rpm_hysteresis = getInteger("rpm_hysteresis", rpm_hysteresis);
        temperature_hysteresis = getInteger("temperature_hysteresis", temperature_hysteresis);

        power_hysteresis = getInteger("power_hysteresis", power_hysteresis);
        mTemperatureAlarm = getInteger("temperature", mTemperatureAlarm);
        speech_volume = getInteger("speech_volume", speech_volume);
        AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int sb2value = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        sb2value = sb2value * speech_volume / 100;
        am.setStreamVolume(AudioManager.STREAM_MUSIC, sb2value, 0);
        vibrate_on = mPrefs.getBoolean("vibrate_on", vibrate_on);
        metric = mPrefs.getBoolean("metric", metric);
        mpxData = mPrefs.getBoolean("mpx_data", mpxData);
        displayAlwaysOn = mPrefs.getBoolean("displayAlwaysOn", displayAlwaysOn);
        voltage_speech_ack = mPrefs.getBoolean("voltage_speech_ack", voltage_speech_ack);
        valueTmp = voltage_speech_label + ";" + voltage_speech_unit;
        valueTmp = mPrefs.getString("voltage_speech_text", valueTmp);
        if (!valueTmp.equals("") && valueTmp.contains(";")) {
            StringTokenizer tokens = new StringTokenizer(valueTmp, ";");
            voltage_speech_label = tokens.nextToken().trim();
            voltage_speech_unit = tokens.nextToken().trim();
        }

        height_speech_ack = mPrefs.getBoolean("height_speech_ack", height_speech_ack);
        auto_connect = mPrefs.getBoolean("auto_connect", auto_connect);
        mpxData = mPrefs.getBoolean("mpx_data", mpxData);
        valueTmp = height_speech_label + ";" + height_speech_unit;
        valueTmp = mPrefs.getString("height_speech_text", valueTmp);
        if (!valueTmp.equals("") && valueTmp.contains(";")) {
            StringTokenizer tokens = new StringTokenizer(valueTmp, ";");
            height_speech_label = tokens.nextToken().trim();
            height_speech_unit = tokens.nextToken().trim();
        }
        current_speech_ack = mPrefs.getBoolean("current_speech_ack", current_speech_ack);
        valueTmp = current_speech_label + ";" + current_speech_unit;
        valueTmp = mPrefs.getString("current_speech_text", valueTmp);
        if (!valueTmp.equals("") && valueTmp.contains(";")) {
            StringTokenizer tokens = new StringTokenizer(valueTmp, ";");
            current_speech_label = tokens.nextToken().trim();
            current_speech_unit = tokens.nextToken().trim();
        }
        used_speech_ack = mPrefs.getBoolean("used_speech_ack", used_speech_ack);
        valueTmp = used_speech_label + ";" + used_speech_unit;
        valueTmp = mPrefs.getString("used_speech_text", valueTmp);
        if (!valueTmp.equals("") && valueTmp.contains(";")) {
            StringTokenizer tokens = new StringTokenizer(valueTmp, ";");
            used_speech_label = tokens.nextToken().trim();
            used_speech_unit = tokens.nextToken().trim();
        }
        speed_speech_ack = mPrefs.getBoolean("speed_speech_ack", speed_speech_ack);
        valueTmp = speed_speech_label + ";" + speed_speech_unit;
        valueTmp = mPrefs.getString("speed_speech_text", valueTmp);
        if (!valueTmp.equals("") && valueTmp.contains(";")) {
            StringTokenizer tokens = new StringTokenizer(valueTmp, ";");
            speed_speech_label = tokens.nextToken().trim();
            speed_speech_unit = tokens.nextToken().trim();
        }
        vario_delay = mPrefs.getString("vario_delay", vario_delay);
        rpm_speech_ack = mPrefs.getBoolean("rpm_speech_ack", rpm_speech_ack);
        valueTmp = rpm_speech_label + ";" + rpm_speech_unit;
        valueTmp = mPrefs.getString("rpm_speech_text", valueTmp);
        if (!valueTmp.equals("") && valueTmp.contains(";")) {
            StringTokenizer tokens = new StringTokenizer(valueTmp, ";");
            rpm_speech_label = tokens.nextToken().trim();
            rpm_speech_unit = tokens.nextToken().trim();
        }

        temp_speech_ack = mPrefs.getBoolean("temp_speech_ack", temp_speech_ack);
        valueTmp = temp_speech_label + ";" + temp_speech_unit;
        valueTmp = mPrefs.getString("temp_speech_text", valueTmp);
        if (!valueTmp.equals("") && valueTmp.contains(";")) {
            StringTokenizer tokens = new StringTokenizer(valueTmp, ";");
            temp_speech_label = tokens.nextToken().trim();
            temp_speech_unit = tokens.nextToken().trim();
        }

    } catch (Exception e) {
    }
    valueTmp = mPrefs.getString("log_file", log_file);
    if (valueTmp != "") {
        log_file = valueTmp;
    }
    valueTmp = mPrefs.getString("bluetooth_device", bluetooth_device);
    if (valueTmp != "") {
        bluetooth_device = valueTmp;
    }
    mSound_on = mPrefs.getBoolean("sound_on", mSound_on);
    speech_on = mPrefs.getBoolean("speech_on", speech_on);
    speech_intervall = mPrefs.getString("speech_intervall", speech_intervall);

    speech_alert_intervall = mPrefs.getString("speech_alert_intervall", speech_alert_intervall);
    mAlarm_on = mPrefs.getBoolean("alarm_on", mAlarm_on);
    mSpeak_on = mPrefs.getBoolean("speak_on", mSpeak_on);
    mlog_file = mPrefs.getBoolean("logging_on", mlog_file);
    alert_tone = mPrefs.getString("ringtone", alert_tone);
    label_rpm1 = mPrefs.getString("label_rpm1", label_rpm1);
    label_rpm2 = mPrefs.getString("label_rpm2", label_rpm2);
    label_temp1 = mPrefs.getString("label_temp1", label_temp1);
    label_temp2 = mPrefs.getString("label_temp2", label_temp2);
    unit_rpm1 = mPrefs.getString("unit_rpm1", unit_rpm1);
    unit_rpm2 = mPrefs.getString("unit_rpm2", unit_rpm2);
    unit_temp1 = mPrefs.getString("unit_temp1", unit_temp1);
    unit_temp2 = mPrefs.getString("unit_temp2", unit_temp2);
    current_sensor_type = mPrefs.getString("current_sensor_type", current_sensor_type);
    vario_delay = mPrefs.getString("vario_delay", vario_delay);

    alarm_voltage = mPrefs.getBoolean("alarm_voltage", alarm_voltage);
    alarm_used = mPrefs.getBoolean("alarm_used", alarm_used);
    alarm_current = mPrefs.getBoolean("alarm_current", alarm_current);
    alarm_speed = mPrefs.getBoolean("alarm_speed", alarm_speed);
    alarm_fuel = mPrefs.getBoolean("alarm_fuel", alarm_fuel);
    alarm_temperature = mPrefs.getBoolean("alarm_temperature", alarm_temperature);
    alarm_altitude = mPrefs.getBoolean("alarm_altitude", alarm_altitude);
    alarm_rpm = mPrefs.getBoolean("alarm_rpm", alarm_rpm);
    alarm_power = mPrefs.getBoolean("alarm_power", alarm_power);
    speak_voltage = mPrefs.getBoolean("speak_voltage", speak_voltage);
    speak_used = mPrefs.getBoolean("speak_used", speak_used);
    speak_current = mPrefs.getBoolean("speak_current", speak_current);
    speak_speed = mPrefs.getBoolean("speak_speed", speak_speed);
    speak_fuel = mPrefs.getBoolean("speak_fuel", speak_fuel);
    speak_temperature = mPrefs.getBoolean("speak_temperature", speak_temperature);
    speak_altitude = mPrefs.getBoolean("speak_altitude", speak_altitude);
    speak_rpm = mPrefs.getBoolean("speak_rpm", speak_rpm);
    speak_power = mPrefs.getBoolean("speak_power", speak_power);
    if (rpm1Label != null)
        rpm1Label.setText(label_rpm1);
    if (rpm2Label != null)
        rpm2Label.setText(label_rpm2);
    if (tempLabel != null)
        tempLabel.setText(label_temp1);
    if (temp2Label != null)
        temp2Label.setText(label_temp2);
    if (rpm1_unit != null)
        rpm1_unit.setText(unit_rpm1);
    if (rpm2_unit != null)
        rpm2_unit.setText(unit_rpm2);
    if (temp1_unit != null)
        temp1_unit.setText(unit_temp1);
    if (temp1_unit != null)
        temp1_unit.setText(unit_temp2);
    if (alert_tone.equals("")) {
        uri = null;
    } else {
        uri = Uri.parse(alert_tone);
    }
    if (mp != null) {
        mp.stop();
        mp.release();
        mp = null;
        if (uri != null && !uri.toString().equals("res/raw/alarm.mp3")) {

            mp = MediaPlayer.create(getApplicationContext(), uri);
        } else {
            mp = MediaPlayer.create(getApplicationContext(), R.raw.alarm);
        }
    }
}

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

private synchronized void doPlay(final DownloadFile downloadFile, final int position, final boolean start) {
    try {//from   w w w .  java 2s .  c  o  m
        downloadFile.setPlaying(true);
        final File file = downloadFile.isCompleteFileAvailable() ? downloadFile.getCompleteFile()
                : downloadFile.getPartialFile();
        boolean isPartial = file.equals(downloadFile.getPartialFile());
        downloadFile.updateModificationDate();

        subtractPosition = 0;
        mediaPlayer.setOnCompletionListener(null);
        mediaPlayer.setOnPreparedListener(null);
        mediaPlayer.setOnErrorListener(null);
        mediaPlayer.reset();
        setPlayerState(IDLE);
        try {
            mediaPlayer.setAudioSessionId(audioSessionId);
        } catch (Throwable e) {
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        }
        String dataSource = file.getAbsolutePath();
        if (isPartial && !Util.isOffline(this)) {
            if (proxy == null) {
                proxy = new BufferProxy(this);
                proxy.start();
            }
            proxy.setBufferFile(downloadFile);
            dataSource = proxy.getPrivateAddress(dataSource);
            Log.i(TAG, "Data Source: " + dataSource);
        } else if (proxy != null) {
            proxy.stop();
            proxy = null;
        }
        mediaPlayer.setDataSource(dataSource);
        setPlayerState(PREPARING);

        mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
            public void onBufferingUpdate(MediaPlayer mp, int percent) {
                Log.i(TAG, "Buffered " + percent + "%");
                if (percent == 100) {
                    mediaPlayer.setOnBufferingUpdateListener(null);
                }
            }
        });

        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            public void onPrepared(MediaPlayer mediaPlayer) {
                try {
                    setPlayerState(PREPARED);

                    synchronized (DownloadService.this) {
                        if (position != 0) {
                            Log.i(TAG, "Restarting player from position " + position);
                            mediaPlayer.seekTo(position);
                        }
                        cachedPosition = position;

                        applyReplayGain(mediaPlayer, downloadFile);

                        if (start || autoPlayStart) {
                            mediaPlayer.start();
                            setPlayerState(STARTED);

                            // Disable autoPlayStart after done
                            autoPlayStart = false;
                        } else {
                            setPlayerState(PAUSED);
                            onSongProgress();
                        }
                    }

                    // Only call when starting, setPlayerState(PAUSED) already calls this
                    if (start) {
                        lifecycleSupport.serializeDownloadQueue();
                    }
                } catch (Exception x) {
                    handleError(x);
                }
            }
        });

        setupHandlers(downloadFile, isPartial, start);

        mediaPlayer.prepareAsync();
    } catch (Exception x) {
        handleError(x);
    }
}

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

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private synchronized void setupNext(final DownloadFile downloadFile) {
    try {//from w w  w . j a  va2s  . c  om
        final File file = downloadFile.isCompleteFileAvailable() ? downloadFile.getCompleteFile()
                : downloadFile.getPartialFile();
        resetNext();

        // Exit when using remote controllers
        if (remoteState != LOCAL) {
            return;
        }

        nextMediaPlayer = new MediaPlayer();
        nextMediaPlayer.setWakeMode(DownloadService.this, PowerManager.PARTIAL_WAKE_LOCK);
        try {
            nextMediaPlayer.setAudioSessionId(audioSessionId);
        } catch (Throwable e) {
            nextMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        }
        nextMediaPlayer.setDataSource(file.getPath());
        setNextPlayerState(PREPARING);

        nextMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            public void onPrepared(MediaPlayer mp) {
                // Changed to different while preparing so ignore
                if (nextMediaPlayer != mp) {
                    return;
                }

                try {
                    setNextPlayerState(PREPARED);

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

                    applyReplayGain(nextMediaPlayer, downloadFile);
                } 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);
    }
}