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.kiandastream.musicplayer.MusicService.java

void processPreviousRequest() {

    if (mState == State.Starting) {
        if (song_playlist != null) {
            if (Integer.parseInt(positionofsong) > 0) {
                if ((Integer.parseInt(positionofsong) - 1) < song_playlist.size()) {
                    Integer pos = Integer.parseInt(positionofsong) - 1;
                    positionofsong = pos.toString();
                    createMediaPlayerIfNeeded();
                    mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    try {
                        //String songurl="http://api.kiandastream.globusapps.com/static/songs/"+song_playlist.get(Integer.parseInt(positionofsong)).getSong_id()+".mp3";
                        System.out.println("url of song playing is "
                                + song_playlist.get(Integer.parseInt(positionofsong)).getSongurl());
                        mPlayer.setDataSource(song_playlist.get(Integer.parseInt(positionofsong)).getSongurl());
                        setNotification("Loading");
                        mState = State.Preparing;
                        //Setting title in notification bar

                        mPlayer.prepareAsync();
                        if (!mWifiLock.isHeld())
                            mWifiLock.acquire();
                    } catch (NumberFormatException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IllegalArgumentException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (SecurityException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IllegalStateException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }/*from  ww w  .j a va  2  s  . c  o  m*/
                } else
                    relaxResources(true);
            }
        } else
            relaxResources(true);
    } else if (mState == State.Playing) {
        if (song_playlist != null) {
            if (Integer.parseInt(positionofsong) > 0) {
                if ((Integer.parseInt(positionofsong) - 1) < song_playlist.size()) {
                    Integer pos = Integer.parseInt(positionofsong) - 1;
                    positionofsong = pos.toString();
                    if (listener != null)
                        listener.stopUpdating(mPlayer);
                    mPlayer.pause();

                    mPlayer.reset();

                    mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    try {
                        //String songurl="http://api.kiandastream.globusapps.com/static/songs/"+song_playlist.get(Integer.parseInt(positionofsong)).getSong_id()+".mp3";
                        System.out.println("url of song playing is "
                                + song_playlist.get(Integer.parseInt(positionofsong)).getSongurl());
                        mPlayer.setDataSource(song_playlist.get(Integer.parseInt(positionofsong)).getSongurl());
                        setNotification("Loading");
                        mState = State.Preparing;
                        //Setting title in notification bar

                        mPlayer.prepareAsync();
                        if (!mWifiLock.isHeld())
                            mWifiLock.acquire();
                    } catch (NumberFormatException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IllegalArgumentException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (SecurityException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IllegalStateException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    if (mState == State.Paused) {
        if (song_playlist != null) {
            if (Integer.parseInt(positionofsong) > 0) {
                if ((Integer.parseInt(positionofsong) - 1) < song_playlist.size()) {
                    Integer pos = Integer.parseInt(positionofsong) - 1;
                    positionofsong = pos.toString();
                    createMediaPlayerIfNeeded();
                    mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    try {
                        //String songurl="http://api.kiandastream.globusapps.com/static/songs/"+song_playlist.get(Integer.parseInt(positionofsong)).getSong_id()+".mp3";
                        System.out.println("url of song playing is "
                                + song_playlist.get(Integer.parseInt(positionofsong)).getSongurl());
                        mPlayer.setDataSource(song_playlist.get(Integer.parseInt(positionofsong)).getSongurl());
                        setNotification("Loading");
                        mState = State.Preparing;
                        //Setting title in notification bar

                        mPlayer.prepareAsync();
                        if (!mWifiLock.isHeld())
                            mWifiLock.acquire();
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (SecurityException e) {
                        e.printStackTrace();
                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "Last Song of Playlist", Toast.LENGTH_LONG).show();
                    relaxResources(true);
                }
            }
        }

    }

}

From source file:com.example.mydemos.view.RingtonePickerActivity.java

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
    Log.e("lys", "onItemClick position ==" + position + "id" + id);
    if (id == -1) {
        if (mHasSilentItem) {

            if ((mHasDefaultItem && (position == 1)) || !mHasDefaultItem) {
                Log.e("lys", "onItemClick silentItemChecked == true");
                //toneCur.moveToPosition(position);
                mSelectedId = SILENT_ID;
                mSelectedUri = null;//from  ww w. ja  v a  2  s .  c  o  m
                silentItemChecked = true;
                defaultItemChecked = false;
                stopMediaPlayer();
                listView.invalidateViews();
                return;
            } else if (mHasDefaultItem && (position == 0)) {
                Log.e("lys", "onItemClick defaultItemChecked == true");
                //toneCur.moveToPosition(position);
                mSelectedId = DEFAULT_ID;
                mSelectedUri = mUriForDefaultItem;
                defaultItemChecked = true;
                silentItemChecked = false;
            }
        } else {
            if (mHasDefaultItem) {
                Log.e("lys", "onItemClick defaultItemChecked == true");
                //toneCur.moveToPosition(position);
                mSelectedId = DEFAULT_ID;
                mSelectedUri = mUriForDefaultItem;
                defaultItemChecked = true;
                silentItemChecked = false;
            }
        }

    } else {
        if (mHasSilentItem) {
            silentItemChecked = false;
            position--;
        }

        if (mHasDefaultItem) {
            defaultItemChecked = false;
            position--;
        }
    }
    if (id != -1) {
        toneCur.moveToPosition(position);
        Log.e("lys", "onItemClick position == " + position + "id ==" + id);
        long newId = toneCur.getLong(toneCur.getColumnIndex(MediaStore.Audio.Media._ID));
        mSelectedId = newId;
        Log.e("lys", " onItemClick mSelectedId==" + mSelectedId);

        //wuqingliang modify begin20130307
        if (tabName == SYSTEM_TONE) {
            BaseUri = MediaStore.Audio.Media.INTERNAL_CONTENT_URI;
            Log.e("lys", "BaseUri = MediaStore.Audio.Media.INTERNAL_CONTENT_URI;111111");
        } else {
            BaseUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            Log.e("lys", "BaseUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;1111111");
        }
        //wuqingliang modify end
        mSelectedUri = ContentUris.withAppendedId(BaseUri, newId);
    }
    listView.invalidateViews();
    audioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
    stopMediaPlayer();
    mMediaPlayer = new MediaPlayer();
    try {
        if (toneType == ALARM_TYPE)
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
        else
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
        mMediaPlayer.setDataSource(RingtonePickerActivity.this, mSelectedUri);
        mMediaPlayer.prepare();
        mMediaPlayer.start();

    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.speedtong.example.ui.chatting.ChattingActivity.java

private void initToneGenerator() {
    AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    if (mToneGenerator == null) {
        try {/*from  ww  w  .j  a v  a 2  s.c om*/
            int streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            int streamMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            int volume = (int) (TONE_RELATIVE_VOLUME * (streamVolume / streamMaxVolume));
            mToneGenerator = new ToneGenerator(AudioManager.STREAM_MUSIC, volume);

        } catch (RuntimeException e) {
            LogUtil.d("Exception caught while creating local tone generator: " + e);
            mToneGenerator = null;
        }
    }
}

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

private void requestAudioFocus() {
    // Request audio focus for playback
    int result = PsfAudioManager.requestAudioFocus(AudioFocusChangeListener,
            // Use the music stream.
            AudioManager.STREAM_MUSIC,
            // Request permanent focus.
            AudioManager.AUDIOFOCUS_GAIN);

    if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        Log.d(LOGTAG, "Audio focus granted");
    } else {//  w  ww.  ja va  2s . c o m
        Log.w(LOGTAG, "Audio focus not granted: " + result);
    }
}

From source file:org.freelectron.leobel.testlwa.models.AVSAudioPlayer.java

private void setupSpeaker(boolean speech) {
    speaker = new CustomMediaPlayer();
    speaker.setAudioStreamType(AudioManager.STREAM_MUSIC);
    if (speech) {
        speaker.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override/*w  w  w  .  j a v a 2s  .  co  m*/
            public void onCompletion(MediaPlayer mediaPlayer) {
                finishedSpeechItem();
            }
        });
    }

}

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

public void submitChat() {

    ChatConfig config = new ChatConfig();
    config.instance = this.instance.id;
    config.conversation = MainActivity.conversation;
    config.speak = !MainActivity.deviceVoice;
    config.avatar = this.avatarId;
    if (MainActivity.translate && MainActivity.voice != null) {
        config.language = MainActivity.voice.language;
    }//from   w  ww.ja v  a2s  . c  o m
    if (MainActivity.disableVideo) {
        config.avatarFormat = "image";
    } else {
        config.avatarFormat = MainActivity.webm ? "webm" : "mp4";
    }
    config.avatarHD = MainActivity.hd;

    EditText v = (EditText) findViewById(R.id.messageText);
    config.message = v.getText().toString().trim();
    if (config.message.equals("")) {
        return;
    }
    this.messages.add(config);
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            ListView list = (ListView) findViewById(R.id.chatList);
            ((ChatListAdapter) list.getAdapter()).notifyDataSetChanged();
            list.invalidateViews();
        }

    });

    Spinner emoteSpin = (Spinner) findViewById(R.id.emoteSpin);
    config.emote = emoteSpin.getSelectedItem().toString();

    HttpChatAction action = new HttpChatAction(ChatActivity.this, config);
    action.execute();

    v.setText("");
    emoteSpin.setSelection(0);
    resetToolbar();

    WebView responseView = (WebView) findViewById(R.id.responseText);
    responseView.loadDataWithBaseURL(null, "thinking...", "text/html", "utf-8", null);

    //Check the volume
    AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    int volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    if (volume <= 3 && volumeChecked) {
        Toast.makeText(this, "Please check 'Media' volume", Toast.LENGTH_LONG).show();
        volumeChecked = false;
    }

    //stop letting the mic on.
    stopListening();
    //its Important for "sleep" "scream" ...etc commands.
    //this will turn off the mic
    MainActivity.listenInBackground = false;
}

From source file:com.juce.jucedemo.JuceDemo.java

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

    isScreenSaverEnabled = true;/*from  w w  w. j  a va 2  s. c  om*/
    hideActionBar();
    viewHolder = new ViewHolder(this);
    setContentView(viewHolder);

    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    permissionCallbackPtrMap = new HashMap<Integer, Long>();
}

From source file:com.shinymayhem.radiopresets.ServiceRadioPlayer.java

/**
 * Called after audio format service processes the url and gets a streaming media url from it (if it was a playlist or something)
 * @param url/*from  ww  w. ja  v a2 s.c o m*/
 */
private void playUrl(String url) {
    if (LOCAL_LOGD)
        log("playUrl " + url, "d");
    if (!mCurrentPlayerState.equals(ServiceRadioPlayer.STATE_INITIALIZING)) {
        if (LOCAL_LOGV)
            log("incorrect state to play url", "v");
        return;
    }
    this.stopAndReleasePlayer(mMediaPlayer);
    this.mMediaPlayer = new MediaPlayer();
    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mCurrentPlayerState = ServiceRadioPlayer.STATE_PREPARING;

    //get playlist data
    AsyncTaskPlaylist playlist = new AsyncTaskPlaylist();
    playlist.execute(mUrl);
    if (LOCAL_LOGV)
        log("get metadata", "v");
    if (!mMetadataRunnable.isRunning()) {
        mMetadataRunnable.init();
    }

    //play url
    try {
        //str += mUrl;
        if (LOCAL_LOGV)
            log("setting datasource for '" + mTitle + "' at '" + url + "'", "v");
        mMediaPlayer.setDataSource(url);
        initializePlayer(mMediaPlayer);

    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        log("IllegalArgumentException, setting data source failed", "e");
        if (LOCAL_LOGV)
            e.printStackTrace();
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        log("SecurityException, setting data source failed", "e");
        if (LOCAL_LOGV)
            e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        log("IllegalStateException, setting data source failed", "e");
        if (LOCAL_LOGV)
            e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        //TODO handle this somehow, let user know
        log("IOException, setting data source failed", "e");
        if (LOCAL_LOGV)
            e.printStackTrace();
    }

    mMediaPlayer.prepareAsync(); // might take long! (for buffering, etc)
    if (LOCAL_LOGV)
        log("preparing async", "v");

}

From source file:github.daneren2005.dsub.service.DownloadServiceImpl.java

private synchronized void doPlay(final DownloadFile downloadFile, final int position, final boolean start) {
    try {//from   w w w .  j  a  v a 2  s. c o m
        downloadFile.setPlaying(true);
        final File file = downloadFile.isCompleteFileAvailable() ? downloadFile.getCompleteFile()
                : downloadFile.getPartialFile();
        isPartial = file.equals(downloadFile.getPartialFile());
        downloadFile.updateModificationDate();

        mediaPlayer.setOnCompletionListener(null);
        mediaPlayer.reset();
        setPlayerState(IDLE);
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        String dataSource = file.getPath();
        if (isPartial) {
            if (proxy == null) {
                proxy = new StreamProxy(this);
                proxy.start();
            }
            dataSource = String.format("http://127.0.0.1:%d/%s", proxy.getPort(),
                    URLEncoder.encode(dataSource, Constants.UTF_8));
            Log.i(TAG, "Data Source: " + dataSource);
        } else if (proxy != null) {
            proxy.stop();
            proxy = null;
        }
        mediaPlayer.setDataSource(dataSource);
        setPlayerState(PREPARING);

        mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
            public void onBufferingUpdate(MediaPlayer mp, int percent) {
                Log.i(TAG, "Buffered " + percent + "%");
                if (percent == 100) {
                    mediaPlayer.setOnBufferingUpdateListener(null);
                }
            }
        });

        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            public void onPrepared(MediaPlayer mediaPlayer) {
                try {
                    setPlayerState(PREPARED);

                    synchronized (DownloadServiceImpl.this) {
                        if (position != 0) {
                            Log.i(TAG, "Restarting player from position " + position);
                            mediaPlayer.seekTo(position);
                        }
                        cachedPosition = position;

                        if (start) {
                            mediaPlayer.start();
                            setPlayerState(STARTED);
                        } else {
                            setPlayerState(PAUSED);
                        }
                    }

                    lifecycleSupport.serializeDownloadQueue();
                } catch (Exception x) {
                    handleError(x);
                }
            }
        });

        setupHandlers(downloadFile, isPartial);

        mediaPlayer.prepareAsync();
    } catch (Exception x) {
        handleError(x);
    }
}