Example usage for android.media AudioManager STREAM_MUSIC

List of usage examples for android.media AudioManager STREAM_MUSIC

Introduction

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

Prototype

int STREAM_MUSIC

To view the source code for android.media AudioManager STREAM_MUSIC.

Click Source Link

Document

Used to identify the volume of audio streams for music playback

Usage

From source file:com.rks.musicx.services.MusicXService.java

public float getDeviceVolume() {
    int volumeLevel = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    return (float) volumeLevel / maxVolume;
}

From source file:com.hotstar.player.adplayer.player.PlayerFragment.java

private void requestAudioFocus() {
    AudioManager am = (AudioManager) getActivity().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_TRANSIENT_MAY_DUCK);

    if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        AdVideoApplication.logger.i(LOG_TAG + "#requestAudioFocus()", "Gained audio focus.");
    }//  w  ww.jav a  2  s  .com
}

From source file:org.botlibre.sdk.activity.MicConfiguration.java

private void muteMicBeep(boolean mute) {
    AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    if (mute) {// w  ww.ja  va 2  s  . c  o m
        //if its true then the Volume will be zero.
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
    } else {
        //if its false, the Volume will put back no
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, MainActivity.volume, 0);
    }
}

From source file:co.shunya.gita.player.MusicService.java

/**
 * Starts playing the next song. If manualUrl is null, the next song will be randomly selected
 * from our Media Retriever (that is, it will be a random song in the user's device). If
 * manualUrl is non-null, then it specifies the URL or path to the song that will be played
 * next.//from  w ww  .  ja  v a  2  s  .  com
 */
void playNextSong(Long id) {
    if (id == null || id < 0) {
        throw new IllegalArgumentException("id must be non nul +ve");
    }
    setState(State.Stopped);
    relaxResources(false); // release everything except MediaPlayer

    try {
        // set the source of the media player to a manual URL or path
        Track playingItem = mRetriever.getItem(id);
        createMediaPlayerIfNeeded();
        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

        if (playingItem == null) {
            Toast.makeText(this, "All Tracks of current category is been played", Toast.LENGTH_LONG).show();
            processStopRequest(true); // stop everything!
            return;
        }
        //            BusProvider.getInstance().post(playingItem);
        mCurrentID = id;
        mPlayer.setDataSource(playingItem.isDownloded() ? playingItem.getLocalUrl(this) : playingItem.getUrl());
        mIsStreaming = playingItem.getUrl().startsWith("http:") || playingItem.getUrl().startsWith("https:");
        mSongTitle = playingItem.getTitle();

        setState(State.Preparing);
        updateUI();

        setUpAsForeground(mSongTitle + " (loading)");

        // Use the media button APIs (if available) to register ourselves for media button
        // events

        MediaButtonHelper.registerMediaButtonEventReceiverCompat(mAudioManager, mMediaButtonReceiverComponent);

        // Use the remote control APIs (if available) to set the playback state

        if (mRemoteControlClientCompat == null) {
            Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
            intent.setComponent(mMediaButtonReceiverComponent);
            mRemoteControlClientCompat = new RemoteControlClientCompat(PendingIntent.getBroadcast(
                    this /*context*/, 0 /*requestCode, ignored*/, intent /*intent*/, 0 /*flags*/));
            RemoteControlHelper.registerRemoteControlClient(mAudioManager, mRemoteControlClientCompat);
        }

        mRemoteControlClientCompat.setPlaybackState(RemoteControlClient.PLAYSTATE_PLAYING);

        mRemoteControlClientCompat.setTransportControlFlags(RemoteControlClient.FLAG_KEY_MEDIA_PLAY
                | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_NEXT
                | RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS | RemoteControlClient.FLAG_KEY_MEDIA_STOP);

        // Update the remote controls
        mRemoteControlClientCompat.editMetadata(true)
                .putString(MediaMetadataRetriever.METADATA_KEY_ALBUM, "Gita")
                .putString(MediaMetadataRetriever.METADATA_KEY_TITLE, playingItem.getTitle())
                .putBitmap(RemoteControlClientCompat.MetadataEditorCompat.METADATA_KEY_ARTWORK, mDummyAlbumArt)
                .apply();

        // 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!
        mPlayer.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. If, on the other hand,
        // we are *not* streaming, we want to release the lock if we were holding it before.
        if (mIsStreaming)
            mWifiLock.acquire();
        else if (mWifiLock.isHeld())
            mWifiLock.release();
    } catch (IOException ex) {
        Log.e("MusicService", "IOException playing next song: " + ex.getMessage());
        ex.printStackTrace();
    }
}

From source file:com.jungle.base.utils.MiscUtils.java

public static void playSound(Context context, int soundResId) {
    final MediaPlayer player = MediaPlayer.create(context, soundResId);
    if (player == null) {
        return;/*from   w  ww .  ja v a 2  s  . c  om*/
    }

    AudioManager manager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    int maxVolume = manager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    int currVolume = manager.getStreamVolume(AudioManager.STREAM_MUSIC);

    float volume = 1.0f;
    if (maxVolume > 0) {
        volume = (float) currVolume / (float) maxVolume;
    }

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

    player.setVolume(volume, volume);
    player.start();
}

From source file:edu.missouri.bas.service.SensorService.java

public void playSound(int sound, float fSpeed) {
    AudioManager mgr = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
    float volume = streamVolumeCurrent;
    mSoundPool.play(soundsMap.get(sound), volume, volume, 1, 0, fSpeed);

}

From source file:com.google.android.exoplayer2.demo.MediaPlayerFragment.java

private void setAudioVolume(int vol, boolean up) {
    mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, vol, 0);

    /* Since android 4.3, the safe volume warning dialog is displayed only with the FLAG_SHOW_UI flag.
     * We don't want to always show the default UI volume, so show it only when volume is not set. */
    int newVol = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    if (vol != newVol) {
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, vol, AudioManager.FLAG_SHOW_UI);
    }/*from  w  w w  . jav a 2  s  . c  o  m*/

    mTouchAction = TOUCH_VOLUME;
    vol = vol * 100 / mAudioMax;
    int drawableId;
    if (newVol == 0) {
        drawableId = R.drawable.ic_volume_mute_white_36dp;
    } else if (up) {
        drawableId = R.drawable.ic_volume_up_white_36dp;
    } else {
        drawableId = R.drawable.ic_volume_down_white_36dp;
    }
    setVolumeOrBrightnessInfo(getContext().getString(R.string.volume_changing, vol), drawableId);
    //        showInfoWithVerticalBar(getString(R.string.volume) + "\n" + Integer.toString(vol) + '%', 1000, vol);
}

From source file:com.nd.android.u.square.service.MusicPlaybackService.java

/**
 * Starts playing the next song. If manualUrl is null, the next song will be randomly selected
 * from our Media Retriever (that is, it will be a random song in the user's device). If
 * manualUrl is non-null, then it specifies the URL or path to the song that will be played
 * next./*from ww  w. j  a va 2 s  .c  om*/
 */
void playNextSong(Item playingItem) {
    mState = State.Stopped;
    relaxResources(false); // release everything except MediaPlayer

    try {
        if (null == playingItem) {
            playingItem = pollNextSong(mPlayingItem);
            if (null == playingItem) {
                if (sOnStateChangedListener != null) {
                    sOnStateChangedListener.onPlayListIsEmpty();
                }
                return;
            }
            mPlayingItem = playingItem;

            if (null != sOnStateChangedListener)
                sOnStateChangedListener.onCurrentPlayingItemChanged(mPlayingItem);
        }

        // set the source of the media player a a content URI
        createMediaPlayerIfNeeded();
        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mPlayer.setDataSource(playingItem.getUrl());
        mIsStreaming = true;
        mSongTitle = playingItem.title;
        mState = State.Preparing;
        setUpAsForeground(mSongTitle + "");

        // Use the media button APIs (if available) to register ourselves for media button
        // events

        MediaButtonHelper.registerMediaButtonEventReceiverCompat(mAudioManager, mMediaButtonReceiverComponent);

        // Use the remote control APIs (if available) to set the playback state

        if (mRemoteControlClientCompat == null) {
            Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
            intent.setComponent(mMediaButtonReceiverComponent);
            mRemoteControlClientCompat = new RemoteControlClientCompat(PendingIntent
                    .getBroadcast(this /*context*/, 0 /*requestCode, ignored*/, intent /*intent*/, 0 /*flags*/
            ));
            RemoteControlHelper.registerRemoteControlClient(mAudioManager, mRemoteControlClientCompat);
        }

        mRemoteControlClientCompat.setPlaybackState(RemoteControlClient.PLAYSTATE_PLAYING);

        mRemoteControlClientCompat.setTransportControlFlags(
                RemoteControlClient.FLAG_KEY_MEDIA_PLAY | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE
                        | RemoteControlClient.FLAG_KEY_MEDIA_NEXT | RemoteControlClient.FLAG_KEY_MEDIA_STOP);

        // Update the remote controls
        mRemoteControlClientCompat.editMetadata(true)
                .putString(MediaMetadataRetriever.METADATA_KEY_TITLE, playingItem.title)
                .putLong(MediaMetadataRetriever.METADATA_KEY_DURATION, playingItem.duration)
                // TODO: fetch real item artwork
                .putBitmap(RemoteControlClientCompat.MetadataEditorCompat.METADATA_KEY_ARTWORK, mDummyAlbumArt)
                .apply();

        // 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!
        mPlayingItem.bufferedPercent = 0;
        mPlayer.prepareAsync();

        if (null != sOnStateChangedListener)
            sOnStateChangedListener.onPlayerPreparing(mPlayingItem);

        // 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. If, on the other hand,
        // we are *not* streaming, we want to release the lock if we were holding it before.
        if (mIsStreaming)
            mWifiLock.acquire();
        else if (mWifiLock.isHeld())
            mWifiLock.release();
    } catch (IOException ex) {
        Log.e(TAG, "IOException playing next song: " + ex.getMessage(), ex);
    }
}

From source file:com.kaku.weac.fragment.AlarmClockOntimeFragment.java

/**
 * /*from  www  .j av  a2 s .  c  om*/
 */
private void playRing() {
    mAudioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);

    mCurrentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    // ?
    mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, mAlarmClock.getVolume(), AudioManager.ADJUST_SAME);

    // 
    if (mAlarmClock.getRingUrl().equals(WeacConstants.DEFAULT_RING_URL)
            || TextUtils.isEmpty(mAlarmClock.getRingUrl())) {
        // ?
        if (mAlarmClock.isVibrate()) {
            // 
            AudioPlayer.getInstance(getActivity()).playRaw(R.raw.ring_weac_alarm_clock_default, true, true);
        } else {
            AudioPlayer.getInstance(getActivity()).playRaw(R.raw.ring_weac_alarm_clock_default, true, false);
        }

        // 
    } else if (mAlarmClock.getRingUrl().equals(WeacConstants.NO_RING_URL)) {
        // ?
        if (mAlarmClock.isVibrate()) {
            AudioPlayer.getInstance(getActivity()).stop();
            AudioPlayer.getInstance(getActivity()).vibrate();
        } else {
            AudioPlayer.getInstance(getActivity()).stop();
        }
    } else {
        // ?
        if (mAlarmClock.isVibrate()) {
            AudioPlayer.getInstance(getActivity()).play(mAlarmClock.getRingUrl(), true, true);
        } else {
            AudioPlayer.getInstance(getActivity()).play(mAlarmClock.getRingUrl(), true, false);
        }
    }
}

From source file:org.drrickorang.loopback.LoopbackActivity.java

/**
 * In the case where the test is started through adb command, this method will change the
 * settings if any parameter is specified.
 *///from   ww  w .  j a va  2 s  . c  o m
private void runIntentTest() {
    // mIntentRunning == true if test is started through adb command.
    if (mIntentRunning) {
        if (mIntentBufferTestDuration > 0) {
            getApp().setBufferTestDuration(mIntentBufferTestDuration);
        }

        if (mIntentAudioLevel >= 0) {
            AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            am.setStreamVolume(AudioManager.STREAM_MUSIC, mIntentAudioLevel, 0);
        }

        if (mIntentSamplingRate != 0) {
            getApp().setSamplingRate(mIntentSamplingRate);
        }

        if (mIntentMicSource >= 0) {
            getApp().setMicSource(mIntentMicSource);
        }

        if (mIntentAudioThread >= 0) {
            getApp().setAudioThreadType(mIntentAudioThread);
            getApp().computeDefaults();
        }

        int bytesPerFrame = Constant.BYTES_PER_FRAME;

        if (mIntentRecorderBuffer > 0) {
            getApp().setRecorderBufferSizeInBytes(mIntentRecorderBuffer * bytesPerFrame);
        }

        if (mIntentPlayerBuffer > 0) {
            getApp().setPlayerBufferSizeInBytes(mIntentPlayerBuffer * bytesPerFrame);
        }

        refreshState();

        if (mIntentTestType >= 0) {
            switch (mIntentTestType) {
            case Constant.LOOPBACK_PLUG_AUDIO_THREAD_TEST_TYPE_LATENCY:
                startLatencyTest();
                break;
            case Constant.LOOPBACK_PLUG_AUDIO_THREAD_TEST_TYPE_BUFFER_PERIOD:
                startBufferTest();
                break;
            default:
                assert (false);
            }
        } else {
            // if test type is not specified in command, just run latency test
            startLatencyTest();
        }

    }
}