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.andryr.musicplayer.PlaybackService.java

public void play() {
    int result = mAudioManager.requestAudioFocus(mAudioFocusChangeListener, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN);
    if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        mMediaPlayer.start();//from  w  w w. j a  v  a2s .c  o  m
        mIsPlaying = true;
        mIsPaused = false;
        notifyChange(PLAYSTATE_CHANGED);
    }

}

From source file:leoisasmendi.android.com.suricatepodcast.services.MediaPlayerService.java

private boolean requestAudioFocus() {
    audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        //Focus gained
        return true;
    }/*from w  w w .j  av  a  2  s  .  c  om*/
    //Could not gain focus
    return false;
}

From source file:net.sourceforge.kalimbaradio.androidapp.service.DownloadServiceImpl.java

private synchronized void doPlay(final DownloadFile downloadFile, int position, boolean start) {
    try {//from   w  w  w.ja va  2  s.  c om
        final File file = downloadFile.isCompleteFileAvailable() ? downloadFile.getCompleteFile()
                : downloadFile.getPartialFile();
        downloadFile.updateModificationDate();
        mediaPlayer.setOnCompletionListener(null);
        mediaPlayer.reset();
        setPlayerState(IDLE);
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.setDataSource(file.getPath());
        setPlayerState(PREPARING);
        mediaPlayer.prepare();
        setPlayerState(PREPARED);

        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {

                // Acquire a temporary wakelock, since when we return from
                // this callback the MediaPlayer will release its wakelock
                // and allow the device to go to sleep.
                wakeLock.acquire(60000);

                setPlayerState(COMPLETED);

                // If COMPLETED and not playing partial file, we are *really" finished
                // with the song and can move on to the next.
                if (!file.equals(downloadFile.getPartialFile())) {
                    onSongCompleted();
                    return;
                }

                // If file is not completely downloaded, restart the playback from the current position.
                int pos = mediaPlayer.getCurrentPosition();
                synchronized (DownloadServiceImpl.this) {

                    // Work-around for apparent bug on certain phones: If close (less than ten seconds) to the end
                    // of the song, skip to the next rather than restarting it.
                    Integer duration = downloadFile.getSong().getDuration() == null ? null
                            : downloadFile.getSong().getDuration() * 1000;
                    if (duration != null) {
                        if (Math.abs(duration - pos) < 10000) {
                            LOG.info("Skipping restart from " + pos + " of " + duration);
                            onSongCompleted();
                            return;
                        }
                    }

                    LOG.info("Requesting restart from " + pos + " of " + duration);
                    reset();
                    bufferTask = new BufferTask(downloadFile, pos);
                    bufferTask.start();
                }
            }
        });

        if (position != 0) {
            LOG.info("Restarting player from position " + position);
            mediaPlayer.seekTo(position);
        }

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

    } catch (Exception x) {
        handleError(x);
    }
}

From source file:com.iamplus.musicplayer.MusicService.java

private void startPlayback() {
    try {/*  ww w .j  a  v a  2s  . c  o  m*/
        MediaItem playingItem = null;
        mIsStreaming = false; // playing a locally available song

        playingItem = MusicRetriever.getInstance().getCurrentSong();
        if (playingItem == null) {
            //Get all songs if the current list is empty
            MusicRetriever.getInstance().setSonglist(getAllSongs(), 0);
            MusicRetriever.getInstance().setPlayMode(e_play_mode.e_play_mode_shuffle);

            playingItem = MusicRetriever.getInstance().getCurrentSong();

            if (playingItem == null) {
                processStopRequest(true); // stop everything!
                return;
            }
        }
        mCurrentPlayingItem = playingItem;

        // set the source of the media player a a content URI
        createMediaPlayerIfNeeded();
        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mPlayer.setDataSource(getApplicationContext(), playingItem.getURI());

        // 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(TAG, "IOException playing first song: " + ex.getMessage());
        //ex.printStackTrace();
        Toast.makeText(getApplicationContext(), R.string.invalid_file_track, Toast.LENGTH_LONG).show();
        //Stop Playback
        processStopRequest();
        return;
    }
    //mSongTitle = mCurrentPlayingItem.getTitle();

    //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.setTransportControlFlags(
            RemoteControlClient.FLAG_KEY_MEDIA_PLAY | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE
                    | RemoteControlClient.FLAG_KEY_MEDIA_NEXT | RemoteControlClient.FLAG_KEY_MEDIA_STOP);

    updateRemoteControlPlayingState();
}

From source file:com.wanikani.androidnotifier.WebReviewActivity.java

/**
 * Called when the action is initially displayed. It initializes the objects
 * and starts loading the review page.// w w w.  jav  a 2 s. c o m
 *    @param bundle the saved bundle
 */
@Override
public void onCreate(Bundle bundle) {
    super.onCreate(bundle);

    Resources res;

    CookieSyncManager.createInstance(this);
    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    mh = new MenuHandler(this, new MenuListener());

    if (SettingsActivity.getFullscreen(this)) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
    }

    setContentView(R.layout.web_review);

    res = getResources();

    selectedColor = res.getColor(R.color.selected);
    unselectedColor = res.getColor(R.color.unselected);

    muteDrawable = res.getDrawable(R.drawable.ic_mute);
    notMutedDrawable = res.getDrawable(R.drawable.ic_not_muted);

    kbstatus = KeyboardStatus.INVISIBLE;

    bar = (ProgressBar) findViewById(R.id.pb_reviews);
    dbar = (ProgressBar) findViewById(R.id.pb_download);

    ignbtn = (ImageButton) findViewById(R.id.btn_ignore);
    ignbtn.setOnClickListener(new IgnoreButtonListener());

    /* First of all get references to views we'll need in the near future */
    splashView = findViewById(R.id.wv_splash);
    contentView = findViewById(R.id.wv_content);
    msgw = (TextView) findViewById(R.id.tv_message);
    wv = (FocusWebView) findViewById(R.id.wv_reviews);

    wv.getSettings().setJavaScriptEnabled(true);
    wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    wv.getSettings().setSupportMultipleWindows(false);
    wv.getSettings().setUseWideViewPort(false);
    wv.getSettings().setDatabaseEnabled(true);
    wv.getSettings().setDomStorageEnabled(true);
    wv.getSettings().setDatabasePath(getFilesDir().getPath() + "/wv");
    wv.addJavascriptInterface(new WKNKeyboard(), "wknKeyboard");
    wv.setScrollBarStyle(ScrollView.SCROLLBARS_OUTSIDE_OVERLAY);
    wv.setWebViewClient(new WebViewClientImpl());
    wv.setWebChromeClient(new WebChromeClientImpl());

    download = getIntent().getAction().equals(DOWNLOAD_ACTION);
    if (download) {
        downloadPrefix = getIntent().getStringExtra(EXTRA_DOWNLOAD_PREFIX);
        wv.setDownloadListener(fda = new FileDownloader());
    }

    wv.loadUrl(getIntent().getData().toString());

    nativeKeyboard = new NativeKeyboard(this, wv);
    localIMEKeyboard = new LocalIMEKeyboard(this, wv);

    muteH = (ImageButton) findViewById(R.id.kb_mute_h);
    muteH.setOnClickListener(new MuteListener());

    singleb = (Button) findViewById(R.id.kb_single);
    singleb.setOnClickListener(new SingleListener());

    if (SettingsActivity.getTimerReaper(this)) {
        reaper = new TimerThreadsReaper();
        rtask = reaper.createTask(new Handler(), 2, 7000);
        rtask.setListener(new ReaperTaskListener());
    }
}

From source file:com.fastbootmobile.encore.service.PlaybackService.java

/**
 * Request the audio focus and registers the remote media controller
 *///from  www .j  a v  a2  s  . c  o m
private synchronized void requestAudioFocus() {
    if (!mHasAudioFocus) {
        final AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

        // Request audio focus for music playback
        int result = am.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

        if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
            am.registerMediaButtonEventReceiver(RemoteControlReceiver.getComponentName(this));

            // Notify the remote metadata that we're getting active
            mRemoteMetadata.setActive(true);

            // Register AUDIO_BECOMING_NOISY to stop playback when earbuds are pulled
            registerReceiver(mAudioNoisyReceiver, new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY));

            // Add a WakeLock to avoid CPU going to sleep while music is playing
            mWakeLock.acquire();

            mHasAudioFocus = true;
        } else {
            Log.e(TAG, "Audio focus request denied: " + result);
        }
    }
}

From source file:com.nbplus.vbroadlauncher.RealtimeBroadcastActivity.java

private void finishActivity() {
    Log.d(TAG, "finishActivity()");
    runOnUiThread(new Runnable() {
        @Override//w  w  w  .j av  a 2 s . c o m
        public void run() {
            LauncherSettings.getInstance(getApplicationContext()).setCurrentPlayingBroadcastType(null);

            overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
            if (mText2Speech != null) {
                mText2Speech.shutdown();
            }
            mText2Speech = null;
            mText2SpeechHandler = null;
            mBroadcastPayloadIdx = -1;

            if (mWebView != null) {
                mWebView.removeAllViews();
                mWebView.destroy();
            }
            mWebViewClient = null;
            mWebView = null;
            LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(mBroadcastReceiver);
            unregisterReceiver(mBroadcastReceiver);

            releaseCpuLock();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showSystemUI();
                }
            });

            AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            audio.setStreamVolume(AudioManager.STREAM_MUSIC, mStreamMusicVolume, AudioManager.FLAG_PLAY_SOUND);

            //finish();
            Log.e(TAG, "RealtimeBroadcastActivity.java call System.exit(0)");
            System.exit(0);
        }
    });
}

From source file:com.tealeaf.TeaLeaf.java

private void configureActivity() {
    getWindow().requestFeature(Window.FEATURE_NO_TITLE);
    if (isFullScreen) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }//from www  .j  ava  2s . c  o  m
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
}

From source file:com.wojtechnology.sunami.TheBrain.java

private void init() {
    mSongManager = new SongManager(this);
    mGenreGraph = new GenreGraph(this);
    mSongHistory = new SongHistory(HISTORY_SIZE);
    mShuffleController = new ShuffleController(this, mGenreGraph, mSongManager, mUpNext);
    mMediaPlayer = new MediaPlayer();

    // Setting wake locks
    mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
    mWakeLock.acquire();/*from w w w. j  a  v a  2 s . c o m*/

    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            if (!mPreparing) {
                playNext();
            }
        }
    });
    mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            return false;
        }
    });
    mMediaPlayer.setOnPreparedListener(mMPPreparedListener);
    mContext.setVolumeControlStream(AudioManager.STREAM_MUSIC);
}

From source file:com.smithdtyler.prettygoodmusicplayer.MusicPlaybackService.java

private synchronized void play() {
    pauseTime = Long.MAX_VALUE;//from w  w w  .j av a2s .  co m
    if (mp.isPlaying()) {
        // do nothing
    } else {
        // Request audio focus for playback
        int result = am.requestAudioFocus(MusicPlaybackService.this.audioFocusListener,
                // Use the music stream.
                AudioManager.STREAM_MUSIC,
                // Request permanent focus.
                AudioManager.AUDIOFOCUS_GAIN);
        Log.d(TAG, "requestAudioFocus result = " + result);
        Log.i(TAG, "About to play " + songFile);

        if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
            Log.d(TAG, "We got audio focus!");
            mp.start();
            updateNotification();
            wakeLock.acquire();
        } else {
            Log.e(TAG, "Unable to get audio focus");
        }
    }
}