Example usage for android.media MediaPlayer setAudioStreamType

List of usage examples for android.media MediaPlayer setAudioStreamType

Introduction

In this page you can find the example usage for android.media MediaPlayer setAudioStreamType.

Prototype

public void setAudioStreamType(int streamtype) 

Source Link

Document

Sets the audio stream type for this MediaPlayer.

Usage

From source file:com.mattprecious.prioritysms.receiver.AlarmReceiver.java

private void doNotify(Context context, BaseProfile profile) {
    AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    MediaPlayer mediaPlayer = new MediaPlayer();

    try {/*from   w w w .  ja  v a  2s . c o m*/
        if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL || profile.isOverrideSilent()) {
            mediaPlayer.setWakeMode(context, PowerManager.PARTIAL_WAKE_LOCK);
            mediaPlayer.setAudioStreamType(
                    profile.isOverrideSilent() ? AudioManager.STREAM_ALARM : AudioManager.STREAM_NOTIFICATION);
            mediaPlayer.setDataSource(context, profile.getRingtone());
            mediaPlayer.prepare();
            mediaPlayer.start();

            if (profile.isVibrate()) {
                Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
                vibrator.vibrate(VIBRATE_PATTERN, -1);
            }
        }
    } catch (IllegalArgumentException e) {
        Log.e(TAG, "failed to play audio", e);
    } catch (IOException e) {
        Log.e(TAG, "failed to play audio", e);
    }
}

From source file:org.kontalk.ui.AudioDialog.java

void playAudio() {
    mProgressBar.setClickable(true);//ww w  .  j  a v  a  2 s .  c  o  m
    try {
        MediaPlayer player = mData.getPlayer();
        player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        player.setDataSource(mFile.getAbsolutePath());
        player.prepare();
    } catch (IOException e) {
        Log.e(TAG, "error reading from external storage", e);
        new MaterialDialog.Builder(getContext()).content(R.string.err_playing_sdcard)
                .positiveText(android.R.string.ok).show();
    } catch (Exception e) {
        Log.e(TAG, "error playing audio", e);
    }
    setupForPlaying();
    animate(mProgressBar, null, 0, MAX_PROGRESS, mData.getPlayer().getDuration());
    resumeAudio();
}

From source file:org.schabi.terminightor.NightKillerService.java

private MediaPlayer setupNewMediaPlayer(Alarm alarm) {
    MediaPlayer mediaPlayer = null;
    try {/*from   ww w .j a  va  2  s.com*/
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setDataSource(this, Uri.parse(alarm.getAlarmTone()));
        boolean overrideVolume = PreferenceManager.getDefaultSharedPreferences(this)
                .getBoolean(getString(R.string.overrideAlarmVolume), false);
        if (overrideVolume) {
            mediaPlayer.setVolume(1.0f, 1.0f);
        }
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
        mediaPlayer.setLooping(true);
        mediaPlayer.prepare();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return mediaPlayer;
}

From source file:org.FrancoisDescamps.CatPlayer.MusicService.java

public void playMusic(final String pathToMusic) {
    //register receiver
    IntentFilter receiverFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
    HeadphonesUnplugReceiver receiver = new HeadphonesUnplugReceiver();
    registerReceiver(receiver, receiverFilter);

    if (mp != null) {
        mp.stop();/*from  w w  w  .ja  va  2 s.com*/
        mp = null;
    }

    try {
        mp = new MediaPlayer();
        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mp.setDataSource(pathToMusic);
        mp.prepare();
        mp.start();
    } catch (Exception e) {
        /*NOP*/
    }

    mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            switch (repeat) {
            case 0: // Lecture en boucle dsactive
                /* NOP */
                break;
            case 1: // Lecture en boucle d'une seule musique
                playMusic(pathToMusic);
                break;
            case 2: // Lecture en boucle de toutes les musiques
                if (positionOfInitialMusic + cpt + 1 == queu.size()) {
                    cpt = 0;
                    positionOfInitialMusic = 0;
                } else {
                    cpt++;
                }
                playMusic(queu.get(positionOfInitialMusic + cpt).getPath());
                break;
            }

            currentTitle = properties[0][positionOfInitialMusic + cpt];
            currentAlbum = properties[1][positionOfInitialMusic + cpt];
            currentArtist = properties[2][positionOfInitialMusic + cpt];
            currentPath = properties[3][positionOfInitialMusic + cpt];

            musicAsChanged = true;
            MainActivity.notifyOtherMusicStarted();
            buildNotification(true);

            //save "cpt"
            editor = preferences.edit();
            editor.putInt("cpt", cpt);

            if (Build.VERSION.SDK_INT < 9) {
                editor.commit();
            } else {
                editor.apply();
            }
        }
    });
}

From source file:it.interfree.leonardoce.bootreceiver.AlarmKlaxon.java

private void startAlarm(MediaPlayer player)
        throws java.io.IOException, IllegalArgumentException, IllegalStateException {
    final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    // Non deve suonare se il cellulare e' silenzioso
    Log.v(LTAG, "Stato del telefono: " + audioManager.getRingerMode());

    // do not play alarms if stream volume is 0
    // (typically because ringer mode is silent).
    if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0
            && audioManager.getRingerMode() != AudioManager.RINGER_MODE_SILENT
            && audioManager.getRingerMode() != AudioManager.RINGER_MODE_VIBRATE) {
        player.setAudioStreamType(AudioManager.STREAM_ALARM);
        player.setLooping(true);//from   ww  w  .ja v a  2  s.c om
        player.prepare();
        player.start();
    }
}

From source file:com.yohpapa.research.simplemusicplayer.PlaybackService.java

private MediaPlayer initializePlayer() {
    MediaPlayer player = new MediaPlayer();
    player.setAudioStreamType(AudioManager.STREAM_MUSIC);
    player.setOnPreparedListener(this);
    player.setOnCompletionListener(this);
    player.setOnErrorListener(this);
    player.setOnSeekCompleteListener(this);
    player.setWakeMode(this, PowerManager.PARTIAL_WAKE_LOCK);

    IntentFilter filter = new IntentFilter();
    filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    filter.addAction(Intent.ACTION_HEADSET_PLUG);
    filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
    filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
    registerReceiver(audioOutputChangedEventReceiver, filter);

    return player;
}

From source file:brama.com.hearthum.waveform.WaveformFragment.java

protected void loadFromFile() {
    mFile = new File(mFilename);
    mLoadingLastUpdateTime = System.currentTimeMillis();
    mLoadingKeepGoing = true;//  w  w w.j  a v a2s. c  om
    mProgressDialog = new ProgressDialog(getActivity());
    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mProgressDialog.setTitle(R.string.progress_dialog_loading);
    mProgressDialog.setCancelable(true);
    mProgressDialog.setOnCancelListener((DialogInterface dialog) -> mLoadingKeepGoing = false);
    mProgressDialog.show();

    final CheapSoundFile.ProgressListener listener = (double fractionComplete) -> {
        long now = System.currentTimeMillis();
        if (now - mLoadingLastUpdateTime > 100) {
            mProgressDialog.setProgress((int) (mProgressDialog.getMax() * fractionComplete));
            mLoadingLastUpdateTime = now;
        }
        return mLoadingKeepGoing;
    };

    // Create the MediaPlayer in a background thread
    new Thread() {
        public void run() {
            try {
                MediaPlayer player = new MediaPlayer();
                player.setDataSource(mFile.getAbsolutePath());
                player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                player.prepare();
                mPlayer = player;
            } catch (final java.io.IOException e) {
                Log.e(TAG, "Error while creating media player", e);
            }
        }
    }.start();

    // Load the sound file in a background thread
    new Thread() {
        public void run() {
            try {
                mSoundFile = CheapSoundFile.create(mFile.getAbsolutePath(), listener);
            } catch (final Exception e) {
                Log.e(TAG, "Error while loading sound file", e);
                mProgressDialog.dismiss();
                mInfo.setText(e.toString());
                return;
            }
            if (mLoadingKeepGoing) {
                mHandler.post(() -> finishOpeningSoundFile());
            }
        }
    }.start();
}

From source file:com.soubw.other.WaveformFragment.java

protected void loadFromFile() {
    mFile = new File(mFilename);
    mLoadingLastUpdateTime = System.currentTimeMillis();
    mLoadingKeepGoing = true;//from w ww.  j  a  v a  2 s  .  c o  m
    mProgressDialog = new ProgressDialog(getActivity());
    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mProgressDialog.setTitle(R.string.progress_dialog_loading);
    mProgressDialog.setCancelable(true);
    mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            mLoadingKeepGoing = false;
        }
    });
    mProgressDialog.show();

    final CheapSoundFile.ProgressListener listener = new CheapSoundFile.ProgressListener() {
        @Override
        public boolean reportProgress(double fractionComplete) {
            long now = System.currentTimeMillis();
            if (now - mLoadingLastUpdateTime > 100) {
                mProgressDialog.setProgress((int) (mProgressDialog.getMax() * fractionComplete));
                mLoadingLastUpdateTime = now;
            }
            return mLoadingKeepGoing;
        }
    };

    // Create the MediaPlayer in a background thread
    new Thread() {
        public void run() {
            try {
                MediaPlayer player = new MediaPlayer();
                player.setDataSource(mFile.getAbsolutePath());
                player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                player.prepare();
                mPlayer = player;
            } catch (final java.io.IOException e) {
                Log.e(TAG, "Error while creating media player", e);
            }
        }
    }.start();

    // Load the sound file in a background thread
    new Thread() {
        public void run() {
            try {
                mSoundFile = CheapSoundFile.create(mFile.getAbsolutePath(), listener);
            } catch (final Exception e) {
                Log.e(TAG, "Error while loading sound file", e);
                mProgressDialog.dismiss();
                mInfo.setText(e.toString());
                return;
            }
            if (mLoadingKeepGoing) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        finishOpeningSoundFile();
                    }
                });
            }
        }
    }.start();
}

From source file:com.orange.essentials.otb.ui.OtbTermsFragment.java

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
        @Nullable Bundle savedInstanceState) {
    mView = inflater.inflate(R.layout.otb_terms, container, false);
    LinearLayout llayout = (LinearLayout) mView.findViewById(R.id.otb_terms_layout);
    TextView headerTv = (TextView) llayout.findViewById(R.id.otb_header_tv_text);
    headerTv.setText(R.string.otb_home_terms_content);
    List<Term> terms = TrustBadgeManager.INSTANCE.getTerms();

    for (Term term : terms) {
        View layoutToAdd = null;/* ww w . j av a  2  s  .com*/
        if (term.getTermType() == TermType.VIDEO
                && Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD_MR1) {
            layoutToAdd = View.inflate(getActivity(), R.layout.otb_terms_video, null);
            TextView titleTv = (TextView) layoutToAdd.findViewById(R.id.otb_term_video_title);
            final AutoResizingFrameLayout anchorView = (AutoResizingFrameLayout) layoutToAdd
                    .findViewById(R.id.videoSurfaceContainer);
            if (mVideoViews == null) {
                mVideoViews = new ArrayList<>();
            }
            mVideoViews.add(anchorView);
            SurfaceView videoSurface = (SurfaceView) layoutToAdd.findViewById(R.id.videoSurface);

            titleTv.setText(term.getTitleId());

            SurfaceHolder videoHolder = videoSurface.getHolder();
            MediaPlayer player = new MediaPlayer();
            if (mPlayers == null) {
                mPlayers = new ArrayList<>();
            }
            mPlayers.add(player);
            final VideoControllerView controller = new VideoControllerView(getContext());
            VideoCallback videoCallback = new VideoCallback(player, controller, anchorView);
            videoHolder.addCallback(videoCallback);
            anchorView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    controller.show();
                    return false;
                }
            });
            try {
                player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                player.setDataSource(getContext(), Uri.parse(getString(term.getContentId())));
                player.setOnPreparedListener(videoCallback);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (term.getTermType() == TermType.TEXT) {//TermType.TEXT
            layoutToAdd = View.inflate(getActivity(), R.layout.otb_terms_text, null);
            TextView titleTv = (TextView) layoutToAdd.findViewById(R.id.otb_term_text_title);
            TextView contentTv = (TextView) layoutToAdd.findViewById(R.id.otb_term_text_content);
            titleTv.setText(term.getTitleId());
            contentTv.setText(Html.fromHtml(getString(term.getContentId())));
            contentTv.setMovementMethod(LinkMovementMethod.getInstance());
            contentTv.setLinkTextColor(getResources().getColor(R.color.colorAccent));
        }
        if (null != layoutToAdd) {
            llayout.addView(layoutToAdd);
        }
        if (terms.indexOf(term) != terms.size() - 1) {
            View.inflate(getActivity(), R.layout.otb_separator, llayout);
        }
    }

    return mView;
}

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

public static boolean validateUrl(String url) {

    if (!URLUtil.isHttpUrl(url) && !URLUtil.isHttpsUrl(url)) {
        //if (LOCAL_LOGV) log("not a valid http or https url", "v");
        return false;
    }/* ww w .  j  a  v  a 2s . c  o  m*/
    //check for empty after prefix
    if (url.equals("http://") || url.equals("https://")) {
        return false;
    }

    MediaPlayer mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    try {
        mediaPlayer.setDataSource(url);
        mediaPlayer.release();
    } catch (IOException e) {
        return false;
    }
    return true;
}