List of usage examples for android.media AudioManager STREAM_MUSIC
int STREAM_MUSIC
To view the source code for android.media AudioManager STREAM_MUSIC.
Click Source Link
From source file:com.bangz.shotrecorder.RecordActivity.java
private void doStartRecord() { doDelayStart();/*from www. j ava2 s . c om*/ ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_MUSIC, 100); tg.startTone(ToneGenerator.TONE_CDMA_ABBR_ALERT, BEEP_DURATIONMS); SystemClock.sleep(BEEP_DURATIONMS - 20); tg.stopTone(); tg.release(); mState = STATE_RECORDING; Intent intent = new Intent(this, RecordService.class); intent.putExtra(RecordService.EXTRA_SAMPLERATE, mSampleRate); intent.putExtra(RecordService.EXTRA_CHANNLES, mChannels); intent.putExtra(RecordService.EXTRA_ENCODDING, mEncoding); intent.putExtra(RecordService.EXTRA_MODE, mMode.ordinal()); intent.putExtra(RecordService.EXTRA_MAXSHOT, this.mMaxShots); intent.putExtra(RecordService.EXTRA_MAXPARTIME, (int) (mMaxParTime * 1000)); intent.putExtra(RecordService.EXTRA_CAPTURESIZE, 128); intent.putExtra(RecordService.EXTRA_MAXRECORDTIME, 5 * 60); startService(intent); doBindService(); textTIME.setText(R.string.READY); }
From source file:org.connectbot.ConsoleActivity.java
@Override public void onCreate(Bundle icicle) { super.onCreate(icicle); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { StrictModeSetup.run();/*from w w w. jav a 2 s . c om*/ } hardKeyboard = getResources().getConfiguration().keyboard == Configuration.KEYBOARD_QWERTY; clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); prefs = PreferenceManager.getDefaultSharedPreferences(this); titleBarHide = prefs.getBoolean(PreferenceConstants.TITLEBARHIDE, false); if (titleBarHide && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // This is a separate method because Gradle does not uniformly respect the conditional // Build check. See: https://code.google.com/p/android/issues/detail?id=137195 requestActionBar(); } this.setContentView(R.layout.act_console); // hide status bar if requested by user if (prefs.getBoolean(PreferenceConstants.FULLSCREEN, false)) { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } // TODO find proper way to disable volume key beep if it exists. setVolumeControlStream(AudioManager.STREAM_MUSIC); // handle requested console from incoming intent if (icicle == null) { requested = getIntent().getData(); } else { String uri = icicle.getString(STATE_SELECTED_URI); if (uri != null) { requested = Uri.parse(uri); } } inflater = LayoutInflater.from(this); toolbar = (Toolbar) findViewById(R.id.toolbar); pager = (TerminalViewPager) findViewById(R.id.console_flip); pager.addOnPageChangeListener(new TerminalViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { setTitle(adapter.getPageTitle(position)); onTerminalChanged(); } }); adapter = new TerminalPagerAdapter(); pager.setAdapter(adapter); empty = (TextView) findViewById(android.R.id.empty); stringPromptGroup = (RelativeLayout) findViewById(R.id.console_password_group); stringPromptInstructions = (TextView) findViewById(R.id.console_password_instructions); stringPrompt = (EditText) findViewById(R.id.console_password); stringPrompt.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_UP) return false; if (keyCode != KeyEvent.KEYCODE_ENTER) return false; // pass collected password down to current terminal String value = stringPrompt.getText().toString(); PromptHelper helper = getCurrentPromptHelper(); if (helper == null) return false; helper.setResponse(value); // finally clear password for next user stringPrompt.setText(""); updatePromptVisible(); return true; } }); booleanPromptGroup = (RelativeLayout) findViewById(R.id.console_boolean_group); booleanPrompt = (TextView) findViewById(R.id.console_prompt); booleanYes = (Button) findViewById(R.id.console_prompt_yes); booleanYes.setOnClickListener(new OnClickListener() { public void onClick(View v) { PromptHelper helper = getCurrentPromptHelper(); if (helper == null) return; helper.setResponse(Boolean.TRUE); updatePromptVisible(); } }); Button booleanNo = (Button) findViewById(R.id.console_prompt_no); booleanNo.setOnClickListener(new OnClickListener() { public void onClick(View v) { PromptHelper helper = getCurrentPromptHelper(); if (helper == null) return; helper.setResponse(Boolean.FALSE); updatePromptVisible(); } }); fade_out_delayed = AnimationUtils.loadAnimation(this, R.anim.fade_out_delayed); // Preload animation for keyboard button keyboard_fade_in = AnimationUtils.loadAnimation(this, R.anim.keyboard_fade_in); keyboard_fade_out = AnimationUtils.loadAnimation(this, R.anim.keyboard_fade_out); keyboardGroup = (LinearLayout) findViewById(R.id.keyboard_group); keyboardAlwaysVisible = prefs.getBoolean(PreferenceConstants.KEY_ALWAYS_VISIVLE, false); if (keyboardAlwaysVisible) { // equivalent to android:layout_above=keyboard_group RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); layoutParams.addRule(RelativeLayout.ABOVE, R.id.keyboard_group); pager.setLayoutParams(layoutParams); // Show virtual keyboard keyboardGroup.setVisibility(View.VISIBLE); } mKeyboardButton = (ImageView) findViewById(R.id.button_keyboard); mKeyboardButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { View terminal = adapter.getCurrentTerminalView(); if (terminal == null) return; InputMethodManager inputMethodManager = (InputMethodManager) getSystemService( Context.INPUT_METHOD_SERVICE); inputMethodManager.toggleSoftInputFromWindow(terminal.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0); terminal.requestFocus(); hideEmulatedKeys(); } }); findViewById(R.id.button_ctrl).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_esc).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_tab).setOnClickListener(emulatedKeysListener); addKeyRepeater(findViewById(R.id.button_up)); addKeyRepeater(findViewById(R.id.button_up)); addKeyRepeater(findViewById(R.id.button_down)); addKeyRepeater(findViewById(R.id.button_left)); addKeyRepeater(findViewById(R.id.button_right)); findViewById(R.id.button_home).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_end).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_pgup).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_pgdn).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_f1).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_f2).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_f3).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_f4).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_f5).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_f6).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_f7).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_f8).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_f9).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_f10).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_f11).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_f12).setOnClickListener(emulatedKeysListener); actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); if (titleBarHide) { actionBar.hide(); } actionBar.addOnMenuVisibilityListener(new ActionBar.OnMenuVisibilityListener() { public void onMenuVisibilityChanged(boolean isVisible) { inActionBarMenu = isVisible; if (!isVisible) { hideEmulatedKeys(); } } }); } final HorizontalScrollView keyboardScroll = (HorizontalScrollView) findViewById(R.id.keyboard_hscroll); if (!hardKeyboard) { // Show virtual keyboard and scroll back and forth showEmulatedKeys(false); keyboardScroll.postDelayed(new Runnable() { @Override public void run() { final int xscroll = findViewById(R.id.button_f12).getRight(); if (BuildConfig.DEBUG) { Log.d(TAG, "smoothScrollBy(toEnd[" + xscroll + "])"); } keyboardScroll.smoothScrollBy(xscroll, 0); keyboardScroll.postDelayed(new Runnable() { @Override public void run() { if (BuildConfig.DEBUG) { Log.d(TAG, "smoothScrollBy(toStart[" + (-xscroll) + "])"); } keyboardScroll.smoothScrollBy(-xscroll, 0); } }, 500); } }, 500); } // Reset keyboard auto-hide timer when scrolling keyboardScroll.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_MOVE: autoHideEmulatedKeys(); break; case MotionEvent.ACTION_UP: v.performClick(); return (true); } return (false); } }); tabs = (TabLayout) findViewById(R.id.tabs); if (tabs != null) setupTabLayoutWithViewPager(); pager.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showEmulatedKeys(true); } }); // Change keyboard button image according to soft keyboard visibility // How to detect keyboard visibility: http://stackoverflow.com/q/4745988 contentView = findViewById(android.R.id.content); contentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { Rect r = new Rect(); contentView.getWindowVisibleDisplayFrame(r); int screenHeight = contentView.getRootView().getHeight(); int keypadHeight = screenHeight - r.bottom; if (keypadHeight > screenHeight * 0.15) { // keyboard is opened mKeyboardButton.setImageResource(R.drawable.ic_keyboard_hide); mKeyboardButton.setContentDescription( getResources().getText(R.string.image_description_hide_keyboard)); } else { // keyboard is closed mKeyboardButton.setImageResource(R.drawable.ic_keyboard); mKeyboardButton.setContentDescription( getResources().getText(R.string.image_description_show_keyboard)); } } }); }
From source file:com.scooter1556.sms.lib.android.service.AudioPlayerService.java
private void preparePlayer() { // Request audio focus for playback int result = audioManager.requestAudioFocus(audioFocusListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { // Start playback String streamUrl = restService.getConnection().getUrl() + "/stream/" + player.getTranscodeProfile().getID() + "?offset=" + (int) (player.getOffset() * 0.001); Uri contentUri = Uri.parse(streamUrl); player.addListener(this); player.initialise(this, contentUri, true); wakeLock.acquire();//from w w w . j av a2 s . c om wifiLock.acquire(); if (!mediaSession.isActive()) { mediaSession.setActive(true); } // Register receiver for audio manager events registerAudioManagerReceiver(); } }
From source file:com.rks.musicx.services.MusicXService.java
private boolean successfullyRetrievedAudioFocus() { int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); return result == AudioManager.AUDIOFOCUS_GAIN; }
From source file:com.owncloud.android.media.MediaService.java
/** * Starts playing the current media file. *///from w ww. j a v a 2 s .c om protected void playMedia() { mState = State.STOPPED; releaseResources(false); // release everything except MediaPlayer try { if (mFile == null) { Toast.makeText(this, R.string.media_err_nothing_to_play, Toast.LENGTH_LONG).show(); processStopRequest(true); return; } else if (mAccount == null) { Toast.makeText(this, R.string.media_err_not_in_owncloud, Toast.LENGTH_LONG).show(); processStopRequest(true); return; } createMediaPlayerIfNeeded(); mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); String url = mFile.getStoragePath(); updateFileObserver(url); /* Streaming is not possible right now if (url == null || url.length() <= 0) { url = AccountUtils.constructFullURLForAccount(this, mAccount) + mFile.getRemotePath(); } mIsStreaming = url.startsWith("http:") || url.startsWith("https:"); */ mIsStreaming = false; mPlayer.setDataSource(url); mState = State.PREPARING; setUpAsForeground(String.format(getString(R.string.media_state_loading), mFile.getFileName())); // starts preparing the media player in background mPlayer.prepareAsync(); // prevent the Wifi from going to sleep when streaming if (mIsStreaming) { mWifiLock.acquire(); } else if (mWifiLock.isHeld()) { mWifiLock.release(); } } catch (SecurityException e) { Log_OC.e(TAG, "SecurityException playing " + mAccount.name + mFile.getRemotePath(), e); Toast.makeText(this, String.format(getString(R.string.media_err_security_ex), mFile.getFileName()), Toast.LENGTH_LONG).show(); processStopRequest(true); } catch (IOException e) { Log_OC.e(TAG, "IOException playing " + mAccount.name + mFile.getRemotePath(), e); Toast.makeText(this, String.format(getString(R.string.media_err_io_ex), mFile.getFileName()), Toast.LENGTH_LONG).show(); processStopRequest(true); } catch (IllegalStateException e) { Log_OC.e(TAG, "IllegalStateException " + mAccount.name + mFile.getRemotePath(), e); Toast.makeText(this, String.format(getString(R.string.media_err_unexpected), mFile.getFileName()), Toast.LENGTH_LONG).show(); processStopRequest(true); } catch (IllegalArgumentException e) { Log_OC.e(TAG, "IllegalArgumentException " + mAccount.name + mFile.getRemotePath(), e); Toast.makeText(this, String.format(getString(R.string.media_err_unexpected), mFile.getFileName()), Toast.LENGTH_LONG).show(); processStopRequest(true); } }
From source file:audio.lisn.adapter.StoreBookViewAdapter.java
private void playPreview() { isLoadingPreview = true;/* w w w.j a va 2 s . co m*/ isPlayingPreview = false; pausePlayer(); notifyDataSetChanged(); if (connectionDetector.isConnectingToInternet()) { if (mediaPlayer == null) { mediaPlayer = new MediaPlayer(); } if (mediaPlayer.isPlaying()) { mediaPlayer.stop(); if (timerUpdateThread != null) { timerUpdateThread.interrupt(); } } mediaPlayer.reset(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); try { mediaPlayer.setDataSource(selectedAudioBook.getPreview_audio()); } catch (IOException e) { Log.v("playPreview", "IOException" + e.getMessage()); e.printStackTrace(); } mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { public void onPrepared(MediaPlayer mp) { isPlayingPreview = true; isLoadingPreview = false; startTimer(); mp.start(); notifyDataSetChanged(); } }); mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() { public boolean onError(MediaPlayer mp, int what, int extra) { notifyDataSetChanged(); String msg = ""; if (extra == MediaPlayer.MEDIA_ERROR_IO) { msg = "MEDIA_ERROR_IO"; } else if (extra == MediaPlayer.MEDIA_ERROR_MALFORMED) { msg = "MEDIA_ERROR_MALFORMED"; } else if (extra == MediaPlayer.MEDIA_ERROR_UNSUPPORTED) { msg = "MEDIA_ERROR_UNSUPPORTED"; } else if (extra == MediaPlayer.MEDIA_ERROR_TIMED_OUT) { msg = "MEDIA_ERROR_TIMED_OUT"; } else { msg = "video_error_unknown_error"; } showErrorMessage(msg); return false; } }); mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { isPlayingPreview = false; isLoadingPreview = false; stopTimer(); notifyDataSetChanged(); } }); try { mediaPlayer.prepareAsync(); // prepare async to not block main } catch (Exception e) { showErrorMessage(e.getMessage()); isPlayingPreview = false; isLoadingPreview = false; stopTimer(); notifyDataSetChanged(); } } else { AlertDialog.Builder builder = new AlertDialog.Builder(selectedView.getContext()); builder.setTitle(R.string.NO_INTERNET_TITLE).setMessage(R.string.NO_INTERNET_MESSAGE) .setPositiveButton(R.string.BUTTON_OK, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // FIRE ZE MISSILES! } }); AlertDialog dialog = builder.create(); dialog.show(); } }
From source file:com.smedic.tubtub.BackgroundAudioService.java
private void onVideoStart(SparseArray<YtFile> ytFiles) { YtFile ytFile;//from w w w . j a va 2 s .c o m if (ytFiles == null || (ytFile = findBestStream(ytFiles)) == null) { // Something went wrong we got no urls. Always check this. Toast.makeText(YTApplication.getAppContext(), R.string.failed_playback, Toast.LENGTH_SHORT).show(); playNext(); buildNotification(generateAction(android.R.drawable.ic_media_pause, "Pause", ACTION_PAUSE)); return; } final String id = videoItem.getId(); final String title = videoItem.getTitle(); final int bitrate = ytFile.getFormat().getAudioBitrate(); final String message = "Starting: " + title + "(" + id + ")" + ", quality: " + bitrate + "kbps."; Log.d(TAG, message); try { if (mMediaPlayer != null) { mMediaPlayer.reset(); isPrepared = false; // Make sure the media player will acquire a wake-lock while playing. If we don't do // that, the CPU might go to sleep while the song is playing, causing playback to stop. // // Remember that to use this, we have to declare the android.permission.WAKE_LOCK // permission in AndroidManifest.xml. mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK); mMediaPlayer.setDataSource(ytFile.getUrl()); mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.prepareAsync(); if (!mWifiLock.isHeld()) mWifiLock.acquire(); Toast.makeText(YTApplication.getAppContext(), message, Toast.LENGTH_SHORT).show(); } } catch (IOException io) { io.printStackTrace(); } }
From source file:com.smc.tw.waltz.MainActivity.java
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (DEBUG)//from www . ja va 2s . co m Log.d(TAG, "onKeyDown code:" + keyCode); switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_UP: { mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI); return true; } case KeyEvent.KEYCODE_VOLUME_DOWN: { mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI); return true; } default: break; } return super.onKeyDown(keyCode, event); }
From source file:com.nbplus.vbroadlauncher.RadioActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Constants.OPEN_BETA_PHONE && LauncherSettings.getInstance(this).isSmartPhone()) { this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); }// ww w . j a va2s .co m mSettingsContentObserver = new SettingsContentObserver(this, new Handler()); getApplicationContext().getContentResolver().registerContentObserver( android.provider.Settings.System.CONTENT_URI, true, mSettingsContentObserver); showProgressDialog(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.setStatusBarColor(getResources().getColor(R.color.activity_radio_background)); } overridePendingTransition(R.anim.fade_in, R.anim.fade_out); setContentView(R.layout.activity_radio); Intent i = getIntent(); mShortcutData = i.getParcelableExtra(Constants.EXTRA_NAME_SHORTCUT_DATA); if (mShortcutData == null) { Log.e(TAG, "mShortcutData is not found.."); finishActivity(); return; } IntentFilter filter = new IntentFilter(); filter.addAction(MusicService.ACTION_PLAYED); filter.addAction(MusicService.ACTION_PAUSED); filter.addAction(MusicService.ACTION_STOPPED); filter.addAction(MusicService.ACTION_COMPLETED); filter.addAction(MusicService.ACTION_ERROR); filter.addAction(MusicService.ACTION_PLAYING_STATUS); LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, filter); // send playing status Intent queryStatus = new Intent(this, MusicService.class); queryStatus.setAction(MusicService.ACTION_PLAYING_STATUS); startService(queryStatus); // ViewPager . // ??? ? ? ? . mViewPager = (NbplusViewPager) findViewById(R.id.viewPager); mIndicator = (CirclePageIndicator) findViewById(R.id.indicator); // close button ImageButton closeButton = (ImageButton) findViewById(R.id.btn_close); closeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finishActivity(); } }); mActivityLayout = (RelativeLayout) findViewById(R.id.radio_activity_background); int wallpaperId = LauncherSettings.getInstance(this).getWallpaperId(); mActivityLayout.setBackgroundResource(LauncherSettings.landWallpaperResource[wallpaperId]); // title. mRadioTitle = (TextView) findViewById(R.id.radio_activity_label); // media controller mPlayToggle = (ImageButton) findViewById(R.id.ic_media_control_play); mPlayToggle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mCurrentPlayingStatus == null) { return; } MusicService.State state = (MusicService.State) mCurrentPlayingStatus .getSerializable(MusicService.EXTRA_PLAYING_STATUS); Intent i = new Intent(RadioActivity.this, MusicService.class); if (state == MusicService.State.Playing) { i.setAction(MusicService.ACTION_PAUSE); } else if (state == MusicService.State.Paused) { i.setAction(MusicService.ACTION_PLAY); } startService(i); } }); mPlayStop = (ImageButton) findViewById(R.id.ic_media_control_stop); mPlayStop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mCurrentPlayingStatus == null) { return; } MusicService.State state = (MusicService.State) mCurrentPlayingStatus .getSerializable(MusicService.EXTRA_PLAYING_STATUS); if (state == MusicService.State.Playing || state == MusicService.State.Paused) { Intent i = new Intent(RadioActivity.this, MusicService.class); i.setAction(MusicService.ACTION_STOP); i.putExtra(MusicService.EXTRA_MUSIC_FORCE_STOP, false); startService(i); } } }); mSoundToggle = (ImageButton) findViewById(R.id.ic_media_control_volume_btn); AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE); int currentVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC); int maxVolume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC); if (currentVolume <= 0) { mSoundToggle.setBackgroundResource(R.drawable.ic_button_radio_sound_off); } else { mSoundToggle.setBackgroundResource(R.drawable.ic_button_radio_sound_on); } mSoundToggle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE); if (audio.getStreamVolume(AudioManager.STREAM_MUSIC) <= 0) { if (mSoundTogglePreviousValue > 0) { audio.setStreamVolume(AudioManager.STREAM_MUSIC, mSoundTogglePreviousValue, AudioManager.FLAG_PLAY_SOUND); } else { mSoundTogglePreviousValue = 1; audio.setStreamVolume(AudioManager.STREAM_MUSIC, mSoundTogglePreviousValue, AudioManager.FLAG_PLAY_SOUND); } mSoundToggle.setBackgroundResource(R.drawable.ic_button_radio_sound_on); mSeekbar.setProgress(mSoundTogglePreviousValue); mSoundTogglePreviousValue = -1; } else { mSoundTogglePreviousValue = audio.getStreamVolume(AudioManager.STREAM_MUSIC); audio.setStreamVolume(AudioManager.STREAM_MUSIC, 0, AudioManager.FLAG_PLAY_SOUND); mSoundToggle.setBackgroundResource(R.drawable.ic_button_radio_sound_off); } } }); mSeekbar = (SeekBar) findViewById(R.id.ic_media_control_volume_seek); mSeekbar.setMax(maxVolume); mSeekbar.setProgress(currentVolume); mSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { mSoundTogglePreviousValue = -1; AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE); audio.setStreamVolume(AudioManager.STREAM_MUSIC, progress, AudioManager.FLAG_PLAY_SOUND); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); getRadioChannelTask = new GetRadioChannelTask(); if (getRadioChannelTask != null) { getRadioChannelTask.setBroadcastApiData(this, mHandler, mShortcutData.getDomain() + mShortcutData.getPath()); mIsExecuteGetRadioChannelTask = true; getRadioChannelTask.execute(); } }
From source file:com.google.android.exoplayer2.demo.MediaPlayerFragment.java
private void initVol() { /* Services and miscellaneous */ mAudioManager = (AudioManager) getContext().getApplicationContext().getSystemService(AUDIO_SERVICE); mAudioMax = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC); }