@Override public int onStartCommand(Intent intent, int flags, int startId) { if (mPlayer == null) { mPlayer = new MediaPlayer(); mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mPlayer.setOnPreparedListener(this); mPlayer.setOnCompletionListener(this); mPlayer.setOnSeekCompleteListener(this); try { mSong = pickNextSong(); mPlayer.setDataSource(this, Uri.parse(mSongResource[mSong])); } catch (IOException e) { e.printStackTrace(); mPlayer.release(); mPlayer = null; } } if (mPlayer != null && !mIsPrepared) { mPlayer.prepareAsync(); mPlayWhenPrepared = true; } return START_STICKY; }
/** * set date source * * @param path */ public void setDataSource(String path) throws IOException, IllegalArgumentException, IllegalStateException { if (mPlayStatus != VideoConst.PLAY_STATUS_END) { MmpTool.LOG_ERROR("Video is playing,can't set setDataSource"); sendMsg(VideoConst.MSG_IS_PLAYING); } isEnd = false; try { mmediaplayer.setDataSource(path); } catch (IOException e) { e.printStackTrace(); throw new IOException(); } catch (IllegalArgumentException e) { e.printStackTrace(); throw new IllegalArgumentException(e); } catch (IllegalStateException e) { e.printStackTrace(); throw new IllegalStateException(e); } mPlayStatus = VideoConst.PLAY_STATUS_INITED; MmpTool.LOG_DBG("setDataSource finish!"); }
protected long getDuration(String file) { long duration = -2; if (!isPlaying & !isStreaming(file)) { try { mPlayer = new MediaPlayer(); mPlayer.setDataSource("/sdcard/" + file); mPlayer.prepare(); duration = mPlayer.getDuration(); mPlayer.release(); } catch (Exception e) { e.printStackTrace(); return (-3); } } else if (isPlaying & !isStreaming(file)) { duration = mPlayer.getDuration(); } else if (isPlaying & isStreaming(file)) { try { duration = mPlayer.getDuration(); } catch (Exception e) { e.printStackTrace(); return (-4); } } else { return -1; } return duration; }
/** * create mediaplayer for music * * @param pPath the pPath relative to assets * @return */ private MediaPlayer createMediaplayer(final String path) { MediaPlayer mediaPlayer = new MediaPlayer(); try { if (CocosPlayClient.isEnabled() && !CocosPlayClient.isDemo()) { CocosPlayClient.updateAssets(path); } CocosPlayClient.notifyFileLoaded(path); if (path.startsWith("/")) { final FileInputStream fis = new FileInputStream(path); mediaPlayer.setDataSource(fis.getFD()); fis.close(); } else { final AssetFileDescriptor assetFileDescritor = this.mContext.getAssets().openFd(path); mediaPlayer.setDataSource( assetFileDescritor.getFileDescriptor(), assetFileDescritor.getStartOffset(), assetFileDescritor.getLength()); } mediaPlayer.prepare(); mediaPlayer.setVolume(this.mLeftVolume, this.mRightVolume); } catch (final Exception e) { mediaPlayer = null; Log.e(Cocos2dxMusic.TAG, "error: " + e.getMessage(), e); } return mediaPlayer; }
public void turnOnRadio(String station) { if (mp != null) { mp.stop(); mp.release(); } Logger.d("clock", "turnOnRadio"); try { Logger.d(TAG, "try"); mp = new MediaPlayer(); mp.setScreenOnWhilePlaying(true); mp.setAudioStreamType(AudioManager.STREAM_MUSIC); Logger.d(TAG, "Station---------------------" + station); try { mp.setDataSource(station); } catch (Exception e) { Logger.d(TAG, "default radio"); try { mp.setDataSource(Radiostations.stations.get("DLF")); } catch (Exception ex) { Logger.d(TAG, "f**k this"); } } mp.setVolume(0.99f, 0.99f); mp.setOnCompletionListener(this); mp.setOnPreparedListener(this); mp.prepareAsync(); } catch (Exception ee) { Logger.e("Error", "No Stream"); } }
public void myPlay(String url, String src) { if (url == null || url.length() == 0) { Toast.makeText(mContext, "无播放地址", Toast.LENGTH_SHORT).show(); return; } if (!mLoading.isShowing()) mLoading.show(); mPlayPath = url; Logger.LOGD(TAG, "begin to play:" + mPlayPath + ", " + src); if (mPlayer == null) { Logger.LOGD(TAG, "mPlayer is null!!"); initPlayer(); } try { Logger.LOGD(TAG, "-=-=-=-=-=-= -=-=-reset-=--= -=-==-"); mPlayer.reset(); // mPlayer.stop(); Logger.LOGD("mUaMap.size= " + mUaMap.size() + ", value: " + mUaMap.get(src)); Map<String, String> headers = new HashMap<String, String>(); if (mUaMap.get(src) != null) { Logger.LOGD("=== had headers ===="); String headinfo = mUaMap.get(src); String[] grp = headinfo.split("\\$\\$"); if (grp != null) { for (String items : grp) { String[] item = items.split("\\:"); if (item != null && item.length == 2) { Logger.LOGD("Add header: " + item[0] + "=" + item[1]); headers.put(item[0], item[1]); } } } } if (headers.size() > 0) { Logger.LOGD("use header"); mPlayer.setDataSource(Player.this, Uri.parse(url), headers); } else { Logger.LOGD("use no-header"); mPlayer.setDataSource(url); } mPlayer.prepareAsync(); } catch (IllegalArgumentException e) { e.printStackTrace(); Logger.LOGD(TAG, e.toString()); } catch (IllegalStateException e) { e.printStackTrace(); Logger.LOGD(TAG, e.toString()); } catch (IOException e) { e.printStackTrace(); Logger.LOGD(TAG, e.toString()); } }
public synchronized long BackgroundMusicCreateFromFile(String fileName, int[] error) { if (fileName.equals("")) { error[0] = GAUDIO_CANNOT_OPEN_FILE; return 0; } AssetFileDescriptor fd = null; if (fileName.startsWith("/")) { File file = new File(fileName); if (!file.isFile()) { error[0] = GAUDIO_CANNOT_OPEN_FILE; return 0; } } else { if (patchFile_ != null) fd = patchFile_.getAssetFileDescriptor(fileName); if (fd == null && mainFile_ != null) fd = mainFile_.getAssetFileDescriptor(fileName); if (fd == null) try { fd = WeakActivityHolder.get().getAssets().openFd("assets/" + fileName); } catch (IOException e) { } if (fd == null) { error[0] = GAUDIO_CANNOT_OPEN_FILE; return 0; } } MediaPlayer player = new MediaPlayer(); int duration = 0; try { if (fd != null) { player.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength()); fd.close(); } else { player.setDataSource(fileName); } player.prepare(); duration = player.getDuration(); player.release(); player = null; } catch (Exception e) { error[0] = GAUDIO_UNRECOGNIZED_FORMAT; return 0; } long gid = nextgid(); sounds_.put(gid, new Sound(fileName, duration)); return gid; }
public synchronized long BackgroundMusicPlay(long backgroundMusic, boolean paused, long data) { Sound sound2 = sounds_.get(backgroundMusic); if (sound2 == null) return 0; String fileName = sound2.fileName; AssetFileDescriptor fd = null; if (fileName.startsWith("/")) { File file = new File(fileName); if (!file.isFile()) return 0; } else { if (patchFile_ != null) fd = patchFile_.getAssetFileDescriptor(fileName); if (fd == null && mainFile_ != null) fd = mainFile_.getAssetFileDescriptor(fileName); if (fd == null) try { fd = WeakActivityHolder.get().getAssets().openFd("assets/" + fileName); } catch (IOException e) { } if (fd == null) return 0; } MediaPlayer player = new MediaPlayer(); try { if (fd != null) { player.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength()); fd.close(); } else { player.setDataSource(fileName); } player.prepare(); } catch (Exception e) { return 0; } long gid = nextgid(); player.setOnCompletionListener(new OnCompletionListener(this, gid)); Channel channel = new Channel(gid, player, sound2, data); sound2.channels.add(channel); channels_.put(gid, channel); channel.paused = paused; if (!paused) channel.player.start(); return gid; }
protected void initialize() throws IOException { try { mp = new MediaPlayer(); String url = TiConvert.toString(proxy.getProperty(TiC.PROPERTY_URL)); if (URLUtil.isAssetUrl(url)) { Context context = proxy.getTiContext().getTiApp(); String path = url.substring(TiConvert.ASSET_URL.length()); AssetFileDescriptor afd = null; try { afd = context.getAssets().openFd(path); // Why mp.setDataSource(afd) doesn't work is a problem for another day. // http://groups.google.com/group/android-developers/browse_thread/thread/225c4c150be92416 mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); } catch (IOException e) { Log.e(LCAT, "Error setting file descriptor: ", e); } finally { if (afd != null) { afd.close(); } } } else { Uri uri = Uri.parse(url); if (uri.getScheme().equals(TiC.PROPERTY_FILE)) { mp.setDataSource(uri.getPath()); } else { remote = true; mp.setDataSource(url); } } mp.setLooping(looping); mp.setOnCompletionListener(this); mp.setOnErrorListener(this); mp.setOnInfoListener(this); mp.setOnBufferingUpdateListener(this); mp.prepare(); // Probably need to allow for Async setState(STATE_INITIALIZED); setVolume(volume); if (proxy.hasProperty(TiC.PROPERTY_TIME)) { setTime(TiConvert.toInt(proxy.getProperty(TiC.PROPERTY_TIME))); } } catch (Throwable t) { Log.w(LCAT, "Issue while initializing : ", t); release(); setState(STATE_STOPPED); } }
/** * Starts playing the next song. If manualUrl is null, the next song will be randomly selected * from our Media Retriever (that is, it will be a random song in the user's device). If manualUrl * is non-null, then it specifies the URL or path to the song that will be played next. */ void playNextSong(String manualUrl) { mState = State.Stopped; relaxResources(false); // release everything except MediaPlayer try { if (manualUrl != null) { // set the source of the media player to a manual URL or path createMediaPlayerIfNeeded(); mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mPlayer.setDataSource(manualUrl); mSongTitle = manualUrl; mIsStreaming = manualUrl.startsWith("http:") || manualUrl.startsWith("https:"); } else { mIsStreaming = false; // playing a locally available song MusicRetriever.Item item = mRetriever.getRandomItem(); if (item == null) { say("No song to play :-("); return; } // set the source of the media player a a content URI createMediaPlayerIfNeeded(); mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mPlayer.setDataSource(getApplicationContext(), item.getURI()); mSongTitle = item.getTitle(); } mState = State.Preparing; setUpAsForeground(mSongTitle + " (loading)"); // 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("MusicService", "IOException playing next song: " + ex.getMessage()); ex.printStackTrace(); } }
public void gotoPrevTrack() { Log.i(TAG, "REWIND MUSIC"); if (mPlayer != null && !mLastSong.isEmpty()) { mPlayer.stop(); mIsPrepared = false; // set the mSong to the last song added in the [] mSong = mLastSong.get(mLastSong.size() - 1); // remove the last index from the [] mLastSong.remove(mLastSong.size() - 1); try { // rest the player back to an idle state mPlayer.reset(); // reset the datasource to the mSong that was updated mPlayer.setDataSource(this, Uri.parse(mSongResource[mSong])); } catch (IOException e) { e.printStackTrace(); } mPlayer.prepareAsync(); mPlayWhenPrepared = true; } else { // if the player is null or the array is empty Toast.makeText(this, "No Previous Track Available", Toast.LENGTH_SHORT).show(); } }
public static void Setup() { String musicDir = Environment.getExternalStorageDirectory().getAbsolutePath() + MUSIC_DIR; mediaPlayer = new MediaPlayer(); try { mediaPlayer.setDataSource(musicDir); mediaPlayer.prepare(); mediaPlayer.setLooping(true); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private void setDataSource(String url) { this.sourceUrl = url; try { mediaPlayer = new MediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayer.setDataSource(url); mediaPlayer.setOnPreparedListener( new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mediaPlayer) { isPrepared = true; mediaPlayer.start(); if (listener != null) { listener.onPrepared(mediaPlayer); } } }); mediaPlayer.prepareAsync(); } catch (IOException e) { e.printStackTrace(); isPrepared = false; } }
@Override public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) { Surface s = new Surface(surfaceTexture); try { mMediaPlayer = new MediaPlayer(); mMediaPlayer.setDataSource(mContext, mVideoUri); mMediaPlayer.setSurface(s); mMediaPlayer.prepare(); mMediaPlayer.setOnBufferingUpdateListener(this); mMediaPlayer.setOnCompletionListener(this); mMediaPlayer.setOnPreparedListener(this); mMediaPlayer.setOnVideoSizeChangedListener(this); mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.seekTo(0); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } /* if ( mMediaPlayer != null ) { mSeekBar.setProgress( 0 ); mSeekBar.setMax( mMediaPlayer.getDuration() ); mVideoTextureView.SetVideoSize( mMediaPlayer.getVideoWidth(), mMediaPlayer.getVideoHeight() ); } */ }
/** * 播放 * * @param position */ private void start(int position) { this.currentPosition = position; isError = false; String url = null; if (getUrlList() != null && getUrlList().size() > 0) { url = getUrlList().get(position); } if (getInfoList() != null && getInfoList().size() > 0) { currentInfo.setText(getInfoList().get(position)); } if (mPlayer != null && url != null) { try { mPlayer.setDataSource(url); mSurface.requestLayout(); requestLayout(); mPlayer.prepareAsync(); isPrepare = true; showFlow(); } catch (IllegalArgumentException | IOException | IllegalStateException | SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
@Override protected Boolean doInBackground(String... params) { Boolean prepared; try { mediaPlayer.setDataSource(params[0]); mediaPlayer.prepare(); prepared = true; } catch (IllegalArgumentException e) { // TODO Auto-generated catch block Log.d("IllegarArgument", e.getMessage()); prepared = false; e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block prepared = false; e.printStackTrace(); } catch (IllegalStateException e) { // TODO Auto-generated catch block prepared = false; e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block prepared = false; e.printStackTrace(); } return prepared; }
public void playSong(final ViewHolder holder, String name) { if (isPlaying == false) { try { String path = name; gus.setDataSource(root + "/" + path); gus.setOnCompletionListener( new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { holder.myImageButton.setBackgroundResource(R.drawable.play); isPlaying = false; } }); gus.prepare(); gus.start(); Log.d("is playing", "true"); isPlaying = true; holder.myImageButton.setBackgroundResource(R.drawable.pausebtn); } catch (Exception e) { e.printStackTrace(); } } else { gus.pause(); gus.reset(); isPlaying = false; holder.myImageButton.setBackgroundResource(R.drawable.play); } }
private void tryToRestoreLocation() { try { if (location == null) { return; } boolean found = false; for (int i = 0; i < metaHolder.getSize(); i++) { if (metaHolder.get(i).getTitle().equals(location.title)) { currentPodcastInPlayer = i; found = true; break; } } if (!found) { location = null; return; } mediaPlayer.reset(); mediaPlayer.setDataSource(currentFile().toString()); mediaPlayer.prepare(); mediaPlayer.seekTo(currentMeta().getCurrentPos()); mediaMode = MediaMode.Paused; } catch (Throwable e) { // bummer. } }
public int onStartCommand(Intent intent, int flags, int startId) { if (intent != null) { String url = intent.getStringExtra("previewUrl"); handler.removeCallbacks(sendSeekUpdate); handler.postDelayed(sendSeekUpdate, 1000); try { mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.setDataSource(url); mMediaPlayer.setOnPreparedListener( new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mediaPlayer) { sendMaxPos(); if (startPlaying) mMediaPlayer.start(); } }); mMediaPlayer.prepareAsync(); } catch (IOException e) { Log.w("IO Exception: ", e.toString()); } } return START_STICKY; }
/** * Plays the given sound, sets playAllListener if available on media player to start next sound */ public static void playSound(String soundPath, OnCompletionListener playAllListener) { Log.i( AnkiDroidApp.TAG, "Playing " + soundPath + " has listener? " + Boolean.toString(playAllListener != null)); if (soundPath.substring(0, 3).equals("tts")) { // TODO: give information about did // ReadText.textToSpeech(soundPath.substring(4, soundPath.length()), // Integer.parseInt(soundPath.substring(3, 4))); } else { if (sMediaPlayer == null) sMediaPlayer = new MediaPlayer(); else sMediaPlayer.reset(); try { // soundPath is usually an URI, but Media player requires a path not url encoded URI soundURI = new URI(soundPath); soundPath = new File(soundURI).getAbsolutePath(); sMediaPlayer.setDataSource(soundPath); sMediaPlayer.setVolume(AudioManager.STREAM_MUSIC, AudioManager.STREAM_MUSIC); sMediaPlayer.prepare(); if (playAllListener != null) sMediaPlayer.setOnCompletionListener(playAllListener); sMediaPlayer.start(); } catch (Exception e) { Log.e( AnkiDroidApp.TAG, "playSounds - Error reproducing sound " + soundPath + " = " + e.getMessage()); releaseSound(); } } }
private void playMusic(String musicPath) { mp = new MediaPlayer(); try { mp.setDataSource(RhoFileApi.openFd(musicPath)); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { mp.prepare(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } mp.start(); try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } mp.stop(); clearMediaPlayerResources(); }
private void playVideo() { doCleanUp(); try { /* * Set path variable to progressive streamable mp4 or 3gpp * format URL. Http protocol should be used. Mediaplayer can only * play "progressive streamable contents" which basically means: 1. * the movie atom has to precede all the media data atoms. 2. The * clip has to be reasonably interleaved. */ path = "http://www.androidbook.com/akc/filestorage/android/documentfiles/3389/movie.mp4"; // path = "http://forum.ea3w.com/coll_ea3w/attach/2008_10/12237832415.3gp"; // Create a new media player and set the listeners mMediaPlayer = new MediaPlayer(); mMediaPlayer.setDataSource(path); mMediaPlayer.setDisplay(holder); mMediaPlayer.prepare(); mMediaPlayer.setOnBufferingUpdateListener(this); mMediaPlayer.setOnCompletionListener(this); mMediaPlayer.setOnPreparedListener(this); mMediaPlayer.setOnVideoSizeChangedListener(this); mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); } catch (Exception e) { Log.e(TAG, "error: " + e.getMessage(), e); } }
public void isSong(Context context, String type) { Uri ringToneUri = null; if (type.equals("mb_normal")) { System.out.println("isnew==============="); ringToneUri = Uri.parse("android.resource://com.citi.mc/" + R.raw.msg); } else if (type.equals("mobile_online")) { System.out.println("isonline======================="); ringToneUri = Uri.parse("android.resource://com.citi.mc/" + R.raw.online); } if (type.equals("mb_system")) { System.out.println("isnew==============="); ringToneUri = Uri.parse("android.resource://com.citi.mc/" + R.raw.system); } try { sPhelper = new SPhelper(context); MediaPlayer mediaPlayer = new MediaPlayer(); mediaPlayer.setDataSource(context, ringToneUri); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayer.setOnPreparedListener(new MediaLIstener()); mediaPlayer.prepareAsync(); } catch (Exception e) { e.printStackTrace(); } }
public MPlayer(Context context, MediaPlayer mmediaPlayer, String url) { this.context = context; mediaPlayer = mmediaPlayer; // progress = new ProgressDialog(context); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); try { mediaPlayer.setDataSource(url); mediaPlayer.prepareAsync(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } mediaPlayer.setOnPreparedListener(this); }
void setSelected(Cursor c) { Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; long newId = mCursor.getLong(mCursor.getColumnIndex(MediaStore.Audio.Media._ID)); mSelectedUri = ContentUris.withAppendedId(uri, newId); mSelectedId = newId; if (newId != mPlayingId || mMediaPlayer == null) { stopMediaPlayer(); mMediaPlayer = new MediaPlayer(); try { mMediaPlayer.setDataSource(this, mSelectedUri); mMediaPlayer.setOnCompletionListener(this); mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.prepare(); mMediaPlayer.start(); mPlayingId = newId; } catch (IOException e) { MusicLogUtils.e(TAG, "Unable to play track", e); /// M: finally just get invalidate list view @{ } finally { getListView().invalidateViews(); } /// @} } else if (mMediaPlayer != null) { stopMediaPlayer(); getListView().invalidateViews(); } }
public void startPlayback(float percentage) { if (state() == PLAYING_PAUSED_STATE) { mSampleStart = System.currentTimeMillis() - mPlayer.getCurrentPosition(); mPlayer.seekTo((int) (percentage * mPlayer.getDuration())); mPlayer.start(); setState(PLAYING_STATE); } else { stop(); mPlayer = new MediaPlayer(); try { mPlayer.setDataSource(mSampleFile.getAbsolutePath()); mPlayer.setOnCompletionListener(this); mPlayer.setOnErrorListener(this); mPlayer.prepare(); mPlayer.seekTo((int) (percentage * mPlayer.getDuration())); mPlayer.start(); } catch (IllegalArgumentException e) { setError(INTERNAL_ERROR); mPlayer = null; return; } catch (IOException e) { setError(STORAGE_ACCESS_ERROR); mPlayer = null; return; } mSampleStart = System.currentTimeMillis(); setState(PLAYING_STATE); } }
public void prepare() throws IOException { if (mVideoResources.size() <= 0) return; VideoResource first = mVideoResources.get(0); mTagsContainer.setVideoTags(first.getVideoTags()); mActiveMediaPlayer.setDataSource(getContext(), first.getVideoUri()); mActiveMediaPlayer.prepare(); }
@Override public void onClick(View v) { if (v.getId() == R.id.ButtonTestPlayPause) { /** ImageButton onClick event handler. Method which start/pause mediaplayer playing */ try { mediaPlayer.setDataSource( "http://stream7.cache12.vcdn.vn/fsfsdfdsfdserwrwq3/df399b944be816f5fcf8d0671209dad5/55a0a05d/2015/05/15/6/6/66dd8254b28ea00774d136e251a40a98.mp3"); // setup song from http://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3 URL to mediaplayer data source mediaPlayer .prepare(); // you must call this method after setup the datasource in setDataSource // method. After calling prepare() the instance of MediaPlayer starts load // data from URL to internal buffer. } catch (Exception e) { e.printStackTrace(); } mediaFileLengthInMilliseconds = mediaPlayer.getDuration(); // gets the song length in milliseconds from URL if (!mediaPlayer.isPlaying()) { mediaPlayer.start(); buttonPlayPause.setImageResource(R.drawable.button_pause); } else { mediaPlayer.pause(); buttonPlayPause.setImageResource(R.drawable.button_play); } primarySeekBarProgressUpdater(); } }
private void openVideo() { if (mUri == null || mSurfaceHolder == null) { // not ready for playback just yet, will try again later return; } if (mMediaPlayer != null) { mMediaPlayer.reset(); mMediaPlayer.release(); mMediaPlayer = null; } try { mMediaPlayer = new MediaPlayer(); mMediaPlayer.setOnPreparedListener(mPreparedListener); mIsPrepared = false; mMediaPlayer.setOnCompletionListener(mCompletionListener); mMediaPlayer.setOnErrorListener(mErrorListener); mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener); mCurrentBufferPercentage = 0; mMediaPlayer.setDataSource(mContext, mUri); mMediaPlayer.setDisplay(mSurfaceHolder); mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.setScreenOnWhilePlaying(true); mMediaPlayer.prepareAsync(); attachMediaController(); } catch (IOException ex) { Log.w("VideoView", "Unable to open content: " + mUri, ex); return; } catch (IllegalArgumentException ex) { Log.w("VideoView", "Unable to open content: " + mUri, ex); return; } }
private void openVideo() { if (mUri == null || mSurface == null) { return; } if (mEnableMusicPause) { sendMusicPauseRequest(); } release(false); try { mPlayer = new MediaPlayer(); mPlayer.setOnPreparedListener(mPreparedListener); mPlayer.setOnVideoSizeChangedListener(mSizeChangedListener); mPlayer.setOnCompletionListener(mCompletionListener); mPlayer.setOnErrorListener(mErrorListener); mPlayer.setDataSource(mCtx, mUri); mPlayer.setSurface(mSurface); mSurface.release(); mSurface = null; mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mPlayer.setParameter(CLEAR_MOTION_KEY, CLEAR_MOTION_DISABLE); mPlayer.prepareAsync(); setCurrentState(STATE_PREPARING); } catch (IOException ex) { Log.e(TAG, "IOException : " + ex); setAllState(STATE_ERROR); mErrorListener.onError(mPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0); } catch (IllegalArgumentException ex) { Log.e(TAG, "IllegalArgumentException : " + ex); setAllState(STATE_ERROR); mErrorListener.onError(mPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0); } }