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:com.example.rttytranslator.Dsp_service.java

public void startAudio() {
    if (!_enableDecoder)
        return;/* w  ww  . j  a  va  2 s  .  c om*/

    //boolean mic = this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_MICROPHONE);

    System.out.println("isRecording: " + isRecording);

    if (!isRecording) {
        isRecording = true;

        buffsize = AudioRecord.getMinBufferSize(8000, AudioFormat.CHANNEL_IN_MONO,
                AudioFormat.ENCODING_PCM_16BIT);
        buffsize = Math.max(buffsize, 3000);

        mRecorder = new AudioRecord(AudioSource.MIC, 8000, AudioFormat.CHANNEL_IN_MONO,
                AudioFormat.ENCODING_PCM_16BIT, buffsize);

        mPlayer = new AudioTrack(AudioManager.STREAM_MUSIC, 8000, AudioFormat.CHANNEL_OUT_MONO,
                AudioFormat.ENCODING_PCM_16BIT, 2 * buffsize, AudioTrack.MODE_STREAM);

        if (enableEcho) {
            AudioManager manager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            manager.setMode(AudioManager.MODE_IN_CALL);
            manager.setSpeakerphoneOn(true);
        }

        if (mRecorder.getState() != AudioRecord.STATE_INITIALIZED) {

            mRecorder = new AudioRecord(AudioSource.DEFAULT, 8000, AudioFormat.CHANNEL_IN_MONO,
                    AudioFormat.ENCODING_PCM_16BIT, buffsize);

        }

        mRecorder.startRecording();
        System.out.println("STARTING THREAD");
        Thread ct = new captureThread();

        ct.start();
    }
}

From source file:com.royer.bangstopwatch.app.StopwatchFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    Log.d(TAG, "Enter onActivityCreated...");

    InitTimeDisplayView();//  w  w w.ja v a  2s.co  m

    mLapList = (ListView) getView().findViewById(R.id.listLap);
    this.registerForContextMenu(mLapList);

    btnStart = (Button) getView().findViewById(R.id.btnStart);
    btnStart.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (state == STATE_NONE) {
                // detect does device support record ?
                if (AudioRecord.getMinBufferSize(44100, AudioFormat.CHANNEL_IN_MONO,
                        AudioFormat.ENCODING_PCM_16BIT) < 0) {
                    Context context = getActivity().getApplicationContext();

                    Toast toast = Toast.makeText(context, R.string.strNoRecorder, 5);
                    toast.show();
                    return;
                }

                AudioManager audiomanager = (AudioManager) getActivity()
                        .getSystemService(Context.AUDIO_SERVICE);
                Log.d(TAG, "AudioMode = " + audiomanager.getMode());
                if (audiomanager.getMode() != AudioManager.MODE_NORMAL) {
                    Context context = getActivity().getApplicationContext();

                    Toast toast = Toast.makeText(context, R.string.strInCalling, 5);
                    toast.show();
                    return;
                }

                state = STATE_COUNTDOWN;
                DialogFragment newFragment = CountdownDialog.NewInstance(5, getTag());
                newFragment.show(getFragmentManager(), "countdownDialog");

            } else {
                changeState();
                state = STATE_NONE;
                updateRealElapseTime();
                printTime();

                // unBind Recordservice
                if (mBound) {
                    mService.stopRecord();
                    mService.unsetBang();
                    getActivity().unbindService(mConnection);
                    getActivity().stopService(new Intent(getActivity(), RecordService.class));
                    mBound = false;
                }
            }
            ((MainActivity) getActivity()).EnableTab(1, state == STATE_NONE);
        }
    });

    if (savedInstanceState != null) {

        Log.d(TAG, "savedInstanceState " + savedInstanceState.toString());
        _timekeeper = savedInstanceState.getParcelable(STATE_TIMEKEEPER);
        mLapManager = savedInstanceState.getParcelable(STATE_LAPS);
        state = savedInstanceState.getInt(STATE_STATE);
        mBound = savedInstanceState.getBoolean(STATE_BOUNDING);
        ((MainActivity) getActivity()).EnableTab(1, state == STATE_NONE);

    } else {
        Log.d(TAG, "savedInstanceState == NULL");
        if (_timekeeper == null)
            _timekeeper = new Timekeeper();
        if (mLapManager == null)
            mLapManager = new LapManager();
    }
    InitLapList();

    printTime();
    updateState();

    Log.d(TAG, "Leave OnActivityCreated...");
}

From source file:de.badaix.snapcast.MainActivity.java

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

    for (int rate : new int[] { 8000, 11025, 16000, 22050, 44100, 48000 }) { // add the rates you wish to check against
        Log.d(TAG, "Samplerate: " + rate);
        int bufferSize = AudioRecord.getMinBufferSize(rate, AudioFormat.CHANNEL_OUT_STEREO,
                AudioFormat.ENCODING_PCM_16BIT);
        if (bufferSize > 0) {
            Log.d(TAG, "Samplerate: " + rate + ", buffer: " + bufferSize);
        }/*from w  w w  .j a v  a  2s .  c  o m*/
    }

    AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        String rate = audioManager.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE);
        nativeSampleRate = Integer.valueOf(rate);
        //            String size = audioManager.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER);
        //            tvInfo.setText("Sample rate: " + rate + ", buffer size: " + size);
    }

    coordinatorLayout = (CoordinatorLayout) findViewById(R.id.myCoordinatorLayout);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(sectionsPagerAdapter);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);
    mViewPager.setVisibility(View.GONE);

    setActionbarSubtitle("Host: no Snapserver found");

    new Thread(new Runnable() {
        @Override
        public void run() {
            Log.d(TAG, "copying snapclient");
            Setup.copyBinAsset(MainActivity.this, "snapclient", "snapclient");
            Log.d(TAG, "done copying snapclient");
        }
    }).start();

    sectionsPagerAdapter.setHideOffline(Settings.getInstance(this).getBoolean("hide_offline", false));
}

From source file:com.murati.oszk.audiobook.playback.LocalPlayback.java

public LocalPlayback(Context context, MusicProvider musicProvider) {
    Context applicationContext = context.getApplicationContext();
    this.mContext = applicationContext;
    this.mMusicProvider = musicProvider;

    this.mAudioManager = (AudioManager) applicationContext.getSystemService(Context.AUDIO_SERVICE);
    // Create the Wifi lock (this does not acquire the lock, this just creates it)
    this.mWifiLock = ((WifiManager) applicationContext.getSystemService(Context.WIFI_SERVICE))
            .createWifiLock(WifiManager.WIFI_MODE_FULL, "uAmp_lock");
}

From source file:androidx.media.MediaSession2ImplBase.java

MediaSession2ImplBase(Context context, MediaSessionCompat sessionCompat, String id, MediaPlayerBase player,
        MediaPlaylistAgent playlistAgent, VolumeProviderCompat volumeProvider, PendingIntent sessionActivity,
        Executor callbackExecutor, SessionCallback callback) {
    mContext = context;//from  ww  w  .j  a va2 s. c  o  m
    mHandlerThread = new HandlerThread("MediaController2_Thread");
    mHandlerThread.start();
    mHandler = new Handler(mHandlerThread.getLooper());

    mSessionCompat = sessionCompat;
    mSession2Stub = new MediaSession2StubImplBase(this);
    mSessionCompat.setCallback(mSession2Stub, mHandler);
    mSessionCompat.setSessionActivity(sessionActivity);

    mId = id;
    mCallback = callback;
    mCallbackExecutor = callbackExecutor;
    mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);

    // TODO: Set callback values properly
    mPlayerEventCallback = new MyPlayerEventCallback(this);
    mPlaylistEventCallback = new MyPlaylistEventCallback(this);

    // Infer type from the id and package name.
    String libraryService = getServiceName(context, MediaLibraryService2.SERVICE_INTERFACE, id);
    String sessionService = getServiceName(context, MediaSessionService2.SERVICE_INTERFACE, id);
    if (sessionService != null && libraryService != null) {
        throw new IllegalArgumentException(
                "Ambiguous session type. Multiple" + " session services define the same id=" + id);
    } else if (libraryService != null) {
        mSessionToken = new SessionToken2(Process.myUid(), TYPE_LIBRARY_SERVICE, context.getPackageName(),
                libraryService, id, mSessionCompat.getSessionToken());
    } else if (sessionService != null) {
        mSessionToken = new SessionToken2(Process.myUid(), TYPE_SESSION_SERVICE, context.getPackageName(),
                sessionService, id, mSessionCompat.getSessionToken());
    } else {
        mSessionToken = new SessionToken2(Process.myUid(), TYPE_SESSION, context.getPackageName(), null, id,
                mSessionCompat.getSessionToken());
    }
    updatePlayer(player, playlistAgent, volumeProvider);
}

From source file:com.microsoft.mimickeralarm.appcore.AlarmMainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_fragment);
    String packageName = getApplicationContext().getPackageName();
    mPreferences = getSharedPreferences(packageName, MODE_PRIVATE);
    PreferenceManager.setDefaultValues(this, R.xml.pref_global, false);
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    AlarmNotificationManager.get(this).handleNextAlarmNotificationStatus();

    UUID alarmId = (UUID) getIntent().getSerializableExtra(AlarmScheduler.ARGS_ALARM_ID);
    if (alarmId != null) {
        showAlarmSettingsFragment(alarmId.toString());
    }/*from   w w w  .j  a  va2s . c o m*/

    Logger.init(this);
}

From source file:com.google.android.car.kitchensink.volume.VolumeTestFragment.java

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
        @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.volume_test, container, false);

    mVolumeList = (ListView) v.findViewById(R.id.volume_list);
    mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);

    mRefreshButton = (Button) v.findViewById(R.id.refresh);
    mAdapter = new VolumeAdapter(getContext(), R.layout.volume_item, mVolumeInfos, this);
    mVolumeList.setAdapter(mAdapter);// ww w . j  a va  2s . c  o  m

    mRefreshButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            initVolumeInfo();
        }
    });

    mCarEmulator = CarEmulator.create(getContext());
    mCar = mCarEmulator.getCar();
    try {
        mCarAudioManager = (CarAudioManager) mCar.getCarManager(Car.AUDIO_SERVICE);
        initVolumeInfo();
        mCarAudioManager.setVolumeController(mVolumeController);
    } catch (CarNotConnectedException e) {
        throw new RuntimeException(e); // Should never occur in car emulator.
    }

    mVolumeUp = (Button) v.findViewById(R.id.volume_up);
    mVolumeDown = (Button) v.findViewById(R.id.volume_down);

    mVolumeUp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mCarEmulator.injectKey(KeyEvent.KEYCODE_VOLUME_UP);
        }
    });

    mVolumeDown.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mCarEmulator.injectKey(KeyEvent.KEYCODE_VOLUME_DOWN);
        }
    });

    return v;
}

From source file:com.mine.psf.PsfPlaybackService.java

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

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
    mWakeLock.setReferenceCounted(false);
    Log.d(LOGTAG, "onCreate, Acquire Wake Lock");

    PsfAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    PsfControlResponder = new ComponentName(getPackageName(), RemoteControlReceiver.class.getName());
    PsfAudioManager.registerMediaButtonEventReceiver(PsfControlResponder);

    mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    reloadQueue();//from  w ww  . j a v  a 2 s.  c  o  m

    // If the service was idle, but got killed before it stopped itself, the
    // system will relaunch it. Make sure it gets stopped again in that case.
    Message msg = mDelayedStopHandler.obtainMessage();
    mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);

    // Register sd card mount/unmount listener
    registerExternalStorageListener();

    // Register noisy listener, it should
    // 1) Playing with headset, unplug headset, sound should be paused;
    // 2) Playing with speaker, plug headset, sound should keep playing.
    registerNoisyListener();
}

From source file:com.whereismyfriend.GcmIntentService.java

private void sendNotification(String msg, String badge, String type) {
    mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

    int notification_id;
    PendingIntent contentIntent;/*from w  w w.j av a2s  . c  o  m*/
    if (type.compareTo("s") == 0) {
        contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, Solicitudes.class), 0);
        notification_id = 0;
    } else {
        contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, Mapa.class), 0);
        notification_id = 1;
    }

    if (Integer.parseInt(badge) > 1) {
        if (type.compareTo("s") == 0)
            msg = getResources().getString(R.string.push_no_leidas_1) + " " + badge + " "
                    + getResources().getString(R.string.push_no_leidas_2);
        else
            msg = getResources().getString(R.string.push_no_leidas_1_acc) + " " + badge + " "
                    + getResources().getString(R.string.push_no_leidas_2_acc);
    }

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_stat_gcm).setContentTitle(getResources().getString(R.string.app_name))
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)).setContentText(msg)
            .setAutoCancel(true);

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

    switch (am.getRingerMode()) {
    case AudioManager.RINGER_MODE_SILENT:
        mBuilder.setLights(Color.CYAN, 3000, 3000);
        break;
    case AudioManager.RINGER_MODE_VIBRATE:
        mBuilder.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
        mBuilder.setLights(Color.CYAN, 3000, 3000);
        break;
    case AudioManager.RINGER_MODE_NORMAL:
        mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
        mBuilder.setLights(Color.CYAN, 3000, 3000);
        break;
    }

    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(notification_id, mBuilder.build());
}

From source file:net.globide.coloring_book.MainActivity.java

/**
 * private RelativeLayout mRlMainRight; private RelativeLayout mRlMainLeft;
 * Implements onCreate().//from w ww .j  av a 2 s  .  c  o m
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Set the activity to full screen mode.
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    // Add default content.
    setContentView(R.layout.activity_main);

    // Determine whether or not the current device is a tablet.
    MainActivity.sIsTablet = getResources().getBoolean(R.bool.isTablet);
    MainActivity.sIsSmall = getResources().getBoolean(R.bool.isSmall);
    MainActivity.sIsNormal = getResources().getBoolean(R.bool.isNormal);
    MainActivity.sIsLarge = getResources().getBoolean(R.bool.isLarge);
    MainActivity.sIsExtraLarge = getResources().getBoolean(R.bool.isExtraLarge);

    // Get stored preferences, if any.
    mSharedPreferences = getSharedPreferences(sFilename, 0);
    // Setup the editor in this function, so it can be used anywhere else if
    // needed.
    mEditor = mSharedPreferences.edit();

    // If this activity continues playing the music, start the media player
    // if the phone is not muted
    AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    // This should only run once at the start of the application.
    switch (audio.getRingerMode()) {
    case AudioManager.RINGER_MODE_SILENT:
        if (!MusicManager.sIsManualSound) {
            // Set the preferences to turn music off.
            mEditor.putBoolean("tbSettingsMusicIsChecked", false);
            mEditor.commit();
        }
        break;
    }

    // This should only run once at the start of the application.
    if (!MusicManager.sIsManualSound) {
        // Set the preferences as early as possible in MusicManager.
        MusicManager.setPreferences(mSharedPreferences);

        // Update actual status
        MusicManager.updateVolume();
        MusicManager.updateStatusFromPrefs(this);

        // This method can no longer be invoked to turn off the
        // sound once the user has manually turned sound on.
        MusicManager.sIsManualSound = true;
    }

    // Store the preference values in local variables.
    boolean tbSettingsMusicIsChecked = mSharedPreferences.getBoolean("tbSettingsMusicIsChecked", false);

    // Set whether music is on or not in the Music Manager
    if (tbSettingsMusicIsChecked) {
        MusicManager.start(this, MusicManager.MUSIC_A);
    }

    // Attach views to their corresponding resource ids.
    mIbPagerLeft = (ImageButton) findViewById(R.id.ibPagerLeft);
    mIbPagerRight = (ImageButton) findViewById(R.id.ibPagerRight);
    mIbMainHelp = (ImageButton) findViewById(R.id.ibMainHelp);
    mIbMainSettings = (ImageButton) findViewById(R.id.ibMainSettings);
    mRlMainLeftTop = (RelativeLayout) findViewById(R.id.rlMainLeftTop);
    mRlMainRightTop = (RelativeLayout) findViewById(R.id.rlMainRightTop);

    /*
     * This screen needs to be dynamically positioned to fit each screen
     * size fluidly.
     */

    // Get the screen metrics.
    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    int screenHeight = dm.heightPixels;

    // Determine the floor section size
    Drawable image = this.getResources().getDrawable(R.drawable.floor);
    // Store the height locally
    int floorHeight = image.getIntrinsicHeight();

    // Determine the title section size

    // Get the top spacing (THIS IS ALSO DEFINED EXACTLY AS IT IS HERE IN
    // EACH XML FILE.
    int topSpacing = 0;

    if (MainActivity.sIsTablet) {
        if (MainActivity.sIsSmall) {
            topSpacing = 18;
        } else if (MainActivity.sIsNormal) {
            topSpacing = 24;
        } else if (MainActivity.sIsLarge) {
            topSpacing = 27;
        } else if (MainActivity.sIsExtraLarge) {
            topSpacing = 30;
        }
    } else {
        topSpacing = 12;
    }

    Drawable imageTitle = this.getResources().getDrawable(R.drawable.main_title);
    // Store the height locally
    int titleHeight = imageTitle.getIntrinsicHeight() + topSpacing;

    // Resize the layout views to be centered in their proper positions
    // based on the sizes calculated.
    ViewGroup.LayoutParams paramsLeftTop = mRlMainLeftTop.getLayoutParams();
    ViewGroup.LayoutParams paramsRightTop = mRlMainRightTop.getLayoutParams();
    int resultHeight = (screenHeight - floorHeight) - titleHeight;
    paramsLeftTop.height = resultHeight;
    paramsRightTop.height = resultHeight;
    mRlMainLeftTop.setLayoutParams(paramsLeftTop);
    mRlMainRightTop.setLayoutParams(paramsRightTop);

    // TODO: See if there are better methods of retrieving the floor height
    // value from the xml layout.

    // Set listeners to objects that can receive user input.
    mIbPagerRight.setOnClickListener(this);
    mIbPagerLeft.setOnClickListener(this);
    mIbMainHelp.setOnClickListener(this);
    mIbMainSettings.setOnClickListener(this);

    // Database check!

    // Create our database access object.
    mDbNodeHelper = new NodeDatabase(this);

    // Call the create method right just in case the user has never run the
    // app before. If a database does not exist, the prepopulated one will
    // be copied from the assets folder. Else, a connection is established.
    mDbNodeHelper.createDatabase();

    // Query the database for all purchased categories.

    // Set a conditional buffer. Internally, the orderby is set to _id ASC
    // (NodeDatabase.java).
    mDbNodeHelper.setConditions("isAvailable", "1");
    // Execute the query.
    mCategoryData = mDbNodeHelper.getCategoryListData();
    // Store the number of categories available.
    mCategoryLength = mCategoryData.length + 1;
    // Flush the buffer.
    mDbNodeHelper.flushQuery();

    // This activity no longer needs the connection, so close it.
    mDbNodeHelper.close();

    // Initialize the pager
    this.initializePaging();
}