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:org.cocos2dx.lib.Cocos2dxSound.java

private void initData() {
    this.mPathStreamIDsMap = new HashMap<String, ArrayList<Integer>>();
    this.mPathSoundIdMap = new HashMap<String, Integer>();
    mSoundPool = new SoundPool(MAX_SIMULTANEOUS_STREAMS_DEFAULT, AudioManager.STREAM_MUSIC, SOUND_QUALITY);

    this.mLeftVolume = 0.5f;
    this.mRightVolume = 0.5f;
}

From source file:com.darly.im.ui.CCPActivityBase.java

/**
 *
 * @return
 */
public int getStreamVolume() {
    return mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
}

From source file:com.example.android.supportv4.media.Playback.java

/**
 * Try to get the system audio focus./*from  w  w  w  .j  a v  a2s . c  om*/
 */
private void tryToGetAudioFocus() {
    Log.d(TAG, "tryToGetAudioFocus");
    if (mAudioFocus != AUDIO_FOCUSED) {
        int result = mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
                AudioManager.AUDIOFOCUS_GAIN);
        if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
            mAudioFocus = AUDIO_FOCUSED;
        }
    }
}

From source file:com.bayapps.android.robophish.playback.LocalPlayback.java

@Override
public void play(QueueItem item) {

    //we never call this if we're auto-queued due to gapless
    if (mMediaPlayersSwapping) {
        mMediaPlayersSwapping = false;/*w w  w . jav a  2  s .  c o m*/
    }

    mPlayOnFocusGain = true;
    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()));

        //noinspection ResourceType
        String source = track.getString(MusicProviderSource.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.mishiranu.dashchan.content.service.AudioPlayerService.java

private boolean play(boolean resetFocus) {
    if (resetFocus && audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN) != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        return false;
    }//from  w w  w  .j  a va  2 s.  c  o m
    mediaPlayer.start();
    wakeLock.acquire();
    return true;
}

From source file:com.appdevper.mediaplayer.app.LocalPlayback.java

/**
 * Try to get the system audio focus./* w  w  w  . j  a  v a2 s.com*/
 */
private void tryToGetAudioFocus() {
    LogHelper.d(TAG, "tryToGetAudioFocus");
    if (mAudioFocus != AUDIO_FOCUSED) {
        int result = mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
                AudioManager.AUDIOFOCUS_GAIN);
        if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
            mAudioFocus = AUDIO_FOCUSED;
        }
    }
}

From source file:com.ayaseya.padnotification.GcmIntentService.java

@Override
protected void onHandleIntent(final Intent intent) {

    extras = intent.getExtras();/*from   w w w. jav  a 2s. c  om*/

    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    // The getMessageType() intent parameter must be the intent you received
    // in your BroadcastReceiver.
    String messageType = gcm.getMessageType(intent);

    //      displayMessage(this, extras.toString());

    if (!extras.isEmpty()) { // has effect of unparcelling Bundle
        /*
         * Filter messages based on message type. Since it is likely that GCM will be
         * extended in the future with new message types, just ignore any message types you're
         * not interested in, or that you don't recognize.
         */
        if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
            //                sendNotification("Send error: " + extras.toString());
            Log.v(TAG, "Send error: " + extras.toString());
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
            //                sendNotification("Deleted messages on server: " + extras.toString());
            Log.v(TAG, "Deleted messages on server: " + extras.toString());
            // If it's a regular GCM message, do some work.
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
            // This loop represents the service doing some work.
            for (int i = 0; i < 5; i++) {
                Log.i(TAG, "Working... " + (i + 1) + "/5 @ " + SystemClock.elapsedRealtime());
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                }
            }
            Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
            // Post notification of received message.

            // ?????IntentService????????
            // ?????????
            new AsyncTask<Void, Void, Void>() {

                @Override
                protected Void doInBackground(Void... params) {
                    //                  Log.v(TAG, "doInBackground()");

                    // soundPool?????
                    soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
                    // soundPool??Listener??????
                    soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {

                        @Override
                        public void onLoadComplete(final SoundPool soundPool, int sampleId, int status) {
                            if (status == 0) {

                                if (notificationPermission) {// ????????

                                    // Notification????
                                    sendNotification("??????"
                                            + extras.get("INDEX") + "??", intent);

                                    //??????????

                                    if (isPlugged) {// ???????
                                        Log.v(TAG, "??????");
                                        if (ringerMode) {// 
                                            Log.v(TAG, "");
                                            if (checkbox_sound) {
                                                soundPool.play(se, 0.5F, 0.5F, 0, 0, 1.0F);
                                            }
                                            if (checkbox_vibration) {
                                                vibrator.vibrate(1500);
                                            }

                                        } else if (vibrateMode) {// 
                                            Log.v(TAG, "");
                                            if (checkbox_vibration) {
                                                vibrator.vibrate(1500);
                                            }

                                        } else if (silentMode) {// 
                                            Log.v(TAG, "");
                                            if (checkbox_sound) {
                                                soundPool.play(se, 0.5F, 0.5F, 0, 0, 1.0F);
                                            }
                                        }

                                    } else {// ?????????
                                        Log.v(TAG, "??????");
                                        if (ringerMode) {// 
                                            Log.v(TAG, "");
                                            if (checkbox_sound) {
                                                soundPool.play(se, 0.5F, 0.5F, 0, 0, 1.0F);
                                            }
                                            if (checkbox_vibration) {
                                                vibrator.vibrate(1500);
                                            }

                                        } else if (vibrateMode) {// 
                                            Log.v(TAG, "");
                                            if (checkbox_vibration) {
                                                vibrator.vibrate(1500);
                                            }

                                        } else if (silentMode) {// 
                                            Log.v(TAG, "");

                                        }
                                    }

                                }
                                // ?soundPool????
                                new Thread(new Runnable() {

                                    @Override
                                    public void run() {

                                        try {
                                            Thread.sleep(30000);
                                        } catch (InterruptedException e) {
                                        }
                                        //                                 Log.v(TAG, "soundPool.release()");

                                        soundPool.release();

                                    }
                                }).start();
                            }
                        }
                    });

                    // soundPool?????
                    se = soundPool.load(GcmIntentService.this, R.raw.notification_sound, 1);

                    return null;
                }

            }.execute(null, null, null);

            //            sendNotification("??????" + extras.get("INDEX") + "???", intent);
            //                sendNotification("Received: " + extras.toString());
            Log.i(TAG, "Received: " + extras.toString());
        }
    }
    // Release the wake lock provided by the WakefulBroadcastReceiver.
    GcmBroadcastReceiver.completeWakefulIntent(intent);
}

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 v a2  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.ayaseya.nolnotification.GcmIntentService.java

@Override
protected void onHandleIntent(final Intent intent) {

    extras = intent.getExtras();/*from w w  w .j  a va 2s  . co m*/

    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    // The getMessageType() intent parameter must be the intent you received
    // in your BroadcastReceiver.
    String messageType = gcm.getMessageType(intent);

    //      displayMessage(this, extras.toString());

    if (!extras.isEmpty()) { // has effect of unparcelling Bundle
        /*
         * Filter messages based on message type. Since it is likely that GCM will be
         * extended in the future with new message types, just ignore any message types you're
         * not interested in, or that you don't recognize.
         */
        if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
            //                sendNotification("Send error: " + extras.toString());
            Log.v(TAG, "Send error: " + extras.toString());
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
            //                sendNotification("Deleted messages on server: " + extras.toString());
            Log.v(TAG, "Deleted messages on server: " + extras.toString());
            // If it's a regular GCM message, do some work.
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
            // This loop represents the service doing some work.
            for (int i = 0; i < 5; i++) {
                Log.i(TAG, "Working... " + (i + 1) + "/5 @ " + SystemClock.elapsedRealtime());
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                }
            }
            Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
            // Post notification of received message.

            // ?????IntentService????????
            // ?????????
            new AsyncTask<Void, Void, Void>() {

                @Override
                protected Void doInBackground(Void... params) {
                    //                  Log.v(TAG, "doInBackground()");

                    // soundPool?????
                    soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
                    // soundPool??Listener??????
                    soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {

                        @Override
                        public void onLoadComplete(final SoundPool soundPool, int sampleId, int status) {
                            if (status == 0) {

                                if (notificationPermission) {// ????????

                                    // Notification????
                                    sendNotification("?????" + extras.get("INDEX")
                                            + "????", intent);

                                    //??????????

                                    if (isPlugged) {// ???????
                                        Log.v(TAG, "??????");
                                        if (ringerMode) {// 
                                            Log.v(TAG, "");
                                            if (checkbox_sound) {
                                                soundPool.play(se, 0.5F, 0.5F, 0, 0, 1.0F);
                                            }
                                            if (checkbox_vibration) {
                                                vibrator.vibrate(1500);
                                            }

                                        } else if (vibrateMode) {// 
                                            Log.v(TAG, "");
                                            if (checkbox_vibration) {
                                                vibrator.vibrate(1500);
                                            }

                                        } else if (silentMode) {// 
                                            Log.v(TAG, "");
                                            if (checkbox_sound) {
                                                soundPool.play(se, 0.5F, 0.5F, 0, 0, 1.0F);
                                            }
                                        }

                                    } else {// ?????????
                                        Log.v(TAG, "??????");
                                        if (ringerMode) {// 
                                            Log.v(TAG, "");
                                            if (checkbox_sound) {
                                                soundPool.play(se, 0.5F, 0.5F, 0, 0, 1.0F);
                                            }
                                            if (checkbox_vibration) {
                                                vibrator.vibrate(1500);
                                            }

                                        } else if (vibrateMode) {// 
                                            Log.v(TAG, "");
                                            if (checkbox_vibration) {
                                                vibrator.vibrate(1500);
                                            }

                                        } else if (silentMode) {// 
                                            Log.v(TAG, "");

                                        }
                                    }

                                }
                                // ?soundPool????
                                new Thread(new Runnable() {

                                    @Override
                                    public void run() {

                                        try {
                                            Thread.sleep(30000);
                                        } catch (InterruptedException e) {
                                        }
                                        //                                 Log.v(TAG, "soundPool.release()");

                                        soundPool.release();

                                    }
                                }).start();
                            }
                        }
                    });

                    // soundPool?????
                    se = soundPool.load(GcmIntentService.this, R.raw.notification_sound, 1);

                    return null;
                }

            }.execute(null, null, null);

            //            sendNotification("??????" + extras.get("INDEX") + "???", intent);
            //                sendNotification("Received: " + extras.toString());
            Log.i(TAG, "Received: " + extras.toString());
        }
    }
    // Release the wake lock provided by the WakefulBroadcastReceiver.
    GcmBroadcastReceiver.completeWakefulIntent(intent);
}

From source file:com.lithiumli.fiction.PlaybackService.java

private void prepareNext() {
    int position = mQueue.getCurrentPosition();

    if (position >= mQueue.getCount() - 1) {
        // TODO: repeat modes
        return;/*from  w w w .  j a va2  s.  com*/
    }

    Song song = mQueue.getItem(position + 1);
    try {
        mNextPlayer = new MediaPlayer();
        mNextPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mNextPlayer.setDataSource(getApplicationContext(), song.getUri());
        mNextPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer player) {
                if (mMediaPlayer == null) {
                } else {
                    mMediaPlayer.setNextMediaPlayer(player);
                    mMediaPlayer.setOnCompletionListener(PlaybackService.this);
                    player.setOnCompletionListener(PlaybackService.this);
                }
            }
        });
        mNextPlayer.prepareAsync();
    } catch (IOException e) {
    }
}