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.mantz_it.rfanalyzer.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    this.savedInstanceState = savedInstanceState;

    // Set default Settings on first run:
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

    // Get reference to the shared preferences:
    preferences = PreferenceManager.getDefaultSharedPreferences(this);

    // Overwrite defaults for file paths in the preferences:
    String extStorage = Environment.getExternalStorageDirectory().getAbsolutePath(); // get the path to the ext. storage
    // File Source file:
    String defaultFile = getString(R.string.pref_filesource_file_default);
    if (preferences.getString(getString(R.string.pref_filesource_file), "").equals(defaultFile))
        preferences.edit().putString(getString(R.string.pref_filesource_file), extStorage + "/" + defaultFile)
                .apply();/*from   w  w  w. j  a v a 2  s .c  om*/
    // Log file:
    defaultFile = getString(R.string.pref_logfile_default);
    if (preferences.getString(getString(R.string.pref_logfile), "").equals(defaultFile))
        preferences.edit().putString(getString(R.string.pref_logfile), extStorage + "/" + defaultFile).apply();

    // Start logging if enabled:
    if (preferences.getBoolean(getString(R.string.pref_logging), false)) {
        if (ContextCompat.checkSelfPermission(this,
                "android.permission.WRITE_EXTERNAL_STORAGE") == PackageManager.PERMISSION_GRANTED) {
            try {
                File logfile = new File(preferences.getString(getString(R.string.pref_logfile), ""));
                logfile.getParentFile().mkdir(); // Create folder
                logcat = Runtime.getRuntime().exec("logcat -f " + logfile);
                Log.i("MainActivity", "onCreate: started logcat (" + logcat.toString() + ") to " + logfile);
            } catch (Exception e) {
                Log.e("MainActivity", "onCreate: Failed to start logging!");
            }
        } else {
            preferences.edit().putBoolean(getString(R.string.pref_logging), false).apply();
            Log.i(LOGTAG, "onCreate: deactivate logging because of missing storage permission.");
        }
    }

    // Get version name:
    try {
        versionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
        Log.i(LOGTAG, "This is RF Analyzer " + versionName + " by Dennis Mantz.");
    } catch (PackageManager.NameNotFoundException e) {
        Log.e(LOGTAG, "onCreate: Cannot read version name: " + e.getMessage());
    }

    // Get references to the GUI components:
    fl_analyzerFrame = (FrameLayout) findViewById(R.id.fl_analyzerFrame);

    // Create a analyzer surface:
    analyzerSurface = new AnalyzerSurface(this, this);
    analyzerSurface.setVerticalScrollEnabled(preferences.getBoolean(getString(R.string.pref_scrollDB), true));
    analyzerSurface.setVerticalZoomEnabled(preferences.getBoolean(getString(R.string.pref_zoomDB), true));
    analyzerSurface.setDecoupledAxis(preferences.getBoolean(getString(R.string.pref_decoupledAxis), false));
    analyzerSurface.setDisplayRelativeFrequencies(
            preferences.getBoolean(getString(R.string.pref_relativeFrequencies), false));
    analyzerSurface.setWaterfallColorMapType(
            Integer.valueOf(preferences.getString(getString(R.string.pref_colorMapType), "4")));
    analyzerSurface.setFftDrawingType(
            Integer.valueOf(preferences.getString(getString(R.string.pref_fftDrawingType), "2")));
    analyzerSurface.setFftRatio(
            Float.valueOf(preferences.getString(getString(R.string.pref_spectrumWaterfallRatio), "0.5")));
    analyzerSurface.setFontSize(Integer.valueOf(preferences.getString(getString(R.string.pref_fontSize), "2")));
    analyzerSurface.setShowDebugInformation(
            preferences.getBoolean(getString(R.string.pref_showDebugInformation), false));

    // Put the analyzer surface in the analyzer frame of the layout:
    fl_analyzerFrame.addView(analyzerSurface);

    // Restore / Initialize the running state and the demodulator mode:
    if (savedInstanceState != null) {
        running = savedInstanceState.getBoolean(getString(R.string.save_state_running));
        demodulationMode = savedInstanceState.getInt(getString(R.string.save_state_demodulatorMode));

        /* BUGFIX / WORKAROUND:
         * The RTL2832U driver will not allow to close the socket and immediately start the driver
         * again to reconnect after an orientation change / app kill + restart.
         * It will report back in onActivityResult() with a -1 (not specified).
         *
         * Work-around:
         * 1) We won't restart the Analyzer if the current source is set to a local RTL-SDR instance:
         * 2) Delay the restart of the Analyzer after the driver was shut down correctly...
         */
        if (running
                && Integer.valueOf(
                        preferences.getString(getString(R.string.pref_sourceType), "1")) == RTLSDR_SOURCE
                && !preferences.getBoolean(getString(R.string.pref_rtlsdr_externalServer), false)) {
            // 1) don't start Analyzer immediately
            running = false;

            // Just inform the user about what is going on (why does this take so long? ...)
            Toast.makeText(MainActivity.this, "Stopping and restarting RTL2832U driver...", Toast.LENGTH_SHORT)
                    .show();

            // 2) Delayed start of the Analyzer:
            Thread timer = new Thread() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1500);
                        startAnalyzer();
                    } catch (InterruptedException e) {
                        Log.e(LOGTAG, "onCreate: (timer thread): Interrupted while sleeping.");
                    }
                }
            };
            timer.start();
        }

    } else {
        // Set running to true if autostart is enabled (this will start the analyzer in onStart() )
        running = preferences.getBoolean((getString(R.string.pref_autostart)), false);
    }

    // Set the hardware volume keys to work on the music audio stream:
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
}

From source file:com.cypress.cysmart.RDKEmulatorView.RemoteControlEmulatorFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    /**/* ww w.  jav  a2  s.  c  o m*/
     * Getting the current orientation of the screen
     * Loading different view for LandScape and portrait
     */
    int currentOrientation = getResources().getConfiguration().orientation;
    if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
        mParentView = inflater.inflate(R.layout.rdk_emulator_view_landscape, container, false);
    } else {
        mParentView = inflater.inflate(R.layout.rdk_emulator_view_portrait, container, false);
    }
    mProgressDialog = new ProgressDialog(getActivity());
    /**
     * Getting the ID's of all Emulator view UI elements
     */
    Button mTrackpadView = (Button) mParentView.findViewById(R.id.trackpad_btn);
    Button mMicrophoneView = (Button) mParentView.findViewById(R.id.microphone_btn);
    mVolumePlusbtn = (ImageButton) mParentView.findViewById(R.id.volume_plus_btn);
    mVolumeMinusBtn = (ImageButton) mParentView.findViewById(R.id.volume_minus_btn);
    mChannelPlusBtn = (ImageButton) mParentView.findViewById(R.id.channel_plus_btn);
    mChannelMinusBtn = (ImageButton) mParentView.findViewById(R.id.channel_minus_btn);
    mLeftBtn = (ImageButton) mParentView.findViewById(R.id.left_btn);
    mRightBtn = (ImageButton) mParentView.findViewById(R.id.right_btn);
    mBackBtn = (ImageButton) mParentView.findViewById(R.id.back_btn);
    mGesturebtn = (ImageButton) mParentView.findViewById(R.id.gesture_btn);
    mExitBtn = (ImageButton) mParentView.findViewById(R.id.exit_btn);
    mPowerBtn = (ImageButton) mParentView.findViewById(R.id.power_btn);
    mRecBtn = (ImageButton) mParentView.findViewById(R.id.record_btn);
    mRecBtn = (ImageButton) mParentView.findViewById(R.id.record_btn);
    /**
     * AudioTrack class initialisation as follows
     *  streamType- AudioManager.STREAM_MUSIC,
     *  sampleRateInHz- 16000,
     *  channelConfig- AudioFormat.CHANNEL_OUT_MONO,
     *  audioFormat-AudioFormat.ENCODING_PCM_16BIT,
     *  bufferSizeInBytes-8000,
     *  mode- AudioTrack.MODE_STREAM
     *
     */
    mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, SAMPLE_RATE, AudioFormat.CHANNEL_OUT_MONO,
            AudioFormat.ENCODING_PCM_16BIT, BUFFER_SIZE, AudioTrack.MODE_STREAM);
    /**
     * TrackPAd button click listner
     */
    mTrackpadView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            TrackpadEmulatorFragment trackpadService = new TrackpadEmulatorFragment();
            try {
                displayView(trackpadService);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    });
    /**
     * Microphone Button click listner
     */
    mMicrophoneView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            MicrophoneEmulatorFragment microphoneService = new MicrophoneEmulatorFragment();
            microphoneService.create(mservice);
            displayView(microphoneService);
        }
    });
    return mParentView;
}

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

@Override
public void onCreate() {
    super.onCreate();

    final SharedPreferences prefs = Util.getPreferences(this);
    new Thread(new Runnable() {
        public void run() {
            Looper.prepare();/*from w w w  .  ja v a2  s. co m*/

            mediaPlayer = new MediaPlayer();
            mediaPlayer.setWakeMode(DownloadService.this, PowerManager.PARTIAL_WAKE_LOCK);

            // We want to change audio session id's between upgrading Android versions.  Upgrading to Android 7.0 is broken (probably updated session id format)
            audioSessionId = -1;
            int id = prefs.getInt(Constants.CACHE_AUDIO_SESSION_ID, -1);
            int versionCode = prefs.getInt(Constants.CACHE_AUDIO_SESSION_VERSION_CODE, -1);
            if (versionCode == Build.VERSION.SDK_INT && id != -1) {
                try {
                    audioSessionId = id;
                    mediaPlayer.setAudioSessionId(audioSessionId);
                } catch (Throwable e) {
                    Log.w(TAG, "Failed to use cached audio session", e);
                    audioSessionId = -1;
                }
            }

            if (audioSessionId == -1) {
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                try {
                    audioSessionId = mediaPlayer.getAudioSessionId();

                    SharedPreferences.Editor editor = prefs.edit();
                    editor.putInt(Constants.CACHE_AUDIO_SESSION_ID, audioSessionId);
                    editor.putInt(Constants.CACHE_AUDIO_SESSION_VERSION_CODE, Build.VERSION.SDK_INT);
                    editor.commit();
                } catch (Throwable t) {
                    // Froyo or lower
                }
            }

            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int what, int more) {
                    handleError(new Exception("MediaPlayer error: " + what + " (" + more + ")"));
                    return false;
                }
            });

            /*try {
               Intent i = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
               i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, audioSessionId);
               i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
               sendBroadcast(i);
            } catch(Throwable e) {
               // Froyo or lower
            }*/

            effectsController = new AudioEffectsController(DownloadService.this, audioSessionId);
            if (prefs.getBoolean(Constants.PREFERENCES_EQUALIZER_ON, false)) {
                getEqualizerController();
            }

            mediaPlayerLooper = Looper.myLooper();
            mediaPlayerHandler = new Handler(mediaPlayerLooper);

            if (runListenersOnInit) {
                onSongsChanged();
                onSongProgress();
                onStateUpdate();
            }

            Looper.loop();
        }
    }, "DownloadService").start();

    Util.registerMediaButtonEventReceiver(this);
    audioNoisyReceiver = new AudioNoisyReceiver();
    registerReceiver(audioNoisyReceiver, audioNoisyIntent);

    if (mRemoteControl == null) {
        // Use the remote control APIs (if available) to set the playback state
        mRemoteControl = RemoteControlClientBase.createInstance();
        ComponentName mediaButtonReceiverComponent = new ComponentName(getPackageName(),
                MediaButtonIntentReceiver.class.getName());
        mRemoteControl.register(this, mediaButtonReceiverComponent);
    }

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
    wakeLock.setReferenceCounted(false);

    WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "downloadServiceLock");

    try {
        timerDuration = Integer.parseInt(prefs.getString(Constants.PREFERENCES_KEY_SLEEP_TIMER_DURATION, "5"));
    } catch (Throwable e) {
        timerDuration = 5;
    }
    sleepTimer = null;

    keepScreenOn = prefs.getBoolean(Constants.PREFERENCES_KEY_KEEP_SCREEN_ON, false);

    mediaRouter = new MediaRouteManager(this);

    instance = this;
    shufflePlayBuffer = new ShufflePlayBuffer(this);
    artistRadioBuffer = new ArtistRadioBuffer(this);
    lifecycleSupport.onCreate();

    if (Build.VERSION.SDK_INT >= 26) {
        Notifications.shutGoogleUpNotification(this);
    }
}

From source file:nuclei.media.playback.FallbackPlayback.java

/**
 * Try to get the system audio focus./*  w w w . j  a  v  a2 s  .com*/
 */
private void tryToGetAudioFocus() {
    if (mAudioFocus != AUDIO_FOCUSED) {
        int result = mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
                AudioManager.AUDIOFOCUS_GAIN);
        if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
            mAudioFocus = AUDIO_FOCUSED;
        }
    }
}

From source file:com.nextgis.maplibui.activity.ModifyAttributesActivity.java

@SuppressWarnings("deprecation")
protected void createSoundPool() {
    mSoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 100);
    mBeepId = mSoundPool.load(this, R.raw.beep, 1);
}

From source file:edu.missouri.bas.service.SensorService.java

@SuppressWarnings("deprecation")
@Override// w ww  . ja v a  2 s.  com
public void onCreate() {

    super.onCreate();
    Log.d(TAG, "Starting sensor service");
    mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
    soundsMap = new HashMap<Integer, Integer>();
    soundsMap.put(SOUND1, mSoundPool.load(this, R.raw.bodysensor_alarm, 1));
    soundsMap.put(SOUND2, mSoundPool.load(this, R.raw.voice_notification, 1));

    serviceContext = this;

    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    bluetoothMacAddress = mBluetoothAdapter.getAddress();
    mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    //Get location manager
    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    activityRecognition = new ActivityRecognitionScan(getApplicationContext());
    activityRecognition.startActivityRecognitionScan();

    mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);

    serviceWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "SensorServiceLock");
    serviceWakeLock.acquire();

    //Initialize start time
    stime = System.currentTimeMillis();

    //Setup calendar object
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(stime);

    /*
     * Setup notification manager
     */

    notification = new Notification(R.drawable.icon2, "Recorded", System.currentTimeMillis());
    notification.defaults = 0;
    notification.flags |= Notification.FLAG_ONGOING_EVENT;
    notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    Intent notifyIntent = new Intent(Intent.ACTION_MAIN);
    notifyIntent.setClass(this, MainActivity.class);

    /*
     * Display notification that service has started
     */
    notification.tickerText = "Sensor Service Running";
    PendingIntent contentIntent = PendingIntent.getActivity(SensorService.this, 0, notifyIntent,
            Notification.FLAG_ONGOING_EVENT);
    notification.setLatestEventInfo(SensorService.this, getString(R.string.app_name),
            "Recording service started at: " + cal.getTime().toString(), contentIntent);

    notificationManager.notify(SensorService.SERVICE_NOTIFICATION_ID, notification);

    // locationControl = new LocationControl(this, mLocationManager, 1000 * 60, 200, 5000);   

    IntentFilter activityResultFilter = new IntentFilter(XMLSurveyActivity.INTENT_ACTION_SURVEY_RESULTS);
    SensorService.this.registerReceiver(alarmReceiver, activityResultFilter);

    IntentFilter sensorDataFilter = new IntentFilter(SensorService.ACTION_SENSOR_DATA);
    SensorService.this.registerReceiver(alarmReceiver, sensorDataFilter);
    Log.d(TAG, "Sensor service created.");

    try {
        prepareIO();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    prepareAlarms();

    Intent startSensors = new Intent(SensorService.ACTION_START_SENSORS);
    this.sendBroadcast(startSensors);

    Intent scheduleCheckConnection = new Intent(SensorService.ACTION_SCHEDULE_CHECK);
    scheduleCheck = PendingIntent.getBroadcast(serviceContext, 0, scheduleCheckConnection, 0);
    mAlarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime() + 1000 * 60 * 5, 1000 * 60 * 5, scheduleCheck);
    mLocationClient = new LocationClient(this, this, this);
}

From source file:com.google.android.car.kitchensink.radio.RadioTestFragment.java

private void addHandlers() {
    mOpenRadio.setOnClickListener(new View.OnClickListener() {
        @Override/* w w  w. jav a2  s .c o m*/
        public void onClick(View v) {
            handleRadioStart();
            updateStates();
        }
    });
    mCloseRadio.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            handleRadioEnd();
            mToggleMuteRadio.setChecked(true);
            updateStates();
        }
    });
    mToggleMuteRadio.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (DBG) {
                Log.i(TAG, "Toggle mute radio");
            }
            mRadioTuner.setMute(!mRadioTuner.getMute());
            updateStates();
        }
    });
    mGetRadioFocus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (DBG) {
                Log.i(TAG, "Get radio focus");
            }
            try {
                mCarAudioManager.requestAudioFocus(mRadioFocusListener, mRadioAudioAttrib,
                        AudioManager.AUDIOFOCUS_GAIN, 0);
            } catch (CarNotConnectedException e) {
                //ignore for now
            }
            mHasRadioFocus = true;
            updateStates();
        }
    });
    mReleaseRadioFocus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (DBG) {
                Log.i(TAG, "Release radio focus");
            }
            mCarAudioManager.abandonAudioFocus(mRadioFocusListener, mRadioAudioAttrib);
            mHasRadioFocus = false;
            updateStates();
        }
    });
    mGetFocus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (DBG) {
                Log.i(TAG, "Get secondary focus");
            }
            mAudioManager.requestAudioFocus(mSecondaryFocusListener, AudioManager.STREAM_MUSIC,
                    AudioManager.AUDIOFOCUS_GAIN);
            mHasSecondaryFocus = true;
            updateStates();
        }
    });
    mReleaseFocus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (DBG) {
                Log.i(TAG, "Release secondary focus");
            }
            mAudioManager.abandonAudioFocus(mSecondaryFocusListener);
            mHasSecondaryFocus = false;
            updateStates();
        }
    });
    mRadioNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (DBG) {
                Log.i(TAG, "Next radio station");
            }
            if (mRadioTuner != null) {
                mRadioTuner.scan(RadioTuner.DIRECTION_UP, true);
            }
            updateStates();
        }
    });
    mRadioPrev.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (DBG) {
                Log.i(TAG, "Previous radio station");
            }
            if (mRadioTuner != null) {
                mRadioTuner.scan(RadioTuner.DIRECTION_DOWN, true);
            }
            updateStates();
        }
    });
    mRadioScanCancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (DBG) {
                Log.i(TAG, "Cancel radio scan");
            }
            if (mRadioTuner != null) {
                mRadioTuner.cancel();
            }
            updateStates();
        }
    });
    mRadioTuneToStation.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (DBG) {
                Log.i(TAG, "Tuning to station");
            }
            String station = mStationFrequency.getText().toString().trim();
            if (mRadioTuner != null && !(station.equals(""))) {
                mRadioTuner.tune(Integer.parseInt(station), 0);
            }
            resetMessages();
            updateMessages();
            updateStates();
        }
    });
    mRadioStepUp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (DBG) {
                Log.i(TAG, "Step up");
            }
            if (mRadioTuner != null) {
                mRadioTuner.step(RadioTuner.DIRECTION_UP, false);
            }
            resetMessages();
            updateMessages();
            updateStates();
        }
    });
    mRadioStepDown.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (DBG) {
                Log.i(TAG, "Step down");
            }
            if (mRadioTuner != null) {
                mRadioTuner.step(RadioTuner.DIRECTION_DOWN, false);
            }
            resetMessages();
            updateMessages();
            updateStates();
        }
    });
    mRadioGetProgramInfo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (DBG) {
                Log.i(TAG, "getProgramInformation");
            }
            if (mRadioTuner != null) {
                RadioManager.ProgramInfo[] programInfos = new RadioManager.ProgramInfo[1];
                mRadioTuner.getProgramInformation(programInfos);
                addLog(Log.INFO, "mRadioTuner.getProgramInformation() =>" + programInfos[0]);
            }
        }
    });
    mRadioBand.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (DBG) {
                Log.i(TAG, "Changing radio band");
            }
            if (mRadioTuner != null) {
                mRadioTuner.setConfiguration(mRadioBand.isChecked() ? mFmConfig : mAmConfig);
            }
            resetMessages();
            updateMessages();
            updateStates();
        }
    });
}

From source file:com.squalala.talkiewalkie.ui.activities.TalkActivity.java

@DebugLog
public int getMaxVolume() {
    return amanager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
}

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

/**
 * Prepare the first item in the list. And setup the listener for media player.
 *//*from www .  j av a 2  s . co m*/
private void initializePlayer() {
    // This service can be created for multiple times, the objects will only be created when
    // it is null
    if (mPlayer != null) {
        return;
    }
    mPlayer = new MediaPlayer();

    // Set playback state to none to create a valid playback state. So controls row can get
    // information about the supported actions.
    mMediaSession.setPlaybackState(createPlaybackStateBuilder(PlaybackStateCompat.STATE_NONE).build());
    // Activate media session
    if (!mMediaSession.isActive()) {
        mMediaSession.setActive(true);
    }

    // Set up listener and audio stream type for underlying music player.
    mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

    // set up listener when the player is prepared.
    mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            mInitialized = true;
            // Every time when the player is prepared (when new data source is set),
            // all listeners will be notified to toggle the UI to "pause" status.
            notifyUiWhenPlayerIsPrepared();

            // When media player is prepared, the callback functions will be executed to update
            // the meta data and playback state.
            onMediaSessionMetaDataChanged();
            mMediaSession
                    .setPlaybackState(createPlaybackStateBuilder(PlaybackStateCompat.STATE_PAUSED).build());
        }
    });

    // set up listener for player's error.
    mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
        @Override
        public boolean onError(MediaPlayer mediaPlayer, int what, int extra) {
            if (DEBUG) {
                PlaybackStateCompat.Builder builder = createPlaybackStateBuilder(
                        PlaybackStateCompat.STATE_ERROR);
                builder.setErrorMessage(PlaybackStateCompat.ERROR_CODE_APP_ERROR, MEDIA_PLAYER_ERROR_MESSAGE);
                mMediaSession.setPlaybackState(builder.build());
            }
            return true;
        }
    });

    // set up listener to respond the event when current music item is finished
    mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

        /**
         * Expected Interaction Behavior:
         * 1. If current media item's playing speed not equal to normal speed.
         *
         *    A. MEDIA_ACTION_REPEAT_ALL
         *       a. If current media item is the last one. The first music item in the list will
         *          be prepared, but it won't play until user press play button.
         *
         *          When user press the play button, the speed will be reset to normal (1.0f)
         *          no matter what the previous media item's playing speed is.
         *
         *       b. If current media item isn't the last one, next media item will be prepared,
         *          but it won't play.
         *
         *          When user press the play button, the speed will be reset to normal (1.0f)
         *          no matter what the previous media item's playing speed is.
         *
         *    B. MEDIA_ACTION_REPEAT_ONE
         *       Different with previous scenario, current item will go back to the start point
         *       again and play automatically. (The reason to enable auto play here is for
         *       testing purpose and to make sure our designed API is flexible enough to support
         *       different situations.)
         *
         *       No matter what the previous media item's playing speed is, in this situation
         *       current media item will be replayed in normal speed.
         *
         *    C. MEDIA_ACTION_REPEAT_NONE
         *       a. If current media is the last one. The service will be closed, no music item
         *          will be prepared to play. From the UI perspective, the progress bar will not
         *          be reset to the starting point.
         *
         *       b. If current media item isn't the last one, next media item will be prepared,
         *          but it won't play.
         *
         *          When user press the play button, the speed will be reset to normal (1.0f)
         *          no matter what the previous media item's playing speed is.
         *
         * @param mp Object of MediaPlayer
         */
        @Override
        public void onCompletion(MediaPlayer mp) {

            // When current media item finishes playing, always reset rewind/ fastforward state
            mFastForwardSpeedFactorIndex = 0;
            mRewindSpeedFactorIndex = 0;
            // Set player's playback speed back to normal
            mPlayer.setPlaybackParams(mPlayer.getPlaybackParams()
                    .setSpeed(mFastForwardSpeedFactors[mFastForwardSpeedFactorIndex]));
            // Pause the player, and update the status accordingly.
            mPlayer.pause();
            mMediaSession
                    .setPlaybackState(createPlaybackStateBuilder(PlaybackStateCompat.STATE_PAUSED).build());

            if (mRepeatState == MEDIA_ACTION_REPEAT_ALL && mCurrentIndex == mMediaItemList.size() - 1) {
                // if the repeat mode is enabled but the shuffle mode is not enabled,
                // will go back to the first music item to play
                if (mShuffleMode == PlaybackStateCompat.SHUFFLE_MODE_NONE) {
                    mCurrentIndex = 0;
                } else {
                    // Or will choose a music item from playing list randomly.
                    mCurrentIndex = generateMediaItemIndex();
                }
                mCurrentMediaItem = mMediaItemList.get(mCurrentIndex);
                // The ui will also be changed from playing state to pause state through
                // setDataSource() operation
                setDataSource();
            } else if (mRepeatState == MEDIA_ACTION_REPEAT_ONE) {
                // Play current music item again.
                // The ui will stay to be "playing" status for the reason that there is no
                // setDataSource() function call.
                mPlayer.start();
                mMediaSession.setPlaybackState(
                        createPlaybackStateBuilder(PlaybackStateCompat.STATE_PLAYING).build());
            } else if (mCurrentIndex < mMediaItemList.size() - 1) {
                if (mShuffleMode == PlaybackStateCompat.SHUFFLE_MODE_NONE) {
                    mCurrentIndex++;
                } else {
                    mCurrentIndex = generateMediaItemIndex();
                }
                mCurrentMediaItem = mMediaItemList.get(mCurrentIndex);
                // The ui will also be changed from playing state to pause state through
                // setDataSource() operation
                setDataSource();
            } else {
                // close the service when the playlist is finished
                // The PlaybackState will be updated to STATE_STOPPED. And onPlayComplete
                // callback will be called by attached glue.
                mMediaSession.setPlaybackState(
                        createPlaybackStateBuilder(PlaybackStateCompat.STATE_STOPPED).build());
                stopSelf();
            }
        }
    });

    final MediaPlayer.OnBufferingUpdateListener mOnBufferingUpdateListener = new MediaPlayer.OnBufferingUpdateListener() {
        @Override
        public void onBufferingUpdate(MediaPlayer mp, int percent) {
            mBufferedProgress = getDuration() * percent / 100;
            PlaybackStateCompat.Builder builder = createPlaybackStateBuilder(
                    PlaybackStateCompat.STATE_BUFFERING);
            builder.setBufferedPosition(mBufferedProgress);
            mMediaSession.setPlaybackState(builder.build());
        }
    };
    mPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
}

From source file:com.yamin.kk.service.AudioService.java

@TargetApi(Build.VERSION_CODES.FROYO)
private void changeAudioFocus(boolean gain) {
    if (!Util.isFroyoOrLater()) // NOP if not supported
        return;//ww  w.j av a  2s.co m

    audioFocusListener = new OnAudioFocusChangeListener() {
        @Override
        public void onAudioFocusChange(int focusChange) {
            if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK
                    || focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
                /*
                 * Lower the volume to 36% to "duck" when an alert or something
                 * needs to be played.
                 */
                LibVLC.getExistingInstance().setVolume(36);
            } else {
                LibVLC.getExistingInstance().setVolume(100);
            }
        }
    };

    AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
    if (gain)
        am.requestAudioFocus(audioFocusListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    else
        am.abandonAudioFocus(audioFocusListener);

}