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.example.android.mediabrowserservice.Playback.java
public void play(MediaSessionCompat.QueueItem item) { mPlayOnFocusGain = true;//from w w w. ja v a 2 s . co m tryToGetAudioFocus(); registerAudioNoisyReceiver(); String mediaId = item.getDescription().getMediaId(); boolean mediaHasChanged = !TextUtils.equals(mediaId, mCurrentMediaId); if (mediaHasChanged) { mCurrentPosition = 0; mCurrentMediaId = mediaId; } if (mState == PlaybackStateCompat.STATE_PAUSED && !mediaHasChanged && mMediaPlayer != null) { configMediaPlayerState(); } else { mState = PlaybackStateCompat.STATE_STOPPED; relaxResources(false); // release everything except MediaPlayer MediaMetadataCompat track = mMusicProvider .getMusic(MediaIDHelper.extractMusicIDFromMediaID(item.getDescription().getMediaId())); String source = track.getString(MusicProvider.CUSTOM_METADATA_TRACK_SOURCE); try { createMediaPlayerIfNeeded(); mState = PlaybackStateCompat.STATE_BUFFERING; mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.setDataSource(source); // Starts preparing the media player in the background. When // it's done, it will call our OnPreparedListener (that is, // the onPrepared() method on this class, since we set the // listener to 'this'). Until the media player is prepared, // we *cannot* call start() on it! mMediaPlayer.prepareAsync(); // If we are streaming from the internet, we want to hold a // Wifi lock, which prevents the Wifi radio from going to // sleep while the song is playing. mWifiLock.acquire(); if (mCallback != null) { mCallback.onPlaybackStatusChanged(mState); } } catch (IOException ex) { LogHelper.e(TAG, ex, "Exception playing song"); if (mCallback != null) { mCallback.onError(ex.getMessage()); } } } }
From source file:com.andreadec.musicplayer.MusicService.java
/** * Called when the service is created.//w w w . ja v a2 s. c om */ @Override public void onCreate() { PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MusicServiceWakelock"); // Initialize the telephony manager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); phoneStateListener = new MusicPhoneStateListener(); notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // Initialize pending intents quitPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("com.andreadec.musicplayer.quit"), 0); previousPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("com.andreadec.musicplayer.previous"), 0); playpausePendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("com.andreadec.musicplayer.playpause"), 0); nextPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("com.andreadec.musicplayer.next"), 0); pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP), PendingIntent.FLAG_UPDATE_CURRENT); // Read saved user preferences preferences = PreferenceManager.getDefaultSharedPreferences(this); // Initialize the media player mediaPlayer = new MediaPlayer(); mediaPlayer.setOnCompletionListener(this); mediaPlayer.setWakeMode(this, PowerManager.PARTIAL_WAKE_LOCK); // Enable the wake lock to keep CPU running when the screen is switched off shuffle = preferences.getBoolean(Constants.PREFERENCE_SHUFFLE, Constants.DEFAULT_SHUFFLE); repeat = preferences.getBoolean(Constants.PREFERENCE_REPEAT, Constants.DEFAULT_REPEAT); repeatAll = preferences.getBoolean(Constants.PREFERENCE_REPEATALL, Constants.DEFAULT_REPEATALL); try { // This may fail if the device doesn't support bass boost bassBoost = new BassBoost(1, mediaPlayer.getAudioSessionId()); bassBoost.setEnabled( preferences.getBoolean(Constants.PREFERENCE_BASSBOOST, Constants.DEFAULT_BASSBOOST)); setBassBoostStrength(preferences.getInt(Constants.PREFERENCE_BASSBOOSTSTRENGTH, Constants.DEFAULT_BASSBOOSTSTRENGTH)); bassBoostAvailable = true; } catch (Exception e) { bassBoostAvailable = false; } try { // This may fail if the device doesn't support equalizer equalizer = new Equalizer(1, mediaPlayer.getAudioSessionId()); equalizer.setEnabled( preferences.getBoolean(Constants.PREFERENCE_EQUALIZER, Constants.DEFAULT_EQUALIZER)); setEqualizerPreset( preferences.getInt(Constants.PREFERENCE_EQUALIZERPRESET, Constants.DEFAULT_EQUALIZERPRESET)); equalizerAvailable = true; } catch (Exception e) { equalizerAvailable = false; } random = new Random(System.nanoTime()); // Necessary for song shuffle shakeListener = new ShakeListener(this); if (preferences.getBoolean(Constants.PREFERENCE_SHAKEENABLED, Constants.DEFAULT_SHAKEENABLED)) { shakeListener.enable(); } telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); // Start listen for telephony events // Inizialize the audio manager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); mediaButtonReceiverComponent = new ComponentName(getPackageName(), MediaButtonReceiver.class.getName()); audioManager.registerMediaButtonEventReceiver(mediaButtonReceiverComponent); audioManager.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); // Initialize remote control client if (Build.VERSION.SDK_INT >= 14) { icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher); Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON); mediaButtonIntent.setComponent(mediaButtonReceiverComponent); PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, mediaButtonIntent, 0); remoteControlClient = new RemoteControlClient(mediaPendingIntent); remoteControlClient.setTransportControlFlags(RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS | RemoteControlClient.FLAG_KEY_MEDIA_NEXT); audioManager.registerRemoteControlClient(remoteControlClient); } updateNotificationMessage(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("com.andreadec.musicplayer.quit"); intentFilter.addAction("com.andreadec.musicplayer.previous"); intentFilter.addAction("com.andreadec.musicplayer.previousNoRestart"); intentFilter.addAction("com.andreadec.musicplayer.playpause"); intentFilter.addAction("com.andreadec.musicplayer.next"); intentFilter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY); broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals("com.andreadec.musicplayer.quit")) { sendBroadcast(new Intent("com.andreadec.musicplayer.quitactivity")); stopSelf(); return; } else if (action.equals("com.andreadec.musicplayer.previous")) { previousItem(false); } else if (action.equals("com.andreadec.musicplayer.previousNoRestart")) { previousItem(true); } else if (action.equals("com.andreadec.musicplayer.playpause")) { playPause(); } else if (action.equals("com.andreadec.musicplayer.next")) { nextItem(); } else if (action.equals(AudioManager.ACTION_AUDIO_BECOMING_NOISY)) { if (preferences.getBoolean(Constants.PREFERENCE_STOPPLAYINGWHENHEADSETDISCONNECTED, Constants.DEFAULT_STOPPLAYINGWHENHEADSETDISCONNECTED)) { pause(); } } } }; registerReceiver(broadcastReceiver, intentFilter); if (!isPlaying()) { loadLastSong(); } startForeground(Constants.NOTIFICATION_MAIN, notification); }
From source file:com.torrenttunes.android.LocalPlayback.java
@Override public void play(QueueItem item) { mPlayOnFocusGain = true;/*from www .j a v a 2 s .c o m*/ tryToGetAudioFocus(); registerAudioNoisyReceiver(); String mediaId = item.getDescription().getMediaId(); boolean mediaHasChanged = !TextUtils.equals(mediaId, mCurrentMediaId); if (mediaHasChanged) { mCurrentPosition = 0; mCurrentMediaId = mediaId; } if (mState == PlaybackState.STATE_PAUSED && !mediaHasChanged && mMediaPlayer != null) { configMediaPlayerState(); } else { mState = PlaybackState.STATE_STOPPED; relaxResources(false); // release everything except MediaPlayer MediaMetadataCompat track = mMusicProvider .getMusic(MediaIDHelper.extractMusicIDFromMediaID(item.getDescription().getMediaId())); String source = track.getString(MusicProvider.CUSTOM_METADATA_TRACK_SOURCE); try { createMediaPlayerIfNeeded(); mState = PlaybackState.STATE_BUFFERING; mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.setDataSource(source); // Starts preparing the media player in the background. When // it's done, it will call our OnPreparedListener (that is, // the onPrepared() method on this class, since we set the // listener to 'this'). Until the media player is prepared, // we *cannot* call start() on it! mMediaPlayer.prepareAsync(); // If we are streaming from the internet, we want to hold a // Wifi lock, which prevents the Wifi radio from going to // sleep while the song is playing. mWifiLock.acquire(); if (mCallback != null) { mCallback.onPlaybackStatusChanged(mState); } } catch (IOException ex) { LogHelper.e(TAG, ex, "Exception playing song"); if (mCallback != null) { mCallback.onError(ex.getMessage()); } } } }
From source file:com.appdevper.mediaplayer.app.LocalPlayback.java
@Override public void play(QueueItem item) { mPlayOnFocusGain = true;/*from ww w . j av a 2s . c o m*/ tryToGetAudioFocus(); registerAudioNoisyReceiver(); String mediaId = item.getDescription().getMediaId(); boolean mediaHasChanged = !TextUtils.equals(mediaId, mCurrentMediaId); if (mediaHasChanged) { mCurrentPosition = 0; mCurrentMediaId = mediaId; } if (mState == PlaybackState.STATE_PAUSED && !mediaHasChanged && mMediaPlayer != null) { configMediaPlayerState(); } else { mState = PlaybackState.STATE_STOPPED; relaxResources(false); // release everything except MediaPlayer MediaMetadataCompat track = mMusicProvider.getMusic(item.getDescription().getMediaId()); String source = track.getString(MusicProviderSource.CUSTOM_METADATA_TRACK_SOURCE); try { createMediaPlayerIfNeeded(); mState = PlaybackState.STATE_BUFFERING; mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.setDataSource(source); mMediaPlayer.prepareAsync(); mWifiLock.acquire(); if (mCallback != null) { mCallback.onPlaybackStatusChanged(mState); } } catch (IOException ex) { LogHelper.e(TAG, ex, "Exception playing song"); if (mCallback != null) { mCallback.onError(ex.getMessage()); } } } }
From source file:com.webileapps.fragments.CordovaFragment.java
protected void init() { appView = makeWebView();/*from w w w .j a v a 2 s .c om*/ createViews(); if (!appView.isInitialized()) { appView.init(cordovaInterface, pluginEntries, preferences); } cordovaInterface.onCordovaInit(appView.getPluginManager()); // Wire the hardware volume controls to control media if desired. String volumePref = preferences.getString("DefaultVolumeStream", ""); if ("media".equals(volumePref.toLowerCase(Locale.ENGLISH))) { getActivity().setVolumeControlStream(AudioManager.STREAM_MUSIC); } if (BuildConfig.DEBUG) { ((WebView) appView.getView()) .setWebViewClient(new SystemWebViewClient((SystemWebViewEngine) appView.getEngine()) { @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { handler.proceed(); } }); } }
From source file:com.example.android.uamp.LocalPlayback.java
@Override public void play(MediaSessionCompat.QueueItem item) { mPlayOnFocusGain = true;/*from ww w . ja v a 2 s .c o m*/ tryToGetAudioFocus(); registerAudioNoisyReceiver(); String mediaId = item.getDescription().getMediaId(); boolean mediaHasChanged = !TextUtils.equals(mediaId, mCurrentMediaId); if (mediaHasChanged) { mCurrentPosition = 0; mCurrentMediaId = mediaId; } if (mState == PlaybackStateCompat.STATE_PAUSED && !mediaHasChanged && mMediaPlayer != null) { configMediaPlayerState(); } else { mState = PlaybackStateCompat.STATE_STOPPED; relaxResources(false); // release everything except MediaPlayer MediaMetadataCompat track = mMusicProvider .getMusic(MediaIDHelper.extractMusicIDFromMediaID(item.getDescription().getMediaId())); String source = track.getString(MusicProvider.CUSTOM_METADATA_TRACK_SOURCE); try { createMediaPlayerIfNeeded(); mState = PlaybackStateCompat.STATE_BUFFERING; mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.setDataSource(source); // Starts preparing the media player in the background. When // it's done, it will call our OnPreparedListener (that is, // the onPrepared() method on this class, since we set the // listener to 'this'). Until the media player is prepared, // we *cannot* call start() on it! mMediaPlayer.prepareAsync(); // If we are streaming from the internet, we want to hold a // Wifi lock, which prevents the Wifi radio from going to // sleep while the song is playing. mWifiLock.acquire(); if (mCallback != null) { mCallback.onPlaybackStatusChanged(mState); } } catch (IOException ex) { LogHelper.e(TAG, ex, "Exception playing song"); if (mCallback != null) { mCallback.onError(ex.getMessage()); } } } }
From source file:info.tongrenlu.music.LocalPlayback.java
@Override public void play(Uri dataUri) { mPlayOnFocusGain = true;//ww w . j av a 2s .co m tryToGetAudioFocus(); registerAudioNoisyReceiver(); boolean mediaHasChanged = false; if (mCurrentMediaUri == null || !mCurrentMediaUri.equals(dataUri)) { mCurrentPosition = 0; mCurrentMediaUri = dataUri; mediaHasChanged = true; } if (mState == PlaybackStateCompat.STATE_PAUSED && !mediaHasChanged && mMediaPlayer != null) { configMediaPlayerState(); } else { mState = PlaybackStateCompat.STATE_STOPPED; relaxResources(false); // release everything except MediaPlayer try { createMediaPlayerIfNeeded(); mDuration = 0; mCurrentStreamPosition = 0; mState = PlaybackStateCompat.STATE_BUFFERING; mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.setDataSource(mService, dataUri); // Starts preparing the media player in the background. When // it's done, it will call our OnPreparedListener (that is, // the onPrepared() method on this class, since we set the // listener to 'this'). Until the media player is prepared, // we *cannot* call start() on it! mMediaPlayer.prepareAsync(); // If we are streaming from the internet, we want to hold a // Wifi lock, which prevents the Wifi radio from going to // sleep while the song is playing. mWifiLock.acquire(); if (mCallback != null) { mCallback.onPlaybackStatusChanged(mState); } } catch (IOException ex) { Log.e(TAG, "Exception playing song", ex); if (mCallback != null) { mCallback.onError(ex.getMessage()); } } } }
From source file:net.gcompris.GComprisActivity.java
public static boolean requestAudioFocus() { Context mContext = m_instance.getApplicationContext(); AudioManager am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE); // Request audio focus for playback int result = am.requestAudioFocus(null, // Use the music stream. AudioManager.STREAM_MUSIC, // Request permanent focus. AudioManager.AUDIOFOCUS_GAIN); if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { return true; }/* w w w.j a v a 2 s . c o m*/ return false; }
From source file:com.example.android.gft.PhrasesFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.word_list, container, false); // Create and setup the {@link AudioManager} to request audio focus mAudioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE); // Create a list of words final ArrayList<Word> words = new ArrayList<Word>(); words.add(new Word(R.string.phrase_where_are_you_going, R.string.miwok_phrase_where_are_you_going, R.raw.phrase_where_are_you_going)); words.add(new Word(R.string.phrase_what_is_your_name, R.string.miwok_phrase_what_is_your_name, R.raw.phrase_what_is_your_name)); words.add(new Word(R.string.phrase_my_name_is, R.string.miwok_phrase_my_name_is, R.raw.phrase_my_name_is)); words.add(new Word(R.string.phrase_how_are_you_feeling, R.string.miwok_phrase_how_are_you_feeling, R.raw.phrase_how_are_you_feeling)); words.add(new Word(R.string.phrase_im_feeling_good, R.string.miwok_phrase_im_feeling_good, R.raw.phrase_im_feeling_good)); words.add(new Word(R.string.phrase_are_you_coming, R.string.miwok_phrase_are_you_coming, R.raw.phrase_are_you_coming)); words.add(new Word(R.string.phrase_yes_im_coming, R.string.miwok_phrase_yes_im_coming, R.raw.phrase_yes_im_coming)); words.add(new Word(R.string.phrase_im_coming, R.string.miwok_phrase_im_coming, R.raw.phrase_im_coming)); words.add(new Word(R.string.phrase_lets_go, R.string.miwok_phrase_lets_go, R.raw.phrase_lets_go)); words.add(new Word(R.string.phrase_come_here, R.string.miwok_phrase_come_here, R.raw.phrase_come_here)); // Create an {@link WordAdapter}, whose data source is a list of {@link Word}s. The // adapter knows how to create list items for each item in the list. WordAdapter adapter = new WordAdapter(getActivity(), words, R.color.category_phrases); // Find the {@link ListView} object in the view hierarchy of the {@link Activity}. // There should be a {@link ListView} with the view ID called list, which is declared in the // word_list.xml layout file. ListView listView = (ListView) rootView.findViewById(R.id.list); // Make the {@link ListView} use the {@link WordAdapter} we created above, so that the // {@link ListView} will display list items for each {@link Word} in the list. listView.setAdapter(adapter);/*from www. j a v a2s .co m*/ // Set a click listener to play the audio when the list item is clicked on listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { // Release the media player if it currently exists because we are about to // play a different sound file releaseMediaPlayer(); // Get the {@link Word} object at the given position the user clicked on Word word = words.get(position); // Request audio focus so in order to play the audio file. The app needs to play a // short audio file, so we will request audio focus with a short amount of time // with AUDIOFOCUS_GAIN_TRANSIENT. int result = mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT); if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { // We have audio focus now. // Create and setup the {@link MediaPlayer} for the audio resource associated // with the current word mMediaPlayer = MediaPlayer.create(getActivity(), word.getAudioResourceId()); // Start the audio file mMediaPlayer.start(); // Setup a listener on the media player, so that we can stop and release the // media player once the sound has finished playing. mMediaPlayer.setOnCompletionListener(mCompletionListener); } } }); return rootView; }
From source file:com.example.haizhu.myvoiceassistant.ui.RobotChatActivity.java
private void iniData() { globalPref = GlobalPref.getInstance(); TruingDataHandler.setListener(this); chatAdapter = new RobotChatAdapter(getApplicationContext(), resultList); initListener();//from ww w . j a va 2 s.c om speechRecognizer = SpeechRecognizer.createSpeechRecognizer(getApplicationContext(), new ComponentName(this, VoiceRecognitionService.class)); speechRecognizer.setRecognitionListener(recognitionListener); speechSynthesizer = new SpeechSynthesizer(AssistantApplication.getInstance().getApplicationContext(), "holder", speechSynthesizerListener); // ?setApiKey???apiKeysecretKey speechSynthesizer.setApiKey("DnBhRg9PvmNSs0a6OD4BHLAk", "8492ef7b1b435bce2b98e41c1023e67b"); speechSynthesizer.setAudioStreamType(AudioManager.STREAM_MUSIC); listener = new DrawerLayout.DrawerListener() { @Override public void onDrawerSlide(View drawerView, float slideOffset) { } @Override public void onDrawerOpened(View drawerView) { } @Override public void onDrawerClosed(View drawerView) { } @Override public void onDrawerStateChanged(int newState) { } }; }