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:io.puzzlebox.orbit.ui.OrbitFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_orbit, container, false);

    //      requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    //      setContentView(R.layout.main);
    //      getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);

    buttonConnectOrbit = (Button) v.findViewById(R.id.buttonConnectOrbit);
    buttonConnectOrbit.setOnClickListener(new View.OnClickListener() {
        @Override//from   w  w w .  j av a 2s .com
        public void onClick(View v) {
            setOrbitActivate();
        }
    });

    Button buttonTestFlight = (Button) v.findViewById(R.id.buttonTestFlight);
    buttonTestFlight.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            demoMode(v);
        }
    });

    progressBarAttention = (ProgressBar) v.findViewById(R.id.progressBarAttention);
    final float[] roundedCorners = new float[] { 5, 5, 5, 5, 5, 5, 5, 5 };
    ShapeDrawable progressBarAttentionDrawable = new ShapeDrawable(
            new RoundRectShape(roundedCorners, null, null));
    String progressBarAttentionColor = "#FF0000";
    progressBarAttentionDrawable.getPaint().setColor(Color.parseColor(progressBarAttentionColor));
    ClipDrawable progressAttention = new ClipDrawable(progressBarAttentionDrawable, Gravity.LEFT,
            ClipDrawable.HORIZONTAL);
    progressBarAttention.setProgressDrawable(progressAttention);
    progressBarAttention
            .setBackgroundDrawable(getResources().getDrawable(android.R.drawable.progress_horizontal));

    progressBarMeditation = (ProgressBar) v.findViewById(R.id.progressBarMeditation);
    ShapeDrawable progressBarMeditationDrawable = new ShapeDrawable(
            new RoundRectShape(roundedCorners, null, null));
    String progressBarMeditationColor = "#0000FF";
    progressBarMeditationDrawable.getPaint().setColor(Color.parseColor(progressBarMeditationColor));
    ClipDrawable progressMeditation = new ClipDrawable(progressBarMeditationDrawable, Gravity.LEFT,
            ClipDrawable.HORIZONTAL);
    progressBarMeditation.setProgressDrawable(progressMeditation);
    progressBarMeditation
            .setBackgroundDrawable(getResources().getDrawable(android.R.drawable.progress_horizontal));

    progressBarSignal = (ProgressBar) v.findViewById(R.id.progressBarSignal);
    ShapeDrawable progressBarSignalDrawable = new ShapeDrawable(new RoundRectShape(roundedCorners, null, null));
    String progressBarSignalColor = "#00FF00";
    progressBarSignalDrawable.getPaint().setColor(Color.parseColor(progressBarSignalColor));
    ClipDrawable progressSignal = new ClipDrawable(progressBarSignalDrawable, Gravity.LEFT,
            ClipDrawable.HORIZONTAL);
    progressBarSignal.setProgressDrawable(progressSignal);
    progressBarSignal.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.progress_horizontal));
    //      progressBarSignal.setProgress(tgSignal);

    progressBarPower = (ProgressBar) v.findViewById(R.id.progressBarPower);
    ShapeDrawable progressBarPowerDrawable = new ShapeDrawable(new RoundRectShape(roundedCorners, null, null));
    String progressBarPowerColor = "#FFFF00";
    progressBarPowerDrawable.getPaint().setColor(Color.parseColor(progressBarPowerColor));
    ClipDrawable progressPower = new ClipDrawable(progressBarPowerDrawable, Gravity.LEFT,
            ClipDrawable.HORIZONTAL);
    progressBarPower.setProgressDrawable(progressPower);
    progressBarPower.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.progress_horizontal));

    seekBarAttention = (SeekBar) v.findViewById(R.id.seekBarAttention);
    seekBarAttention.setOnSeekBarChangeListener(this);
    seekBarMeditation = (SeekBar) v.findViewById(R.id.seekBarMeditation);
    seekBarMeditation.setOnSeekBarChangeListener(this);

    imageViewStatus = (ImageView) v.findViewById(R.id.imageViewStatus);

    textViewLabelScores = (TextView) v.findViewById(R.id.textViewLabelScores);
    textViewLabelScore = (TextView) v.findViewById(R.id.textViewLabelScore);
    textViewLabelLastScore = (TextView) v.findViewById(R.id.textViewLabelLastScore);
    textViewLabelHighScore = (TextView) v.findViewById(R.id.textViewLabelHighScore);

    viewSpaceScore = (View) v.findViewById(R.id.viewSpaceScore);
    viewSpaceScoreLast = (View) v.findViewById(R.id.viewSpaceScoreLast);
    viewSpaceScoreHigh = (View) v.findViewById(R.id.viewSpaceScoreHigh);

    textViewScore = (TextView) v.findViewById(R.id.textViewScore);
    textViewLastScore = (TextView) v.findViewById(R.id.textViewLastScore);
    textViewHighScore = (TextView) v.findViewById(R.id.textViewHighScore);

    // Hide the "Scores" label by default
    textViewLabelScores.setVisibility(View.GONE);
    viewSpaceScore.setVisibility(View.GONE);

    /**
     * AudioHandler
     */

    if (!OrbitSingleton.getInstance().audioHandler.isAlive()) {

        /**
         * Prepare audio stream
         */

        maximizeAudioVolume(); // Automatically set media volume to maximum

        /** Set the hardware buttons to control the audio output */
        getActivity().setVolumeControlStream(AudioManager.STREAM_MUSIC);

        /** Preload the flight control WAV file into memory */
        OrbitSingleton.getInstance().soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
        OrbitSingleton.getInstance().soundPool
                .setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
                    public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                        OrbitSingleton.getInstance().loaded = true;
                    }
                });
        OrbitSingleton.getInstance().soundID = OrbitSingleton.getInstance().soundPool
                .load(getActivity().getApplicationContext(), OrbitSingleton.getInstance().audioFile, 1);

        OrbitSingleton.getInstance().audioHandler.start();

    }

    if (OrbitSingleton.getInstance().flightActive)
        buttonTestFlight.setText(getResources().getString(R.string.button_stop_test));

    /**
     * Update settings according to default UI
     */

    updateScreenLayout();

    updatePowerThresholds();
    //      updatePower();

    return v;

}

From source file:kz.qobyzbook.manager.MusicPlayerService.java

@SuppressLint("NewApi")
private void createNotification(SongDetail mSongDetail) {
    try {/* w w  w.j av a  2 s  .  c o  m*/
        String songName = mSongDetail.getTitle();
        String authorName = mSongDetail.getArtist();
        String songImage = mSongDetail.getImage_url();
        SongDetail audioInfo = MediaController.getInstance().getPlayingSongDetail();

        RemoteViews simpleContentView = new RemoteViews(getApplicationContext().getPackageName(),
                R.layout.player_small_notification);
        RemoteViews expandedView = null;
        if (supportBigNotifications) {
            expandedView = new RemoteViews(getApplicationContext().getPackageName(),
                    R.layout.player_big_notification);
        }

        Intent intent = new Intent(ApplicationDMPlayer.applicationContext, DMPlayerBaseActivity.class);
        intent.setAction("openplayer");
        intent.setFlags(32768);
        PendingIntent contentIntent = PendingIntent.getActivity(ApplicationDMPlayer.applicationContext, 0,
                intent, 0);

        Notification notification = new NotificationCompat.Builder(getApplicationContext())
                .setSmallIcon(R.drawable.player).setContentIntent(contentIntent).setContentTitle(songName)
                .build();

        notification.contentView = simpleContentView;
        if (supportBigNotifications) {
            notification.bigContentView = expandedView;
        }

        setListeners(simpleContentView);
        if (supportBigNotifications) {
            setListeners(expandedView);
        }

        Bitmap albumArt = audioInfo != null ? audioInfo.getSmallCover(ApplicationDMPlayer.applicationContext)
                : null;

        if (albumArt != null) {
            notification.contentView.setImageViewBitmap(R.id.player_album_art, albumArt);
            if (supportBigNotifications) {
                notification.bigContentView.setImageViewBitmap(R.id.player_album_art, albumArt);
            }
        } else {
            notification.contentView.setImageViewResource(R.id.player_album_art,
                    R.drawable.bg_default_album_art);
            if (supportBigNotifications) {
                notification.bigContentView.setImageViewResource(R.id.player_album_art,
                        R.drawable.bg_default_album_art);
            }
        }
        notification.contentView.setViewVisibility(R.id.player_progress_bar, View.GONE);
        notification.contentView.setViewVisibility(R.id.player_next, View.VISIBLE);
        notification.contentView.setViewVisibility(R.id.player_previous, View.VISIBLE);
        if (supportBigNotifications) {
            notification.bigContentView.setViewVisibility(R.id.player_next, View.VISIBLE);
            notification.bigContentView.setViewVisibility(R.id.player_previous, View.VISIBLE);
            notification.bigContentView.setViewVisibility(R.id.player_progress_bar, View.GONE);
        }

        if (MediaController.getInstance().isAudioPaused()) {
            notification.contentView.setViewVisibility(R.id.player_pause, View.GONE);
            notification.contentView.setViewVisibility(R.id.player_play, View.VISIBLE);
            if (supportBigNotifications) {
                notification.bigContentView.setViewVisibility(R.id.player_pause, View.GONE);
                notification.bigContentView.setViewVisibility(R.id.player_play, View.VISIBLE);
            }
        } else {
            notification.contentView.setViewVisibility(R.id.player_pause, View.VISIBLE);
            notification.contentView.setViewVisibility(R.id.player_play, View.GONE);
            if (supportBigNotifications) {
                notification.bigContentView.setViewVisibility(R.id.player_pause, View.VISIBLE);
                notification.bigContentView.setViewVisibility(R.id.player_play, View.GONE);
            }
        }

        notification.contentView.setTextViewText(R.id.player_song_name, songName);
        notification.contentView.setTextViewText(R.id.player_author_name, authorName);
        if (supportBigNotifications) {
            notification.bigContentView.setTextViewText(R.id.player_song_name, songName);
            notification.bigContentView.setTextViewText(R.id.player_author_name, authorName);
            //                notification.bigContentView.setTextViewText(R.id.player_albumname, albumName);
        }
        notification.flags |= Notification.FLAG_ONGOING_EVENT;
        startForeground(5, notification);

        if (remoteControlClient != null) {
            RemoteControlClient.MetadataEditor metadataEditor = remoteControlClient.editMetadata(true);
            metadataEditor.putString(MediaMetadataRetriever.METADATA_KEY_ARTIST, authorName);
            metadataEditor.putString(MediaMetadataRetriever.METADATA_KEY_TITLE, songName);
            if (audioInfo != null && audioInfo.getCover(ApplicationDMPlayer.applicationContext) != null) {
                metadataEditor.putBitmap(RemoteControlClient.MetadataEditor.BITMAP_KEY_ARTWORK,
                        audioInfo.getCover(ApplicationDMPlayer.applicationContext));
            }
            metadataEditor.apply();
            audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:co.codecrunch.musicplayerlite.manager.MusicPlayerService.java

@SuppressLint("NewApi")
private void createNotification(SongDetail mSongDetail) {
    try {/*from w  ww.  j a v  a 2 s.c  om*/
        String songName = mSongDetail.getTitle();
        String authorName = mSongDetail.getArtist();
        String albumName = mSongDetail.getDisplay_name();
        SongDetail audioInfo = MediaController.getInstance().getPlayingSongDetail();

        RemoteViews simpleContentView = new RemoteViews(getApplicationContext().getPackageName(),
                R.layout.player_small_notification);
        RemoteViews expandedView = null;
        if (supportBigNotifications) {
            expandedView = new RemoteViews(getApplicationContext().getPackageName(),
                    R.layout.player_big_notification);
        }

        Intent intent = new Intent(ApplicationMusicPlayer.applicationContext, MusicPlayerBaseActivity.class);
        intent.setAction("openplayer");
        intent.setFlags(32768);
        PendingIntent contentIntent = PendingIntent.getActivity(ApplicationMusicPlayer.applicationContext, 0,
                intent, 0);

        Notification notification = new NotificationCompat.Builder(getApplicationContext())
                .setSmallIcon(R.drawable.player).setContentIntent(contentIntent).setContentTitle(songName)
                .build();

        notification.contentView = simpleContentView;
        if (supportBigNotifications) {
            notification.bigContentView = expandedView;
        }

        setListeners(simpleContentView);
        if (supportBigNotifications) {
            setListeners(expandedView);
        }

        Bitmap albumArt = audioInfo != null ? audioInfo.getSmallCover(ApplicationMusicPlayer.applicationContext)
                : null;

        if (albumArt != null) {
            notification.contentView.setImageViewBitmap(R.id.player_album_art, albumArt);
            if (supportBigNotifications) {
                notification.bigContentView.setImageViewBitmap(R.id.player_album_art, albumArt);
            }
        } else {
            notification.contentView.setImageViewResource(R.id.player_album_art,
                    R.drawable.bg_default_album_art);
            if (supportBigNotifications) {
                notification.bigContentView.setImageViewResource(R.id.player_album_art,
                        R.drawable.bg_default_album_art);
            }
        }
        notification.contentView.setViewVisibility(R.id.player_progress_bar, View.GONE);
        notification.contentView.setViewVisibility(R.id.player_next, View.VISIBLE);
        notification.contentView.setViewVisibility(R.id.player_previous, View.VISIBLE);
        if (supportBigNotifications) {
            notification.bigContentView.setViewVisibility(R.id.player_next, View.VISIBLE);
            notification.bigContentView.setViewVisibility(R.id.player_previous, View.VISIBLE);
            notification.bigContentView.setViewVisibility(R.id.player_progress_bar, View.GONE);
        }

        if (MediaController.getInstance().isAudioPaused()) {
            notification.contentView.setViewVisibility(R.id.player_pause, View.GONE);
            notification.contentView.setViewVisibility(R.id.player_play, View.VISIBLE);
            if (supportBigNotifications) {
                notification.bigContentView.setViewVisibility(R.id.player_pause, View.GONE);
                notification.bigContentView.setViewVisibility(R.id.player_play, View.VISIBLE);
            }
        } else {
            notification.contentView.setViewVisibility(R.id.player_pause, View.VISIBLE);
            notification.contentView.setViewVisibility(R.id.player_play, View.GONE);
            if (supportBigNotifications) {
                notification.bigContentView.setViewVisibility(R.id.player_pause, View.VISIBLE);
                notification.bigContentView.setViewVisibility(R.id.player_play, View.GONE);
            }
        }

        notification.contentView.setTextViewText(R.id.player_song_name, songName);
        notification.contentView.setTextViewText(R.id.player_author_name, authorName);
        if (supportBigNotifications) {
            notification.bigContentView.setTextViewText(R.id.player_song_name, songName);
            notification.bigContentView.setTextViewText(R.id.player_author_name, authorName);
            //                notification.bigContentView.setTextViewText(R.id.player_albumname, albumName);
        }
        notification.flags |= Notification.FLAG_ONGOING_EVENT;
        startForeground(5, notification);

        if (remoteControlClient != null) {
            RemoteControlClient.MetadataEditor metadataEditor = remoteControlClient.editMetadata(true);
            metadataEditor.putString(MediaMetadataRetriever.METADATA_KEY_ARTIST, authorName);
            metadataEditor.putString(MediaMetadataRetriever.METADATA_KEY_TITLE, songName);
            if (audioInfo != null && audioInfo.getCover(ApplicationMusicPlayer.applicationContext) != null) {
                metadataEditor.putBitmap(RemoteControlClient.MetadataEditor.BITMAP_KEY_ARTWORK,
                        audioInfo.getCover(ApplicationMusicPlayer.applicationContext));
            }
            metadataEditor.apply();
            audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:in.risysnetworks.shplayer.mediacontroller.MusicPlayerService.java

@SuppressLint("NewApi")
private void createNotification(SongDetail mSongDetail) {
    try {/*ww w  .  jav a2  s  .c  om*/
        String songName = mSongDetail.getTitle();
        String authorName = mSongDetail.getArtist();
        SongDetail audioInfo = MediaController.getInstance().getPlayingSongDetail();

        RemoteViews simpleContentView = new RemoteViews(getApplicationContext().getPackageName(),
                R.layout.player_small_notification);
        RemoteViews expandedView = null;
        if (supportBigNotifications) {
            expandedView = new RemoteViews(getApplicationContext().getPackageName(),
                    R.layout.player_big_notification);
        }

        Intent intent = new Intent(ApplicationSHPlayer.applicationContext, SHPlayerMainActivity.class);
        intent.setAction("openplayer");
        intent.setFlags(32768);
        PendingIntent contentIntent = PendingIntent.getActivity(ApplicationSHPlayer.applicationContext, 0,
                intent, 0);

        Notification notification = new NotificationCompat.Builder(getApplicationContext())
                .setSmallIcon(R.drawable.player).setContentIntent(contentIntent).setContentTitle(songName)
                .build();

        if (supportBigNotifications) {
            notification.bigContentView = expandedView;
        } else {
            notification.contentView = simpleContentView;
        }

        if (supportBigNotifications) {
            setListeners(expandedView);
        } else {
            setListeners(simpleContentView);
        }

        Bitmap albumArt = audioInfo != null ? audioInfo.getSmallCover(ApplicationSHPlayer.applicationContext)
                : null;

        if (albumArt != null) {

            if (supportBigNotifications) {
                notification.bigContentView.setImageViewBitmap(R.id.player_album_art, albumArt);
            } else {
                notification.contentView.setImageViewBitmap(R.id.player_album_art, albumArt);
            }
        } else {

            if (supportBigNotifications) {
                notification.bigContentView.setImageViewResource(R.id.player_album_art,
                        R.drawable.bg_default_album_art);
            } else {
                notification.contentView.setImageViewResource(R.id.player_album_art,
                        R.drawable.bg_default_album_art);
            }
        }

        if (supportBigNotifications) {
            notification.bigContentView.setViewVisibility(R.id.player_next, View.VISIBLE);
            notification.bigContentView.setViewVisibility(R.id.player_previous, View.VISIBLE);
            notification.bigContentView.setViewVisibility(R.id.player_progress_bar, View.GONE);
        } else {
            notification.contentView.setViewVisibility(R.id.player_progress_bar, View.GONE);
            notification.contentView.setViewVisibility(R.id.player_next, View.VISIBLE);
            notification.contentView.setViewVisibility(R.id.player_previous, View.VISIBLE);
        }

        if (MediaController.getInstance().isAudioPaused()) {

            if (supportBigNotifications) {
                notification.bigContentView.setViewVisibility(R.id.player_pause, View.GONE);
                notification.bigContentView.setViewVisibility(R.id.player_play, View.VISIBLE);
            } else {
                notification.contentView.setViewVisibility(R.id.player_pause, View.GONE);
                notification.contentView.setViewVisibility(R.id.player_play, View.VISIBLE);
            }
        } else {

            if (supportBigNotifications) {
                notification.bigContentView.setViewVisibility(R.id.player_pause, View.VISIBLE);
                notification.bigContentView.setViewVisibility(R.id.player_play, View.GONE);
            } else {
                notification.contentView.setViewVisibility(R.id.player_pause, View.VISIBLE);
                notification.contentView.setViewVisibility(R.id.player_play, View.GONE);
            }
        }

        if (supportBigNotifications) {
            notification.bigContentView.setTextViewText(R.id.player_song_name, songName);
            notification.bigContentView.setTextViewText(R.id.player_author_name, authorName);
        } else {
            notification.contentView.setTextViewText(R.id.player_song_name, songName);
            notification.contentView.setTextViewText(R.id.player_author_name, authorName);
        }
        notification.flags |= Notification.FLAG_ONGOING_EVENT;
        startForeground(5, notification);

        if (remoteControlClient != null) {
            RemoteControlClient.MetadataEditor metadataEditor = remoteControlClient.editMetadata(true);
            metadataEditor.putString(MediaMetadataRetriever.METADATA_KEY_ARTIST, authorName);
            metadataEditor.putString(MediaMetadataRetriever.METADATA_KEY_TITLE, songName);
            if (audioInfo != null && audioInfo.getCover(ApplicationSHPlayer.applicationContext) != null) {
                metadataEditor.putBitmap(RemoteControlClient.MetadataEditor.BITMAP_KEY_ARTWORK,
                        audioInfo.getCover(ApplicationSHPlayer.applicationContext));
            }
            metadataEditor.apply();
            audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
        }
    } catch (Exception e) {
        e.printStackTrace();

        System.out.println(" error --> " + e.toString());
    }
}

From source file:com.xnxs.mediaplayer.widget.media.VRVideoView.java

@TargetApi(Build.VERSION_CODES.M)
private void openVideo() {
    if ((mUri == null && mIMediaDataSource == null) || mSurfaceHolder == null) {
        // not ready for playback just yet, will try again later
        return;//from   w w w  .jav  a 2 s  .c o  m
    }
    // we shouldn't clear the target state, because somebody might have
    // called start() previously
    release(false);

    AudioManager am = getAudioManager();
    am.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

    try {
        mMediaPlayer = createPlayer(Settings.PV_PLAYER__IjkMediaPlayer);
        // TODO: create SubtitleController in MediaPlayer, but we need
        // a context for the subtitle renderers
        final Context context = getContext();
        // REMOVED: SubtitleController

        // REMOVED: mAudioSession
        mMediaPlayer.setOnPreparedListener(mPreparedListener);
        mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
        mMediaPlayer.setOnCompletionListener(mCompletionListener);
        mMediaPlayer.setOnErrorListener(mErrorListener);
        mMediaPlayer.setOnInfoListener(mInfoListener);
        mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
        mCurrentBufferPercentage = 0;

        if (mUri != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                mMediaPlayer.setDataSource(mAppContext, mUri, mHeaders);
            } else {
                mMediaPlayer.setDataSource(mUri.toString());
            }
        } else {
            mMediaPlayer.setDataSource(mIMediaDataSource);
        }
        bindSurfaceHolder(mMediaPlayer, mSurfaceHolder);
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setScreenOnWhilePlaying(true);
        mMediaPlayer.prepareAsync();
        // REMOVED: mPendingSubtitleTracks

        // we don't set the target state here either, but preserve the
        // target state that was there before.
        mCurrentState = STATE_PREPARING;
        attachMediaController();
    } catch (IOException ex) {
        Log.w(TAG, "Unable to open content: " + mUri, ex);
        mCurrentState = STATE_ERROR;
        mTargetState = STATE_ERROR;
        mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
    } catch (IllegalArgumentException ex) {
        Log.w(TAG, "Unable to open content: " + mUri, ex);
        mCurrentState = STATE_ERROR;
        mTargetState = STATE_ERROR;
        mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
    } finally {
        // REMOVED: mPendingSubtitleTracks.clear();
    }
}

From source file:fm.krui.kruifm.StreamService.java

/**
 * Builds and returns a configured, unprepared MediaPlayer and attach an error handler.
 *///from  w  w w  . j av  a2s  .com
public MediaPlayer buildAudioPlayer() {

    // Build MediaPlayer
    mp = new MediaPlayer();

    try {
        mp.reset();
        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mp.setDataSource(streamUrl);
    } catch (IllegalArgumentException e) {
        Log.e(TAG, "Caught IllegalArgumentException: ");
        e.printStackTrace();
    } catch (IllegalStateException e) {
        Log.e(TAG, "Caught IllegalStateException: ");
        e.printStackTrace();
    } catch (SecurityException e) {
        Log.e(TAG, "Caught SecurityException: ");
        e.printStackTrace();
    } catch (IOException e) {
        Log.e(TAG, "Caught IOException: ");
        e.printStackTrace();
    }

    // Attach error handler to instance.
    /*mp.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            
    @Override
    public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
            
        // If there is an error in playback, stop and inform the user.
        mp = buildAudioPlayer();
        // FIXME: This should be a status bar message! Update this when that is fully implemented
        Toast.makeText(getApplicationContext(), "Failed to load the stream. Please check your internet connection and try again.", Toast.LENGTH_LONG).show();
        Log.e(TAG, "Error in playback. onError is being called.");
            
        return true;
    }
            
    });*/
    return mp;
}

From source file:com.brejza.matt.habmodem.Dsp_service.java

public void startAudio() {
    if (!_enableDecoder)
        return;/*from  w ww.  j a  v a2 s . co m*/

    boolean mic = this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_MICROPHONE);

    System.out.println("isRecording: " + isRecording);
    logEvent("Starting Audio. Mic avaliable: " + mic, false);
    if (!isRecording) {
        isRecording = true;

        buffsize = AudioRecord.getMinBufferSize(8000, AudioFormat.CHANNEL_IN_MONO,
                AudioFormat.ENCODING_PCM_16BIT);
        buffsize = Math.max(buffsize, 3000);

        mRecorder = new AudioRecord(AudioSource.MIC, 8000, AudioFormat.CHANNEL_IN_MONO,
                AudioFormat.ENCODING_PCM_16BIT, buffsize);

        mPlayer = new AudioTrack(AudioManager.STREAM_MUSIC, 8000, AudioFormat.CHANNEL_OUT_MONO,
                AudioFormat.ENCODING_PCM_16BIT, 2 * buffsize, AudioTrack.MODE_STREAM);

        if (enableEcho) {
            AudioManager manager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            manager.setMode(AudioManager.MODE_IN_CALL);
            manager.setSpeakerphoneOn(true);
        }

        if (mRecorder.getState() != AudioRecord.STATE_INITIALIZED) {

            mRecorder = new AudioRecord(AudioSource.DEFAULT, 8000, AudioFormat.CHANNEL_IN_MONO,
                    AudioFormat.ENCODING_PCM_16BIT, buffsize);

            if (mRecorder.getState() != AudioRecord.STATE_INITIALIZED) {
                logEvent("Error - Could not initialise audio", true);
                return;
            }
            logEvent("Using default audio source", false);
        }

        mRecorder.startRecording();
        System.out.println("STARTING THREAD");
        Thread ct = new captureThread();
        logEvent("Starting Audio Thread.", false);
        setDecoderRunningNotification();
        ct.start();
    }
}

From source file:com.goftagram.telegram.messenger.MusicPlayerService.java

@SuppressLint("NewApi")
private void createNotification(MessageObject messageObject) {
    String songName = messageObject.getMusicTitle();
    String authorName = messageObject.getMusicAuthor();
    AudioInfo audioInfo = MediaController.getInstance().getAudioInfo();

    RemoteViews simpleContentView = new RemoteViews(getApplicationContext().getPackageName(),
            R.layout.player_small_notification);
    RemoteViews expandedView = null;/*from  ww w.ja  va  2  s  .c o m*/
    if (supportBigNotifications) {
        expandedView = new RemoteViews(getApplicationContext().getPackageName(),
                R.layout.player_big_notification);
    }

    Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class);
    intent.setAction("com.tmessages.openplayer");
    intent.setFlags(32768);
    PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, 0);

    Notification notification = new NotificationCompat.Builder(getApplicationContext())
            .setSmallIcon(R.drawable.player).setContentIntent(contentIntent).setContentTitle(songName).build();

    notification.contentView = simpleContentView;
    if (supportBigNotifications) {
        notification.bigContentView = expandedView;
    }

    setListeners(simpleContentView);
    if (supportBigNotifications) {
        setListeners(expandedView);
    }

    Bitmap albumArt = audioInfo != null ? audioInfo.getSmallCover() : null;
    if (albumArt != null) {
        notification.contentView.setImageViewBitmap(R.id.player_album_art, albumArt);
        if (supportBigNotifications) {
            notification.bigContentView.setImageViewBitmap(R.id.player_album_art, albumArt);
        }
    } else {
        notification.contentView.setImageViewResource(R.id.player_album_art, R.drawable.nocover_small);
        if (supportBigNotifications) {
            notification.bigContentView.setImageViewResource(R.id.player_album_art, R.drawable.nocover_big);
        }
    }
    if (MediaController.getInstance().isDownloadingCurrentMessage()) {
        notification.contentView.setViewVisibility(R.id.player_pause, View.GONE);
        notification.contentView.setViewVisibility(R.id.player_play, View.GONE);
        notification.contentView.setViewVisibility(R.id.player_next, View.GONE);
        notification.contentView.setViewVisibility(R.id.player_previous, View.GONE);
        notification.contentView.setViewVisibility(R.id.player_progress_bar, View.VISIBLE);
        if (supportBigNotifications) {
            notification.bigContentView.setViewVisibility(R.id.player_pause, View.GONE);
            notification.bigContentView.setViewVisibility(R.id.player_play, View.GONE);
            notification.bigContentView.setViewVisibility(R.id.player_next, View.GONE);
            notification.bigContentView.setViewVisibility(R.id.player_previous, View.GONE);
            notification.bigContentView.setViewVisibility(R.id.player_progress_bar, View.VISIBLE);
        }
    } else {
        notification.contentView.setViewVisibility(R.id.player_progress_bar, View.GONE);
        notification.contentView.setViewVisibility(R.id.player_next, View.VISIBLE);
        notification.contentView.setViewVisibility(R.id.player_previous, View.VISIBLE);
        if (supportBigNotifications) {
            notification.bigContentView.setViewVisibility(R.id.player_next, View.VISIBLE);
            notification.bigContentView.setViewVisibility(R.id.player_previous, View.VISIBLE);
            notification.bigContentView.setViewVisibility(R.id.player_progress_bar, View.GONE);
        }

        if (MediaController.getInstance().isAudioPaused()) {
            notification.contentView.setViewVisibility(R.id.player_pause, View.GONE);
            notification.contentView.setViewVisibility(R.id.player_play, View.VISIBLE);
            if (supportBigNotifications) {
                notification.bigContentView.setViewVisibility(R.id.player_pause, View.GONE);
                notification.bigContentView.setViewVisibility(R.id.player_play, View.VISIBLE);
            }
        } else {
            notification.contentView.setViewVisibility(R.id.player_pause, View.VISIBLE);
            notification.contentView.setViewVisibility(R.id.player_play, View.GONE);
            if (supportBigNotifications) {
                notification.bigContentView.setViewVisibility(R.id.player_pause, View.VISIBLE);
                notification.bigContentView.setViewVisibility(R.id.player_play, View.GONE);
            }
        }
    }

    notification.contentView.setTextViewText(R.id.player_song_name, songName);
    notification.contentView.setTextViewText(R.id.player_author_name, authorName);
    if (supportBigNotifications) {
        notification.bigContentView.setTextViewText(R.id.player_song_name, songName);
        notification.bigContentView.setTextViewText(R.id.player_author_name, authorName);
    }
    notification.flags |= Notification.FLAG_ONGOING_EVENT;
    startForeground(5, notification);

    if (remoteControlClient != null) {
        RemoteControlClient.MetadataEditor metadataEditor = remoteControlClient.editMetadata(true);
        metadataEditor.putString(MediaMetadataRetriever.METADATA_KEY_ARTIST, authorName);
        metadataEditor.putString(MediaMetadataRetriever.METADATA_KEY_TITLE, songName);
        if (audioInfo != null && audioInfo.getCover() != null) {
            metadataEditor.putBitmap(RemoteControlClient.MetadataEditor.BITMAP_KEY_ARTWORK,
                    audioInfo.getCover());
        }
        metadataEditor.apply();
        audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    }
}

From source file:com.mantz_it.rfanalyzer.ui.activity.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    toaster = new Toaster(this);

    setContentView(R.layout.activity_main);
    this.savedInstanceState = savedInstanceState;

    // Set default Settings on first run:
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

    // Get reference to the shared preferences:
    preferences = PreferenceManager.getDefaultSharedPreferences(this); // todo: separate preferences files for different PreferenceUsers
    // Overwrite defaults for file paths in the preferences:
    String extStorage = Environment.getExternalStorageDirectory().getAbsolutePath(); // get the path to the ext. storage
    // File Source file:
    String defaultFile = getString(R.string.pref_filesource_file_default);
    if (preferences.getString(getString(R.string.pref_filesource_file), "").equals(defaultFile))
        preferences.edit().putString(getString(R.string.pref_filesource_file), extStorage + "/" + defaultFile)
                .apply();//from www .  j  a v a  2 s.  c om
    // Log file:
    defaultFile = getString(R.string.pref_logfile_default);
    if (preferences.getString(getString(R.string.pref_logfile), "").equals(defaultFile))
        preferences.edit().putString(getString(R.string.pref_logfile), extStorage + "/" + defaultFile).apply();

    // Start logging if enabled:
    if (preferences.getBoolean(getString(R.string.pref_logging), false)) {
        if (ContextCompat.checkSelfPermission(this,
                "android.permission.WRITE_EXTERNAL_STORAGE") == PackageManager.PERMISSION_GRANTED) {
            try {
                File logfile = new File(preferences.getString(getString(R.string.pref_logfile), ""));
                logfile.getParentFile().mkdir(); // Create folder
                logcat = Runtime.getRuntime().exec("logcat -f " + logfile);
                Log.i("MainActivity", "onCreate: started logcat (" + logcat.toString() + ") to " + logfile);
            } catch (Exception e) {
                Log.e("MainActivity", "onCreate: Failed to start logging!");
            }
        } else {
            preferences.edit().putBoolean(getString(R.string.pref_logging), false).apply();
            Log.i(LOGTAG, "onCreate: deactivate logging because of missing storage permission.");
        }
    }
    // Get version name:
    try {
        versionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
        Log.i(LOGTAG, "This is RF Analyzer " + versionName + " by Dennis Mantz (modified).");
    } catch (PackageManager.NameNotFoundException e) {
        Log.e(LOGTAG, "onCreate: Cannot read version name: " + e.getMessage());
    }

    // Get references to the GUI components:
    fl_analyzerFrame = (FrameLayout) findViewById(R.id.fl_analyzerFrame);

    // Create a analyzer surface:
    analyzerSurface = new AnalyzerSurface(this, this);
    analyzerSurface.init(preferences);

    // Put the analyzer surface in the analyzer frame of the layout:
    fl_analyzerFrame.addView(analyzerSurface);

    // Restore / Initialize the running state and the demodulator mode:
    if (savedInstanceState != null) {
        running = savedInstanceState.getBoolean(getString(R.string.save_state_running));
        demodulationMode = savedInstanceState.getInt(getString(R.string.save_state_demodulatorMode));

        /* BUGFIX / WORKAROUND:
         * The RTL2832U driver will not allow to close the socket and immediately start the driver
         * again to reconnect after an orientation change / app kill + restart.
         * It will report back in onActivityResult() with a -1 (not specified).
         *
         * Work-around:
         * 1) We won't restart the Analyzer if the current source is set to a local RTL-SDR instance:
         * 2) Delay the restart of the Analyzer after the driver was shut down correctly...
         */
        if (running
                && Integer.parseInt(
                        preferences.getString(getString(R.string.pref_sourceType), "1")) == RTLSDR_SOURCE
                && !preferences.getBoolean(getString(R.string.pref_rtlsdr_externalServer), false)) {
            // 1) don't start Analyzer immediately
            running = false;

            // Just inform the user about what is going on (why does this take so long? ...)
            toaster.showShort("Stopping and restarting RTL2832U driver...");

            // 2) Delayed start of the Analyzer:
            // todo: can we use notifyAll() instead of this?

            Thread timer = new Thread(() -> {
                try {
                    Thread.sleep(1500);
                    startAnalyzer();
                } catch (InterruptedException e) {
                    Log.e(LOGTAG, "onCreate: (timer thread): Interrupted while sleeping.");
                }
            }, "Timer Thread");

            timer.start();
        }

    } else {
        // Set running to true if autostart is enabled (this will start the analyzer in onStart() )
        running = preferences.getBoolean((getString(R.string.pref_autostart)), false);
    }

    // Set the hardware volume keys to work on the music audio stream:
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
}

From source file:com.andryr.musicplayer.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    setTheme();/*from  w  w w  .  jav a2s  .  c  o  m*/

    super.onCreate(savedInstanceState);

    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    setContentView(R.layout.activity_main);

    mThumbSize = getResources().getDimensionPixelSize(R.dimen.art_thumbnail_size);

    mPlaybackRequests = new PlaybackRequests();

    if (savedInstanceState == null) {
        showLibrary();
    }

    findViewById(R.id.quick_play_pause_toggle).setOnClickListener(mOnClickListener);

    findViewById(R.id.track_info).setOnClickListener(mOnClickListener);

    findViewById(R.id.quick_prev).setOnClickListener(mOnClickListener);
    findViewById(R.id.quick_next).setOnClickListener(mOnClickListener);

    mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
    mNavigationView.inflateHeaderView(R.layout.navigation_header);
    mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {
            mDrawerLayout.closeDrawers();
            switch (menuItem.getItemId()) {
            /* case R.id.action_home:
                showHome();
                break;*/
            case R.id.action_library:
                showLibrary();
                break;
            case R.id.action_favorites:
                showFavorites();
                break;
            case R.id.action_equalizer:
                NavigationUtils.showEqualizer(MainActivity.this);
                break;
            case R.id.action_settings:
                NavigationUtils.showPreferencesActivity(MainActivity.this);
                break;
            }
            return true;
        }
    });
    checkPermissions();

}