Пример #1
12
  @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;
  }
  public void playVoice(String filePath) {
    if (!(new File(filePath).exists())) {
      return;
    }
    AudioManager audioManager = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);

    mediaPlayer = new MediaPlayer();
    if (EMChatManager.getInstance().getChatOptions().getUseSpeaker()) {
      audioManager.setMode(AudioManager.MODE_NORMAL);
      audioManager.setSpeakerphoneOn(true);
      mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
    } else {
      audioManager.setSpeakerphoneOn(false); // 关闭扬声器
      // 把声音设定成Earpiece(听筒)出来,设定为正在通话中
      audioManager.setMode(AudioManager.MODE_IN_CALL);
      mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
    }
    try {
      mediaPlayer.setDataSource(filePath);
      mediaPlayer.prepare();
      mediaPlayer.setOnCompletionListener(
          new MediaPlayer.OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
              // TODO Auto-generated method stub
              mediaPlayer.release();
              mediaPlayer = null;
              stopPlayVoice(); // stop animation
            }
          });
      isPlaying = true;
      currentPlayListener = this;
      currentMessage = message;
      mediaPlayer.start();
      showAnimation();
      try {
        // 如果是接收的消息
        if (!message.isAcked && message.direct == EMMessage.Direct.RECEIVE) {
          message.isAcked = true;
          if (iv_read_status != null && iv_read_status.getVisibility() == View.VISIBLE) {
            // 隐藏自己未播放这条语音消息的标志
            iv_read_status.setVisibility(View.INVISIBLE);
            EMChatDB.getInstance().updateMessageAck(message.getMsgId(), true);
          }
          // 告知对方已读这条消息
          if (chatType != ChatType.GroupChat)
            EMChatManager.getInstance().ackMessageRead(message.getFrom(), message.getMsgId());
        }
      } catch (Exception e) {
        message.isAcked = false;
      }
    } catch (Exception e) {
    }
  }
Пример #3
0
  /**
   * 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();
    }
  }
Пример #4
0
  @Override
  public void onCreate() {

    feedBackIntent = new Intent(BROADCAST_FEEDBACK);
    seekIntent = new Intent(BROADCAST_SEEK);

    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setOnCompletionListener(this);
    mediaPlayer.setOnErrorListener(this);
    mediaPlayer.setOnBufferingUpdateListener(this);
    mediaPlayer.setOnInfoListener(this);
    mediaPlayer.setOnSeekCompleteListener(this);
    mediaPlayer.setOnPreparedListener(this);
    mediaPlayer.reset();

    DropboxConnect dropConnect = new DropboxConnect(getApplicationContext());
    dropboxApi = dropConnect.getDropboxAPI();

    nowplayingData = SongSQLite.getmInstance(getApplicationContext());
    playingSongList = nowplayingData.getAllSong(SongSQLite.TABLE_NOWPLAYING, null);
    intCurrentSong = 0;

    if (playingSongList == null) playingSongList = new ArrayList<>(); // If Database is Emply

    intTotalSong = playingSongList.size();
    updateCurrentSong();

    initNotification();
    Log.d(">>>> THAI <<<<", "onCreat() Service");
  }
Пример #5
0
  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);
    }
  }
Пример #6
0
  public void playNextSong(MusicItem musicItem) {
    String url = musicItem.audio;
    Logger.debug(TAG, ">>>" + "playNextSong:" + url);
    if (musicPlayBackCallback != null) {
      musicPlayBackCallback.onPreparing(currentItem);
    }
    mState = State.Stopped;

    relaxResource(false);
    try {
      setupMediaPlayerIfNeeded();

      mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
      mediaPlayer.setDataSource(url);
      isStreaming = url.startsWith("http:") || url.startsWith("https:");

      songTitle = url;

      mState = State.Preparing;
      setupAsForeGround(musicItem);

      /** @see onPreparedListener */
      mediaPlayer.prepareAsync();

      if (isStreaming) {
        wifiLock.acquire();
      } else if (wifiLock.isHeld()) {
        wifiLock.release();
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  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");
    }
  }
Пример #8
0
  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();
    }
  }
Пример #9
0
    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);
    }
Пример #10
0
  private void play() {

    try {
      player.setDataSource(pathname);

      player.setDisplay(holder);

      int w = mVideo.getWidth();
      int h = mVideo.getHeight();
      if (w != 0 && h != 0) {
        player.enableScaleMode(true, w, h);
        Log.d(
            TAG,
            "set scale mode:"
                + String.valueOf(mVideo.getWidth())
                + "*"
                + String.valueOf(mVideo.getHeight()));
      }
      player.prepareAsync();
      player.setOnPreparedListener(this);
      player.setOnCompletionListener(this);
      player.setAudioStreamType(AudioManager.STREAM_MUSIC);
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Пример #11
0
  private void prepare() {
    setEnabledButton(false);

    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    Item playingItem = mItems.get(mIndex);
    try {
      mMediaPlayer.setDataSource(getApplicationContext(), playingItem.getURI());
      mMediaPlayer.prepare();
    } catch (IllegalArgumentException e) {
      Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
      e.printStackTrace();
    } catch (SecurityException e) {
      Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
      e.printStackTrace();
    } catch (IllegalStateException e) {
      Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
      e.printStackTrace();
    } catch (IOException e) {
      Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
      e.printStackTrace();
    }
    mTextViewArtist.setText(playingItem.artist);
    mTextViewAlbum.setText(playingItem.album);
    mTextViewTitle.setText(playingItem.title);
    mButtonPlayPause.setImageResource(R.drawable.media_play);
    mButtonPlayPause.setContentDescription(getResources().getText(R.string.play));
    mChronometer.setBase(SystemClock.elapsedRealtime());
  }
Пример #12
0
  public void playRingtone() {
    AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);

    // Honour silent mode
    switch (audioManager.getRingerMode()) {
      case AudioManager.RINGER_MODE_NORMAL:
        mPlayer = new MediaPlayer();
        mPlayer.setAudioStreamType(AudioManager.STREAM_RING);

        try {
          mPlayer.setDataSource(
              mContext,
              Uri.parse(
                  "android.resource://" + mContext.getPackageName() + "/" + R.raw.phone_loud1));
          mPlayer.prepare();
        } catch (IOException e) {
          Log.e(LOG_TAG, "Could not setup media player for ringtone");
          mPlayer = null;
          return;
        }
        mPlayer.setLooping(true);
        mPlayer.start();
        break;
    }
  }
Пример #13
0
  private void setSong() {
    if (mSongSelector.getCurrentSong() != null) {
      if (mPlayer == null) {
        createPlayer();
        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
      }
      mPlayer.reset();

      try {
        mPlayer.setDataSource(getApplicationContext(), mSongSelector.getCurrentSong().getUri());
      } 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();
      }
    }
  }
Пример #14
0
 public void initAudioPlayer() {
   mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
   mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
   mediaPlayer.setOnPreparedListener(this);
   // mediaPlayer.setOnCompletionListener(this);
   mediaPlayer.setOnErrorListener(this);
 }
Пример #15
0
  private void initPlayer() throws Exception {
    streamer = new HttpMediaStreamer(mFileName, mMimeType);
    Uri uri = streamer.getUri();

    mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setOnPreparedListener(
        new OnPreparedListener() {

          @Override
          public void onPrepared(MediaPlayer mp) {
            mediaPlayer.start();
          }
        });
    mediaPlayer.setOnCompletionListener(
        new OnCompletionListener() {

          @Override
          public void onCompletion(MediaPlayer mp) {
            killPlayer();
          }
        });

    mediaPlayer.setDataSource(mContext, uri);
    mediaPlayer.prepareAsync();
  }
  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;
    }
  }
  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;
  }
Пример #18
0
  private boolean play() {
    try {
      if (mediaPlayer == null) {
        mediaPlayer = new MediaPlayer();
        mPlayerWeakRef = new WeakReference<MediaPlayer>(mediaPlayer);

        mediaPlayer.setAudioStreamType(AudioManager.STREAM_SYSTEM);
        mediaPlayer.setOnCompletionListener(this);

        mediaPlayer.setDataSource(FilePathHelper.getWaveTransFile());
        mediaPlayer.prepare();

      } else {
        if (mediaPlayer.isPlaying()) {
          mediaPlayer.pause();
        }
      }

      mediaPlayer.start();
    } catch (Exception e) {
      e.printStackTrace();
      mediaPlayer = null;
    }

    if (mediaPlayer == null) {
      return false;
    }

    mIsCurrPlaying = true;
    return true;
  }
Пример #19
0
    public Player(Context context, MediaPlayer mmediaPlayer) {
      this.context = context;
      mediaPlayer = mmediaPlayer;

      // progress = new ProgressDialog(context);
      mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    }
Пример #20
0
  private void initMediaPlayer() {

    mediaPlayer = new MediaPlayer();

    mediaPlayer.setAudioStreamType(STREAM_TYPE);
    mediaPlayer.setVolume(1f, 1f);

    mediaPlayer.setOnErrorListener(
        new OnErrorListener() {
          @Override
          public boolean onError(MediaPlayer mp, int what, int extra) {
            Log.e(TAG, "MediaPlayer.onErrorListener (What: " + what + ", Extra: " + extra + ")");
            // mp.reset();
            if (what == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
              mp.release();
              initMediaPlayer();
            }
            return true;
          }
        });

    mediaPlayer.setOnInfoListener(
        new OnInfoListener() {
          @Override
          public boolean onInfo(MediaPlayer mp, int what, int extra) {
            Log.e(TAG, "MediaPlayer.onInfoListener (What: " + what + ", Extra: " + extra + ")");
            return false;
          }
        });
  }
Пример #21
0
  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;
    }
  }
Пример #22
0
  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();
    }
  }
 /** Prepare the given url */
 @Override
 public MediaPlayerInterface prepare(
     Context context,
     Query query,
     MediaPlayer.OnPreparedListener onPreparedListener,
     MediaPlayer.OnCompletionListener onCompletionListener,
     MediaPlayer.OnErrorListener onErrorListener) {
   Log.d(TAG, "prepare()");
   mOnPreparedListener = onPreparedListener;
   mOnCompletionListener = onCompletionListener;
   mOnErrorListener = onErrorListener;
   mPreparedQuery = null;
   mPreparingQuery = query;
   release();
   mMediaPlayer =
       MediaPlayer.create(context, Uri.parse(query.getPreferredTrackResult().getPath()));
   if (mMediaPlayer == null) {
     return null;
   }
   mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
   mMediaPlayer.setOnPreparedListener(this);
   mMediaPlayer.setOnErrorListener(this);
   mMediaPlayer.setOnCompletionListener(this);
   return this;
 }
Пример #24
0
  private void createPlayerView() {
    mSurfaceView = (SurfaceView) findViewById(R.id.surfaceView);
    mSurfaceHolder = mSurfaceView.getHolder();
    mSurfaceHolder.addCallback(this);
    mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    mMediaPlayer = new MediaPlayer();
    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mMediaPlayer.setOnPreparedListener(
        new MediaPlayer.OnPreparedListener() {
          @Override
          public void onPrepared(MediaPlayer mp) {
            startPlaying();
          }
        });

    mMediaPlayer.setOnCompletionListener(
        new MediaPlayer.OnCompletionListener() {
          @Override
          public void onCompletion(MediaPlayer mp) {
            // 自动播放下一个
            mMediaPlayer.reset();
            playNext();
          }
        });
  }
Пример #25
0
  // playback
  public Playback(SurfaceView surfaceview, int playerMode) {
    mmediaplayer = new MediaPlayer();

    msurfaceholder = surfaceview.getHolder();
    msurfaceholder.addCallback(this);
    // msurfaceholder.setFixedSize(surfaceview.getWidth(),
    // surfaceview.getHeight());
    msurfaceholder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    mmediaplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mmediaplayer.setDisplay(msurfaceholder);

    mmediaplayer.setOnErrorListener(errListener);
    mmediaplayer.setOnPreparedListener(preListener);
    mmediaplayer.setOnCompletionListener(completeListener);
    mmediaplayer.setOnSeekCompleteListener(seekListener);

    mPlayStatus = VideoConst.PLAY_STATUS_UNKNOW;

    if (playerMode == VideoConst.PLAYER_MODE_MMP) {
      videopl = PlayList.getPlayList();
      mcurPath = videopl.getCurrentPath(Const.FILTER_VIDEO);
    }
    mplayerMode = playerMode;

    pb = this;
  }
  private void initData(Context context) {
    this.mContext = context;
    mActivity = (Activity) context;
    DisplayMetrics dm = new DisplayMetrics();
    mActivity.getWindowManager().getDefaultDisplay().getMetrics(dm);
    mDensity = dm.density;
    mWidth = dm.widthPixels;
    mInflater = LayoutInflater.from(mContext);
    AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
    audioManager.setMode(AudioManager.MODE_NORMAL);
    if (audioManager.isSpeakerphoneOn()) {
      audioManager.setSpeakerphoneOn(true);
    } else {
      audioManager.setSpeakerphoneOn(false);
    }
    mp.setAudioStreamType(AudioManager.STREAM_RING);
    mp.setOnErrorListener(
        new OnErrorListener() {

          @Override
          public boolean onError(MediaPlayer mp, int what, int extra) {
            return 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() );
    }

    */
  }
Пример #28
0
  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);
    }
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_audio);

    progressBar = (ProgressBar) findViewById(R.id.download_progress_bar);
    playButton = (ImageButton) findViewById(R.id.play_button);
    stateTextView = (TextView) findViewById(R.id.player_state_text_view);
    playerProgressBar = (ProgressBar) findViewById(R.id.player_progress);

    // date formats for title and url
    Date today = new Date();

    SimpleDateFormat titleDateFormat = new SimpleDateFormat("dd.MM");
    SimpleDateFormat urlDateFormat = new SimpleDateFormat("yyyyMMdd");

    // checking if todays prayer is already uploaded (it should be after 15:40)
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(today);
    calendar.set(Calendar.HOUR_OF_DAY, 15);
    calendar.set(Calendar.MINUTE, 40);
    calendar.set(Calendar.SECOND, 0);
    Date todaysPrayer = calendar.getTime();

    Log.d("date", "today: " + today);
    Log.d("date", "todaysPrayer: " + todaysPrayer);

    Date prayersDate = today;
    if (!today.after(todaysPrayer)) {
      prayersDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000);
      Log.d("date", "dzis jeszcze ni ma :(");
    }

    // obtaining url to current transmission
    String baseUrl = getString(R.string.url_audio);

    String url = baseUrl.replace("{date}", urlDateFormat.format(prayersDate));

    // setting title
    TextView titleTextView = (TextView) findViewById(R.id.title_audio_text_view);
    String baseTitle = getString(R.string.odsluchaj_koronke);
    String title = baseTitle.replace("{date}", titleDateFormat.format(prayersDate));
    titleTextView.setText(title);

    // setting up player
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

    try {
      mediaPlayer.setDataSource(url);
    } catch (IOException e) {
      // handling error that is almost impossible to occur :P
      Toast.makeText(this, R.string.audio_url_error, Toast.LENGTH_LONG).show();
      Log.d("player", e.getMessage(), e);
      finish();
    }
  }
  public void openVideo(Uri uri) {
    if (uri == null || mSurfaceHolder == null || getContext() == null) {
      // not ready for playback just yet, will try again later
      if (mSurfaceHolder == null && uri != null) {
        mUri = uri;
      }
      return;
    }

    mUri = uri;
    mDuration = 0;

    // Idle 状态:当使用new()方法创建一个MediaPlayer对象或者调用了其reset()方法时,该MediaPlayer对象处于idle状态。
    // End 状态:通过release()方法可以进入End状态,只要MediaPlayer对象不再被使用,就应当尽快将其通过release()方法释放掉
    // Initialized 状态:这个状态比较简单,MediaPlayer调用setDataSource()方法就进入Initialized状态,表示此时要播放的文件已经设置好了。
    // Prepared
    // 状态:初始化完成之后还需要通过调用prepare()或prepareAsync()方法,这两个方法一个是同步的一个是异步的,只有进入Prepared状态,才表明MediaPlayer到目前为止都没有错误,可以进行文件播放。

    Exception exception = null;
    try {
      if (mMediaPlayer == null) {
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setOnPreparedListener(mPreparedListener);
        mMediaPlayer.setOnCompletionListener(mCompletionListener);
        mMediaPlayer.setOnErrorListener(mErrorListener);
        mMediaPlayer.setOnVideoSizeChangedListener(mVideoSizeChangedListener);
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setOnSeekCompleteListener(mSeekCompleteListener);
        mMediaPlayer.setOnInfoListener(mInfoListener);
        //			mMediaPlayer.setScreenOnWhilePlaying(true);
        //				mMediaPlayer.setVolume(mSystemVolumn, mSystemVolumn);
        mMediaPlayer.setDisplay(mSurfaceHolder);
      } else {
        mMediaPlayer.reset();
      }
      mMediaPlayer.setDataSource(getContext(), uri);

      //			if (mLooping)
      //				mMediaPlayer.setLooping(true);//循环播放
      mMediaPlayer.prepareAsync();
      // we don't set the target state here either, but preserve the
      // target state that was there before.
      mCurrentState = STATE_PREPARING;
    } catch (IOException ex) {
      exception = ex;
    } catch (IllegalArgumentException ex) {
      exception = ex;
    } catch (Exception ex) {
      exception = ex;
    }
    if (exception != null) {
      Logger.e(exception);
      mCurrentState = STATE_ERROR;
      if (mErrorListener != null)
        mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
    }
  }