Example usage for android.media AudioManager setStreamVolume

List of usage examples for android.media AudioManager setStreamVolume

Introduction

In this page you can find the example usage for android.media AudioManager setStreamVolume.

Prototype

public void setStreamVolume(int streamType, int index, int flags) 

Source Link

Document

Sets the volume index for a particular stream.

Usage

From source file:capstone.se491_phm.Alarm.java

public static void loudest(Context context, int stream) {
    AudioManager manager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    int loudest = manager.getStreamMaxVolume(stream);
    manager.setStreamVolume(stream, loudest, 0);
}

From source file:com.wifi.brainbreaker.mydemo.spydroid.api.RequestHandler.java

/** 
 * The implementation of all the possible requests is here
 * -> "sounds": returns a list of available sounds on the phone
 * -> "screen": returns the screen state (whether the app. is on the foreground or not)
 * -> "play": plays a sound on the phone
 * -> "set": update Spydroid's configuration
 * -> "get": returns Spydroid's configuration (framerate, bitrate...)
 * -> "state": returns a JSON containing information about the state of the application
 * -> "battery": returns an approximation of the battery level on the phone
 * -> "buzz": makes the phone buuz /* w  ww.  j  av  a  2s.  c o  m*/
 * -> "volume": sets or gets the volume 
 * @throws JSONException
 * @throws IllegalAccessException 
 * @throws IllegalArgumentException 
 **/
static private void exec(JSONObject object, StringBuilder response)
        throws JSONException, IllegalArgumentException, IllegalAccessException {

    SpydroidApplication application = SpydroidApplication.getInstance();
    Context context = application.getApplicationContext();

    String action = object.getString("action");

    // Returns a list of available sounds on the phone
    if (action.equals("sounds")) {
        Field[] raws = R.raw.class.getFields();
        response.append("[");
        for (int i = 0; i < raws.length - 1; i++) {
            response.append("\"" + raws[i].getName() + "\",");
        }
        response.append("\"" + raws[raws.length - 1].getName() + "\"]");
    }

    // Returns the screen state (whether the app. is on the foreground or not)
    else if (action.equals("screen")) {
        response.append(application.applicationForeground ? "\"1\"" : "\"0\"");
    }

    // Plays a sound on the phone
    else if (action.equals("play")) {
        Field[] raws = R.raw.class.getFields();
        for (int i = 0; i < raws.length; i++) {
            if (raws[i].getName().equals(object.getString("name"))) {
                mSoundPool.load(application, raws[i].getInt(null), 0);
            }
        }
        response.append("[]");
    }

    // Returns Spydroid's configuration (framerate, bitrate...)
    else if (action.equals("get")) {
        final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);

        response.append("{\"streamAudio\":" + settings.getBoolean("stream_audio", false) + ",");
        response.append("\"audioEncoder\":\""
                + (application.audioEncoder == SessionBuilder.AUDIO_AMRNB ? "AMR-NB" : "AAC") + "\",");
        response.append("\"streamVideo\":" + settings.getBoolean("stream_video", true) + ",");
        response.append("\"videoEncoder\":\""
                + (application.videoEncoder == SessionBuilder.VIDEO_H263 ? "H.263" : "H.264") + "\",");
        response.append("\"videoResolution\":\"" + application.videoQuality.resX + "x"
                + application.videoQuality.resY + "\",");
        response.append("\"videoFramerate\":\"" + application.videoQuality.framerate + " fps\",");
        response.append("\"videoBitrate\":\"" + application.videoQuality.bitrate / 1000 + " kbps\"}");

    }

    // Update Spydroid's configuration
    else if (action.equals("set")) {
        final JSONObject settings = object.getJSONObject("settings");
        final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        final Editor editor = prefs.edit();

        editor.putBoolean("stream_video", settings.getBoolean("stream_video"));
        application.videoQuality = VideoQuality.parseQuality(settings.getString("video_quality"));
        editor.putInt("video_resX", application.videoQuality.resX);
        editor.putInt("video_resY", application.videoQuality.resY);
        editor.putString("video_framerate", String.valueOf(application.videoQuality.framerate));
        editor.putString("video_bitrate", String.valueOf(application.videoQuality.bitrate / 1000));
        editor.putString("video_encoder", settings.getString("video_encoder").equals("H.263") ? "2" : "1");
        editor.putBoolean("stream_audio", settings.getBoolean("stream_audio"));
        editor.putString("audio_encoder", settings.getString("audio_encoder").equals("AMR-NB") ? "3" : "5");
        editor.commit();
        response.append("[]");

    }

    // Returns a JSON containing information about the state of the application
    else if (action.equals("state")) {

        Exception exception = application.lastCaughtException;

        response.append("{");

        if (exception != null) {

            // Used to display the message on the user interface
            String lastError = exception.getMessage();

            // Useful to display additional information to the user depending on the error
            StackTraceElement[] stack = exception.getStackTrace();
            StringBuilder builder = new StringBuilder(
                    exception.getClass().getName() + " : " + lastError + "||");
            for (int i = 0; i < stack.length; i++)
                builder.append("at " + stack[i].getClassName() + "." + stack[i].getMethodName() + " ("
                        + stack[i].getFileName() + ":" + stack[i].getLineNumber() + ")||");

            response.append("\"lastError\":\"" + (lastError != null ? lastError : "unknown error") + "\",");
            response.append("\"lastStackTrace\":\"" + builder.toString() + "\",");

        }

        response.append("\"activityPaused\":\"" + (application.applicationForeground ? "1" : "0") + "\"");
        response.append("}");

    }

    else if (action.equals("clear")) {
        application.lastCaughtException = null;
        response.append("[]");
    }

    // Returns an approximation of the battery level
    else if (action.equals("battery")) {
        response.append("\"" + application.batteryLevel + "\"");
    }

    // Makes the phone vibrates for 300ms
    else if (action.equals("buzz")) {
        Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(300);
        response.append("[]");
    }

    // Sets or gets the system's volume
    else if (action.equals("volume")) {
        AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        if (object.has("set")) {
            audio.setStreamVolume(AudioManager.STREAM_MUSIC, object.getInt("set"),
                    AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
            response.append("[]");
        } else {
            int max = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            int current = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
            response.append("{\"max\":" + max + ",\"current\":" + current + "}");
        }
    }

}

From source file:nth.com.ares.utils.Utils.java

public static void playSound(Context context, int sound) {
    AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    int currentVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
    int maxVolume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    float percent = 0.7f;
    int seventyVolume = (int) (maxVolume * percent);
    audio.setStreamVolume(AudioManager.STREAM_MUSIC, seventyVolume, 0);
    final MediaPlayer mp = MediaPlayer.create(context, sound);
    mp.start();/*from w  w  w  . j a  v  a 2 s  .  c om*/
}

From source file:com.apps.howard.vicissitude.services.NotificationService.java

private void maybeOverrideVolumeBeforeNotify() {

    boolean settingsOverrideVolumeEnabled = prefs.getBoolean(this.getString(R.string.pref_override_volume_key),
            false);/*from   w w  w  .j av a  2 s. co m*/
    int settingsOverrideVolume = prefs.getInt(this.getString(R.string.pref_alert_volume_key), 1);

    AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    if (settingsOverrideVolumeEnabled) {
        audioManager.setStreamVolume(AudioManager.STREAM_ALARM, settingsOverrideVolume, 0);
    }
}

From source file:u.ready_wisc.MenuActivity.java

@Override
public void onClick(View v) {
    //TODO fix action bar or disable completely
    if ((v.getId() == (R.id.prepareButton)) || (v.getId() == (R.id.prepareMenuButton))) {
        Intent i = new Intent(MenuActivity.this, Prep_Main.class);
        startActivity(i);//from w  w  w. j  ava  2  s .  co m
    } else if (v.getId() == (R.id.reportDamageButton) || v.getId() == (R.id.emergencyMenuButton)) {
        Intent i = new Intent(MenuActivity.this, Emergency.class);
        MenuActivity.this.startActivity(i);
    } else if (v.getId() == (R.id.disasterResourcesButton) || v.getId() == (R.id.disasterMenuButton)) {
        Intent i = new Intent(MenuActivity.this, ResourcesActivity.class);
        MenuActivity.this.startActivity(i);
    } else if (v.getId() == (R.id.typeDisasterButton)) {
        Intent i = new Intent(MenuActivity.this, DisastersType.class);
        MenuActivity.this.startActivity(i);
    } else if (v.getId() == (R.id.SOSMenubutton)) {
        if (!sosTone) {

            //sets device volume to maximum
            AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            am.setStreamVolume(AudioManager.STREAM_MUSIC, am.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);

            //begins looping tone
            mp.setLooping(true);
            sosTone = true;
            mp.start();
        }

    } else if (v.getId() == (R.id.FlashlightMenuButton)) {
        //check to see if device has a camera with flash
        if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {

            Log.e("err", "Device has no camera!");
            //Return from the method, do nothing after this code block
            return;
        }
        // if camera has flash toggle on and off
        else {
            // boolean to check status of camera flash
            if (!isFlashOn) {

                //if flash is off, toggle boolean to on and turn on flash
                isFlashOn = true;
                camera = Camera.open();
                Camera.Parameters parameters = camera.getParameters();
                parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                camera.setParameters(parameters);
                camera.startPreview();

            } else {

                //if flash is on turn boolean to false and turn off flash
                isFlashOn = false;
                camera.stopPreview();
                camera.release();
                camera = null;

            }
        }
    } else {

        //stops looping sound
        Log.d("Sound test", "Stopping sound");
        mp.setLooping(false);
        mp.pause();
        sosTone = false;
    }
}

From source file:com.brayanarias.alarmproject.activity.AlarmScreenActivity.java

@Override
protected void onDestroy() {
    Log.e(TAG, "on Destroy method");
    if (task != null) {
        task.cancel(true);//ww  w . j  a  v  a  2s.  c om
    }
    AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    audioManager.setStreamVolume(AudioManager.STREAM_ALARM, actualVolume, 0);
    if (mediaPlayer != null) {
        mediaPlayer.stop();
        mediaPlayer.release();
    }
    if (vibrator != null) {
        vibrator.cancel();
    }
    NotificationManager alarmNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    alarmNotificationManager.cancelAll();
    if (flag) {
        int deleteAlarm = getIntent().getIntExtra(Constant.alarmDeleteAfterKey, 0);
        int id = getIntent().getIntExtra(Constant.alarmIdKey, -1);

        if (deleteAlarm == 1) {
            DataBaseManager dataBaseManager = DataBaseManager.getInstance(getApplicationContext());
            AlarmDataBase.deleteAlarm(id, dataBaseManager);
        } else if (getIntent().getStringExtra(Constant.alarmDaysKey).equals("0000000")) {
            DataBaseManager dataBaseManager = DataBaseManager.getInstance(getApplicationContext());
            Alarm alarm = AlarmDataBase.getAlarmById(dataBaseManager, id);
            alarm.setActivated(0);
            AlarmDataBase.updateAlarm(alarm, dataBaseManager);
        }
        AlarmReceiver.setAlarms(getApplicationContext());
    }
    super.onDestroy();
}

From source file:org.chromium.latency.walt.AudioFragment.java

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.button_start_audio:
        chartLayout.setVisibility(View.GONE);
        disableButtons();// w  ww  .j a va 2  s .co  m
        AudioTestType testType = getSelectedTestType();
        switch (testType) {
        case CONTINUOUS_PLAYBACK:
        case CONTINUOUS_RECORDING:
        case DISPLAY_WAVEFORM:
            audioTest.setAudioMode(AudioTest.AudioMode.CONTINUOUS);
            audioTest.setPeriod(AudioTest.CONTINUOUS_TEST_PERIOD);
            break;
        case COLD_PLAYBACK:
        case COLD_RECORDING:
            audioTest.setAudioMode(AudioTest.AudioMode.CONTINUOUS);
            audioTest.setPeriod(AudioTest.COLD_TEST_PERIOD);
            break;
        }
        if (testType == AudioTestType.DISPLAY_WAVEFORM) {
            // Only need to record 1 beep to display wave
            audioTest.setRecordingRepetitions(1);
        } else {
            audioTest.setRecordingRepetitions(
                    getIntPreference(getContext(), R.string.preference_audio_in_reps, 5));
        }
        if (testType == AudioTestType.CONTINUOUS_PLAYBACK || testType == AudioTestType.COLD_PLAYBACK
                || testType == AudioTestType.CONTINUOUS_RECORDING || testType == AudioTestType.COLD_RECORDING) {
            latencyChart.setVisibility(View.VISIBLE);
            latencyChart.clearData();
            latencyChart.setLegendEnabled(false);
            final String description = getResources().getStringArray(R.array.audio_mode_array)[modeSpinner
                    .getSelectedItemPosition()] + " [ms]";
            latencyChart.setDescription(description);
        }
        switch (testType) {
        case CONTINUOUS_RECORDING:
        case COLD_RECORDING:
        case DISPLAY_WAVEFORM:
            attemptRecordingTest();
            break;
        case CONTINUOUS_PLAYBACK:
        case COLD_PLAYBACK:
            // Set media volume to max
            AudioManager am = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
            am.setStreamVolume(AudioManager.STREAM_MUSIC, am.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
            audioTest.beginPlaybackMeasurement();
            break;
        }
        break;
    case R.id.button_stop_audio:
        audioTest.stopTest();
        break;
    case R.id.button_close_chart:
        chartLayout.setVisibility(View.GONE);
        break;
    }
}

From source file:com.bdcorps.videonews.MainActivity.java

public void speak(String s) {
    Log.d("SSS", "to speak: " + s);
    if (s != null) {
        HashMap<String, String> myHashAlarm = new HashMap<String, String>();
        myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_ALARM));
        myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "completed");
        AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int amStreamMusicMaxVol = am.getStreamMaxVolume(am.STREAM_SYSTEM);
        am.setStreamVolume(am.STREAM_SYSTEM, amStreamMusicMaxVol, 0);
        mTts.speak(s, TextToSpeech.QUEUE_FLUSH, myHashAlarm);
    } else {//from   ww w .j a v  a 2s .c  om
        speakNext();
    }
}

From source file:com.brayanarias.alarmproject.activity.AlarmScreenActivity.java

private void playRingtone(String tone) {
    mediaPlayer = new MediaPlayer();
    try {/*from   ww w .  ja va2  s.  com*/
        Uri ringtoneUri;
        if (tone.equals("default")) {
            ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
        } else {
            ringtoneUri = Uri.parse(tone);
        }

        if (ringtoneUri != null) {
            mediaPlayer.setDataSource(this, ringtoneUri);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
            mediaPlayer.setLooping(true);
            mediaPlayer.prepare();
            AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            actualVolume = audioManager.getStreamVolume(AudioManager.STREAM_ALARM);
            incrementVolume();
            mediaPlayer.start();
            audioManager.setStreamVolume(AudioManager.STREAM_ALARM, 1, 0);
        }
    } catch (Exception e) {
        Log.e(tag, e.getLocalizedMessage(), e);
    }
}

From source file:org.protocoderrunner.base.BaseActivity.java

public void setVolume(int value) {
    AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    int maxValue = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    float val = (float) (value / 100.0 * maxValue);

    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, Math.round(val),
            AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
}