Example usage for android.content Context AUDIO_SERVICE

List of usage examples for android.content Context AUDIO_SERVICE

Introduction

In this page you can find the example usage for android.content Context AUDIO_SERVICE.

Prototype

String AUDIO_SERVICE

To view the source code for android.content Context AUDIO_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.media.AudioManager for handling management of volume, ringer modes and audio routing.

Usage

From source file:org.fdroid.enigtext.notifications.MessageNotifier.java

private static void sendInThreadNotification(Context context) {
    try {//from  w w w .jav a2 s.c  o m
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);

        if (!sp.getBoolean(ApplicationPreferencesActivity.IN_THREAD_NOTIFICATION_PREF, true)) {
            return;
        }

        String ringtone = sp.getString(ApplicationPreferencesActivity.RINGTONE_PREF, null);

        if (ringtone == null)
            return;

        Uri uri = Uri.parse(ringtone);
        MediaPlayer player = new MediaPlayer();
        player.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
        player.setDataSource(context, uri);
        player.setLooping(false);
        player.setVolume(0.25f, 0.25f);
        player.prepare();

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

        audioManager.requestAudioFocus(null, AudioManager.STREAM_NOTIFICATION,
                AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);

        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                audioManager.abandonAudioFocus(null);
            }
        });

        player.start();
    } catch (IOException ioe) {
        Log.w("MessageNotifier", ioe);
    }
}

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

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mAudioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);

    // Initialize instance variables.
    TextureView textureView = (TextureView) getActivity().findViewById(R.id.texture_view);
    textureView.setSurfaceTextureListener(this);

    setBackgroundType(BACKGROUND_TYPE);/*from  w  ww . jav a 2 s .  c o  m*/

    // Set up listener.
    setOnItemViewClickedListener(new ItemViewClickedListener());
}

From source file:com.jtxdriggers.android.ventriloid.VentriloidService.java

@Override
public void onCreate() {
    stopForeground(true);/*from   www .  j  av  a  2s  .co  m*/

    new Thread(new Runnable() {
        @Override
        public void run() {
            Looper.prepare();
            handler = new Handler();
            Looper.loop();
        }
    }).start();

    items = new ItemData(this);
    player = new Player(this);
    recorder = new Recorder(this);

    prefs = PreferenceManager.getDefaultSharedPreferences(this);

    if (prefs.getString("notification_type", "Text to Speech").equals("Text to Speech")) {
        ttsActive = true;
        tts = new TextToSpeech(VentriloidService.this, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == TextToSpeech.SUCCESS)
                    ttsActive = true;
                else {
                    ttsActive = false;
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), "TTS Initialization faled.",
                                    Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    } else if (prefs.getString("notification_type", "Text to Speech").equals("Ringtone"))
        ringtoneActive = true;

    registerReceiver(activityReceiver, new IntentFilter(ACTIVITY_RECEIVER));

    nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    voiceActivation = prefs.getBoolean("voice_activation", false);
    threshold = voiceActivation ? 55.03125 : -1;
    vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    vibrate = prefs.getBoolean("vibrate", true);

    queue = new ConcurrentLinkedQueue<VentriloEventData>();

    //VentriloInterface.debuglevel(65535);
    new Thread(eventHandler).start();
}

From source file:com.shinymayhem.radiopresets.ServiceRadioPlayer.java

@Override
public void onCreate() {
    if (LOCAL_LOGV)
        log("onCreate()", "v");

    //initialize managers
    if (mNotificationManager == null) {
        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    }/*from   ww w. j a  va  2  s.com*/
    if (mAudioManager == null) {
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    }

    //remove pending intents if they exist
    stopInfo();
    //listen for network changes and media buttons
    registerNetworkReceiver();
    registerButtonReceiver();
}

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 //from   w  w  w .ja  va2 s  .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: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 w  w w  . jav a2s . co m
        speakNext();
    }
}

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

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

public SpeechController(TalkBackService context, FeedbackController feedbackController) {
    if (feedbackController == null)
        throw new IllegalStateException();

    mService = context;/*from  w  w  w. jav  a2  s .  com*/
    mService.addServiceStateListener(new TalkBackService.ServiceStateListener() {
        @Override
        public void onServiceStateChanged(int newState) {
            if (newState == TalkBackService.SERVICE_STATE_ACTIVE) {
                setProximitySensorState(true);
            } else if (newState == TalkBackService.SERVICE_STATE_SUSPENDED) {
                setProximitySensorState(false);
            }
        }
    });

    mAudioManager = (AudioManager) mService.getSystemService(Context.AUDIO_SERVICE);

    mFailoverTts = new FailoverTextToSpeech(context);
    mFailoverTts.addListener(new FailoverTextToSpeech.FailoverTtsListener() {
        @Override
        public void onTtsInitialized(boolean wasSwitchingEngines) {
            SpeechController.this.onTtsInitialized(wasSwitchingEngines);
        }

        @Override
        public void onUtteranceCompleted(String utteranceId, boolean success) {
            // Utterances from FailoverTts are considered fragments in SpeechController
            SpeechController.this.onFragmentCompleted(utteranceId, success, true /* advance */);
        }
    });

    mFeedbackController = feedbackController;
    mInjectFullScreenReadCallbacks = false;

    prefListener = new OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
            if ((key == null) || (prefs == null)) {
                return;
            }

            reloadPreferences(prefs);
        }
    };
    final SharedPreferences prefs = SharedPreferencesUtils.getSharedPreferences(context);
    // Handles preference changes that affect speech.
    prefs.registerOnSharedPreferenceChangeListener(prefListener);
    reloadPreferences(prefs);

    mScreenIsOn = true;
    mVoiceRecognitionChecker = new VoiceRecognitionChecker();
}

From source file:count.ly.messaging.CrashDetails.java

/**
 * Checks if device is muted.//from  w  w  w. jav  a2  s .c  om
 */
static String isMuted(Context context) {
    AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    switch (audio.getRingerMode()) {
    case AudioManager.RINGER_MODE_SILENT:
        return "true";
    case AudioManager.RINGER_MODE_VIBRATE:
        return "true";
    default:
        return "false";
    }
}

From source file:com.securecomcode.text.notifications.MessageNotifier.java

private static void sendInThreadNotification(Context context) {
    try {/*from w  ww. j  a va2s  .c o  m*/
        if (!TextSecurePreferences.isInThreadNotifications(context)) {
            return;
        }

        String ringtone = TextSecurePreferences.getNotificationRingtone(context);

        if (ringtone == null)
            return;

        Uri uri = Uri.parse(ringtone);
        MediaPlayer player = new MediaPlayer();
        player.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
        player.setDataSource(context, uri);
        player.setLooping(false);
        player.setVolume(0.25f, 0.25f);
        player.prepare();

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

        audioManager.requestAudioFocus(null, AudioManager.STREAM_NOTIFICATION,
                AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);

        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                audioManager.abandonAudioFocus(null);
            }
        });

        player.start();
    } catch (IOException ioe) {
        Log.w("MessageNotifier", ioe);
    }
}