Java Code Examples for android.media.MediaPlayer#setDataSource()
The following examples show how to use
android.media.MediaPlayer#setDataSource() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BeepManager.java From moVirt with Apache License 2.0 | 7 votes |
private MediaPlayer buildMediaPlayer(Context activity) { MediaPlayer mediaPlayer = new MediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayer.setOnCompletionListener(this); mediaPlayer.setOnErrorListener(this); try { AssetFileDescriptor file = activity.getResources().openRawResourceFd(R.raw.beep); try { mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength()); } finally { file.close(); } mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME); mediaPlayer.prepare(); return mediaPlayer; } catch (IOException ioe) { Log.w(TAG, ioe); mediaPlayer.release(); return null; } }
Example 2
Source File: CutTimeActivity.java From WeiXinRecordedDemo with MIT License | 6 votes |
private void initMediaPlay(SurfaceTexture surface){ try { mMediaPlayer = new MediaPlayer(); mMediaPlayer.setDataSource(path); mMediaPlayer.setSurface(new Surface(surface)); mMediaPlayer.setLooping(true); mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mMediaPlayer.start(); } }); mMediaPlayer.prepareAsync(); }catch (Exception e){ e.printStackTrace(); } initVideoSize(); initThumbs(); }
Example 3
Source File: BeepManager.java From reacteu-app with MIT License | 6 votes |
private static MediaPlayer buildMediaPlayer(Context activity) { MediaPlayer mediaPlayer = new MediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); // When the beep has finished playing, rewind to queue up another one. mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer player) { player.seekTo(0); } }); AssetFileDescriptor file = activity.getResources().openRawResourceFd(fakeR.getId("raw", "beep")); try { mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength()); file.close(); mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME); mediaPlayer.prepare(); } catch (IOException ioe) { Log.w(TAG, ioe); mediaPlayer = null; } return mediaPlayer; }
Example 4
Source File: BeepManager.java From YZxing with Apache License 2.0 | 6 votes |
private MediaPlayer buildMediaPlayer(Context activity) { MediaPlayer mediaPlayer = new MediaPlayer(); try (AssetFileDescriptor file = activity.getResources().openRawResourceFd(R.raw.beep)) { mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength()); mediaPlayer.setOnErrorListener(this); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayer.setLooping(false); mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME); mediaPlayer.prepare(); return mediaPlayer; } catch (IOException ioe) { Log.w(TAG, ioe); mediaPlayer.release(); return null; } }
Example 5
Source File: ws_Main3Activity.java From styT with Apache License 2.0 | 6 votes |
public void Bi(String object) { final MediaPlayer mediaPlayer = new MediaPlayer(); try { mediaPlayer.setDataSource(object); mediaPlayer.prepareAsync(); mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { // 准备完成 开始播放 mediaPlayer.start(); } }); } catch (Exception e) { e.printStackTrace(); } //MediaPlayer mPlayer = MediaPlayer.create(this, object); // mPlayer.start(); }
Example 6
Source File: AlarmAlertActivity.java From SpecialAlarmClock with Apache License 2.0 | 6 votes |
private void startAlarm() { if (alarm.getAlarmTonePath() != "") { mediaPlayer = new MediaPlayer(); if (alarm.IsVibrate()) { vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); long[] pattern = {1000, 200, 200, 200}; vibrator.vibrate(pattern, 0); } try { mediaPlayer.setVolume(1.0f, 1.0f); mediaPlayer.setDataSource(this, Uri.parse(alarm.getAlarmTonePath())); mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); mediaPlayer.setLooping(true); mediaPlayer.prepare(); mediaPlayer.start(); } catch (Exception e) { mediaPlayer.release(); alarmActive = false; } } }
Example 7
Source File: PlaybackFragment.java From Android-AudioRecorder-App with Apache License 2.0 | 6 votes |
private void startPlaying() { mPlayButton.setImageResource(R.drawable.ic_media_pause); mMediaPlayer = new MediaPlayer(); try { mMediaPlayer.setDataSource(item.getFilePath()); mMediaPlayer.prepare(); mSeekBar.setMax(mMediaPlayer.getDuration()); mMediaPlayer.setOnPreparedListener(mp -> mMediaPlayer.start()); } catch (IOException e) { Log.e(LOG_TAG, "prepare() failed"); } mMediaPlayer.setOnCompletionListener(mp -> stopPlaying()); updateSeekBar(); //keep screen on while playing audio getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); }
Example 8
Source File: MediaPlayerActivity.java From KSYMediaPlayer_Android with Apache License 2.0 | 6 votes |
@Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mContext = getApplicationContext(); setContentView(R.layout.activity_media_player); mDataSource = getIntent().getStringExtra("path"); mTextureView = (TextureView) findViewById(R.id.media_player_view); mTextureView.setSurfaceTextureListener(mSurfaceTextureListener); mMediaPlayer = new MediaPlayer(); mMediaPlayer.setOnErrorListener(mOnErrorListener); mMediaPlayer.setOnPreparedListener(mOnPreparedListener); mMediaPlayer.setOnCompletionListener(mOnCompletionListener); try { mMediaPlayer.setDataSource(mDataSource); mMediaPlayer.prepareAsync(); } catch (IOException e) { e.printStackTrace(); } }
Example 9
Source File: MaskProgressLayout.java From AlbumCameraRecorder with MIT License | 5 votes |
@Override public void addAudioUrl(String audioUrl) { MediaPlayer mediaPlayer = new MediaPlayer(); try { mediaPlayer.setDataSource(audioUrl); mediaPlayer.prepare(); int duration = mediaPlayer.getDuration(); if (0 != duration) { MultiMediaView multiMediaView = new MultiMediaView(MultimediaTypes.AUDIO); multiMediaView.setUrl(audioUrl); multiMediaView.setViewHolder(this); if (this.audioList == null) { this.audioList = new ArrayList<>(); } audioList.add(multiMediaView); // 显示音频播放控件,当点击播放的时候,才正式下载并且进行播放 mViewHolder.playView.setVisibility(View.VISIBLE); isShowRemovceRecorder(); RecordingItem recordingItem = new RecordingItem(); recordingItem.setUrl(audioUrl); recordingItem.setLength(duration); mViewHolder.playView.setData(recordingItem, audioProgressColor); //记得释放资源 mediaPlayer.release(); } } catch (IOException e) { e.printStackTrace(); } }
Example 10
Source File: VideoOutputActivity.java From SimpleVideoEdit with Apache License 2.0 | 5 votes |
private void setMediaPlayer() { player = new MediaPlayer(); player.setOnCompletionListener(this); player.setOnInfoListener(this); player.setOnPreparedListener(this); try { player.setDataSource(mSVE.getAllInputClips().get(0).getClipPath()); player.prepare(); player.start(); } catch (IOException e) { } }
Example 11
Source File: MediaSnippetsActivity.java From Wrox-ProfessionalAndroid-4E with Apache License 2.0 | 5 votes |
private void listing17_1() { try { // Listing 17-1: Playback using the Media Player MediaPlayer mediaPlayer = new MediaPlayer(); mediaPlayer.setDataSource("http://site.com/audio/mydopetunes.mp3"); mediaPlayer.setOnPreparedListener(myOnPreparedListener); mediaPlayer.prepareAsync(); } catch (IOException e) { Log.e(TAG, "Playback Error.", e); } }
Example 12
Source File: AndroidMusic.java From Alite with GNU General Public License v3.0 | 5 votes |
public AndroidMusic(AssetFileDescriptor afd, Sound.SoundType soundType, String fileName) throws IOException { mediaPlayer = new MediaPlayer(); musicInfo = fileName; try { mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); mediaPlayer.prepareAsync(); mediaPlayer.setOnPreparedListener(this); mediaPlayer.setOnCompletionListener(this); this.soundType = soundType; } catch (Exception e) { AliteLog.e("Loading Music " + musicInfo + " caused an Error", e.getMessage(), e); throw new RuntimeException("Couldn't load music " + musicInfo + ".", e); } }
Example 13
Source File: AudioRecordingActivity.java From coursera-android with MIT License | 5 votes |
private void startPlaying() { mPlayer = new MediaPlayer(); try { mPlayer.setDataSource(mFileName); mPlayer.prepare(); mPlayer.start(); } catch (IOException e) { Log.e(TAG, "Couldn't prepare and start MediaPlayer"); } }
Example 14
Source File: AlarmService.java From talalarmo with MIT License | 5 votes |
private void startPlayer() { mPlayer = new MediaPlayer(); mPlayer.setOnErrorListener(mErrorListener); try { // add vibration to alarm alert if it is set if (App.getState().settings().vibrate()) { mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); mHandler.post(mVibrationRunnable); } // Player setup is here String ringtone = App.getState().settings().ringtone(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && ringtone.startsWith("content://media/external/") && checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM).toString(); } mPlayer.setDataSource(this, Uri.parse(ringtone)); mPlayer.setLooping(true); mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); mPlayer.setVolume(mVolumeLevel, mVolumeLevel); mPlayer.prepare(); mPlayer.start(); if (App.getState().settings().ramping()) { mHandler.postDelayed(mVolumeRunnable, VOLUME_INCREASE_DELAY); } else { mPlayer.setVolume(MAX_VOLUME, MAX_VOLUME); } } catch (Exception e) { if (mPlayer.isPlaying()) { mPlayer.stop(); } stopSelf(); } }
Example 15
Source File: MultiPlayer.java From MusicPlayer with GNU General Public License v3.0 | 5 votes |
/** * @param player The {@link MediaPlayer} to use * @param path The path of the file, or the http/rtsp URL of the stream * you want to play * @return True if the <code>player</code> has been prepared and is * ready to play, false otherwise */ private boolean setDataSourceImpl(@NonNull final MediaPlayer player, @NonNull final String path) { if (context == null) { return false; } try { player.reset(); player.setOnPreparedListener(null); if (path.startsWith("content://")) { player.setDataSource(context, Uri.parse(path)); } else { player.setDataSource(path); } player.setAudioStreamType(AudioManager.STREAM_MUSIC); player.prepare(); } catch (Exception e) { return false; } player.setOnCompletionListener(this); player.setOnErrorListener(this); final Intent intent = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION); intent.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, getAudioSessionId()); intent.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, context.getPackageName()); intent.putExtra(AudioEffect.EXTRA_CONTENT_TYPE, AudioEffect.CONTENT_TYPE_MUSIC); context.sendBroadcast(intent); return true; }
Example 16
Source File: MediaController.java From ankihelper with GNU General Public License v3.0 | 5 votes |
public void setUpMediaPlayer(MediaOverlays mediaOverlays, String path, String mBookTitle) { this.mediaOverlays = mediaOverlays; mediaHandler = new Handler(); try { mediaItemPosition = 0; String uri = Constants.LOCALHOST + mBookTitle + path; mediaPlayer = new MediaPlayer(); mediaPlayer.setDataSource(uri); mediaPlayer.prepare(); isMediaPlayerReady = true; } catch (IOException e) { Log.e(TAG, e.getMessage()); } }
Example 17
Source File: VoIPBaseService.java From Telegram-FOSS with GNU General Public License v2.0 | 4 votes |
protected void startRingtoneAndVibration(int chatID){ SharedPreferences prefs = MessagesController.getNotificationsSettings(currentAccount); AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE); boolean needRing=am.getRingerMode()!=AudioManager.RINGER_MODE_SILENT; /*if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP){ try{ int mode=Settings.Global.getInt(getContentResolver(), "zen_mode"); if(needRing) needRing=mode==0; }catch(Exception ignore){} }*/ if(needRing){ if(!USE_CONNECTION_SERVICE){ am.requestAudioFocus(this, AudioManager.STREAM_RING, AudioManager.AUDIOFOCUS_GAIN); } ringtonePlayer=new MediaPlayer(); ringtonePlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){ @Override public void onPrepared(MediaPlayer mediaPlayer){ ringtonePlayer.start(); } }); ringtonePlayer.setLooping(true); ringtonePlayer.setAudioStreamType(AudioManager.STREAM_RING); try{ String notificationUri; if(prefs.getBoolean("custom_"+chatID, false)) notificationUri=prefs.getString("ringtone_path_"+chatID, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE).toString()); else notificationUri=prefs.getString("CallsRingtonePath", RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE).toString()); ringtonePlayer.setDataSource(this, Uri.parse(notificationUri)); ringtonePlayer.prepareAsync(); }catch(Exception e){ FileLog.e(e); if(ringtonePlayer!=null){ ringtonePlayer.release(); ringtonePlayer=null; } } int vibrate; if(prefs.getBoolean("custom_"+chatID, false)) vibrate=prefs.getInt("calls_vibrate_"+chatID, 0); else vibrate=prefs.getInt("vibrate_calls", 0); if((vibrate!=2 && vibrate!=4 && (am.getRingerMode()==AudioManager.RINGER_MODE_VIBRATE || am.getRingerMode()==AudioManager.RINGER_MODE_NORMAL)) || (vibrate==4 && am.getRingerMode()==AudioManager.RINGER_MODE_VIBRATE)){ vibrator=(Vibrator) getSystemService(VIBRATOR_SERVICE); long duration=700; if(vibrate==1) duration/=2; else if(vibrate==3) duration*=2; vibrator.vibrate(new long[]{0, duration, 500}, 0); } } }
Example 18
Source File: VideoChatHeadService.java From VideoChatHeads with The Unlicense | 4 votes |
private void showChatHeades() { mWindowManager = (WindowManager) getSystemService(Service.WINDOW_SERVICE); mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); liChatHeads = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); if (chatHeadsView != null) { mWindowManager.removeView(chatHeadsView); mVideoSurfaceView[0] = null; } mVideoViewParams = new WindowManager.LayoutParams( WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_PHONE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, PixelFormat.TRANSLUCENT); DisplayMetrics displaymetrics = new DisplayMetrics(); mWindowManager.getDefaultDisplay().getMetrics(displaymetrics); windowHeight = displaymetrics.heightPixels; windowWidth = displaymetrics.widthPixels; mVideoViewParams.gravity = Gravity.TOP | Gravity.RIGHT; mVideoViewParams.height = Constants.VIDEO_VIEW_CIRCLE_SIZE; mVideoViewParams.width = Constants.VIDEO_VIEW_CIRCLE_SIZE; // final int radius = getResources() // .getDimensionPixelOffset(R.dimen.corner_radius_video); chatHeadsView = liChatHeads.inflate(R.layout.view_layout_chat_heads, null); mVideoSurfaceView[0] = (VideoSurfaceView) chatHeadsView.findViewById(R.id.video_surface_view); imgPlayPause = (ImageView) chatHeadsView.findViewById(R.id.img_play_pause); mVideoSurfaceView[0].setCornerRadius(Constants.VIDEO_VIEW_CORNER_RADIUS); mVideoViewParams.x = 0; mVideoViewParams.y = 50; mWindowManager.addView(chatHeadsView, mVideoViewParams); mediaPlayer = new MediaPlayer(); final VideoSurfaceView surfaceView = mVideoSurfaceView[0]; final String dataSource = "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"; try { mediaPlayer.setDataSource(dataSource); // the video view will take care of calling prepare and attaching the surface once // it becomes available mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override public void onPrepared(MediaPlayer mp) { Utils.setBackground(VideoChatHeadService.this, imgPlayPause, R.drawable.ic_play); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { imgPlayPause.setVisibility(View.GONE); isMediaPrepared = true; isPlaying = true; mediaPlayer.start(); surfaceView.setVideoAspectRatio((float) mediaPlayer.getVideoWidth() / (float) mediaPlayer.getVideoHeight()); } }, 1000); } }); surfaceView.setMediaPlayer(mediaPlayer); } catch (IOException e) { e.printStackTrace(); mediaPlayer.release(); } addViewOnTouchListener(); }
Example 19
Source File: UniversalVideoView.java From LLApp with Apache License 2.0 | 4 votes |
private void openVideo() { if (mUri == null || mSurfaceHolder == null) { // not ready for playback just yet, will try again later return; } AudioManager am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE); am.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); // we shouldn't clear the target state, because somebody might have // called start() previously release(false); try { mMediaPlayer = new MediaPlayer(); if (mAudioSession != 0) { mMediaPlayer.setAudioSessionId(mAudioSession); } else { mAudioSession = mMediaPlayer.getAudioSessionId(); } mMediaPlayer.setOnPreparedListener(mPreparedListener); mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener); mMediaPlayer.setOnCompletionListener(mCompletionListener); mMediaPlayer.setOnErrorListener(mErrorListener); mMediaPlayer.setOnInfoListener(mInfoListener); mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener); mCurrentBufferPercentage = 0; mMediaPlayer.setDataSource(mContext, mUri); mMediaPlayer.setDisplay(mSurfaceHolder); mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.setScreenOnWhilePlaying(true); mMediaPlayer.prepareAsync(); // 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); } }
Example 20
Source File: MediaUtil.java From appinventor-extensions with Apache License 2.0 | 4 votes |
/** * Loads the audio or video specified by mediaPath into the given * MediaPlayer. * * @param mediaPlayer the MediaPlayer * @param form the Form * @param mediaPath the path to the media */ public static void loadMediaPlayer(MediaPlayer mediaPlayer, Form form, String mediaPath) throws IOException { MediaSource mediaSource = determineMediaSource(form, mediaPath); switch (mediaSource) { case ASSET: AssetFileDescriptor afd = getAssetsIgnoreCaseAfd(form,mediaPath); try { FileDescriptor fd = afd.getFileDescriptor(); long offset = afd.getStartOffset(); long length = afd.getLength(); mediaPlayer.setDataSource(fd, offset, length); } finally { afd.close(); } return; case REPL_ASSET: form.assertPermission(Manifest.permission.READ_EXTERNAL_STORAGE); mediaPlayer.setDataSource(replAssetPath(mediaPath)); return; case SDCARD: form.assertPermission(Manifest.permission.READ_EXTERNAL_STORAGE); mediaPlayer.setDataSource(mediaPath); return; case FILE_URL: if (isExternalFileUrl(mediaPath)) { form.assertPermission(Manifest.permission.READ_EXTERNAL_STORAGE); } mediaPlayer.setDataSource(fileUrlToFilePath(mediaPath)); return; case URL: // This works both for streaming and non-streaming. // TODO(halabelson): Think about whether we could get improved // performance if we did buffering control. mediaPlayer.setDataSource(mediaPath); return; case CONTENT_URI: mediaPlayer.setDataSource(form, Uri.parse(mediaPath)); return; case CONTACT_URI: throw new IOException("Unable to load audio or video for contact " + mediaPath + "."); } throw new IOException("Unable to load audio or video " + mediaPath + "."); }