mp3文件没有在应用程序中播放

时间:2016-10-24 10:34:58

标签: android android-fragments android-mediaplayer

我正试图通过服务器播放这首歌,但它没有播放只有搜索栏正在从头到尾移动而没有信息。显示,歌曲也没有播放。 我的玩家活动代码是:

MyPlayer.java

public class MyPlayer extends Fragment implements View.OnClickListener, MediaPlayer.OnBufferingUpdateListener, OnCompletionListener, View.OnTouchListener {

    @Nullable
    AudioManager audioManager;
    ImageButton nextButton,backButton,repeat,volumehigh,volumelow, playpause;
    ToggleButton shufful;
    SeekBar seekbar, seekbar1;
    TextView artistname,mp3ename,starttime,totaltime;
    String strText= "" ,strText1="";
    MediaPlayer myMediaPlayer;
    private MediaPlayer mediaPlayer;
    private int mediaFileLengthInMilliseconds; // this value contains the song duration in milliseconds. Look at getDuration() method in MediaPlayer class
    public EditText editTextSongURL;
    String url = "https://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3";

    private final Handler handler = new Handler();
    private SeekBar seekBarProgress;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // return super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.player, container, false);
        initView();
        ArtistSong songFromArtist = new ArtistSong();
        strText = songFromArtist.getMp3();
        strText1 = songFromArtist.getName();

        artistname = (TextView) view.findViewById(R.id.nameArtistaa);
        mp3ename = (TextView) view.findViewById(R.id.mp3Nameaa);
        totaltime = (TextView) view.findViewById(R.id.totalTimeaa);
        starttime = (TextView) view.findViewById(R.id.startTimeaa);
        playpause = (ImageButton) view.findViewById(R.id.pauseaa);
        nextButton = (ImageButton) view.findViewById(R.id.forwardaa);
        backButton = (ImageButton) view.findViewById(R.id.backaa);
        repeat = (ImageButton) view.findViewById(R.id.loopaa);
        shufful = (ToggleButton) view.findViewById(R.id.icnshuffleaa);
        volumehigh = (ImageButton) view.findViewById(R.id.icnvolumehightaa);
        volumelow = (ImageButton) view.findViewById(R.id.lowvolumeaa);
        seekbar = (SeekBar) view.findViewById(R.id.seekBaraa);
        seekbar1 = (SeekBar) view.findViewById(R.id.seekBar2aa);
        audioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);

        seekbar1.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));

        seekbar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

                // textview.setText("Media Volume : " + i);

                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, i, 0);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });  
        return view;
    }

    private void initView() {
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnBufferingUpdateListener(this);
        mediaPlayer.setOnCompletionListener(this);
    }

    /** Method which updates the SeekBar primary progress by current song playing position*/
    private void primarySeekBarProgressUpdater() {
        seekBarProgress.setProgress((int) (((float) mediaPlayer.getCurrentPosition() / mediaFileLengthInMilliseconds)*100));
        // This math construction give a percentage of "was playing"/"song length"
        if (mediaPlayer.isPlaying()) {
            Runnable notification = new Runnable() {
                public void run() {
                    primarySeekBarProgressUpdater();
                }
            };
            handler.postDelayed(notification,1000);
        }
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.pauseaa){
            /** ImageButton onClick event handler. Method which start/pause mediaplayer playing */
            try {
                mediaPlayer.setDataSource(url.toString());
                // setup song from https://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();
                playpause.setImageResource(R.drawable.pause);
            }else {
                mediaPlayer.pause();
                playpause.setImageResource(R.drawable.play);
            }

            primarySeekBarProgressUpdater();
        }
    }


    public boolean onTouch(View v, MotionEvent event) {
        if(v.getId() == R.id.seekBaraa){
            /** Seekbar onTouch event handler. Method which seeks MediaPlayer to seekBar primary progress position*/
            if(mediaPlayer.isPlaying()){
                SeekBar sb = (SeekBar)v;
                int playPositionInMillisecconds = (mediaFileLengthInMilliseconds / 100) * sb.getProgress();
                mediaPlayer.seekTo(playPositionInMillisecconds);
            }
        }
        return false;
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        /** MediaPlayer onCompletion event handler. Method which calls then song playing is complete*/
        playpause.setImageResource(R.drawable.play);
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        /** Method which updates the SeekBar secondary progress by current song loading from URL position*/
        seekBarProgress.setSecondaryProgress(percent);
    }

}

1 个答案:

答案 0 :(得分:0)

我删除了一些不必要的代码来显示更改。我已经更改了设置OnBufferingUpdateListenerOnErrorListener的位置。引入了一些新的回调(除了OnPrepare()之外,完全取决于你)。

现在我猜测的是,您还没有等待MediaPlayer加载,即MediaPlayer尚未准备好播放。 MediaPlayer.OnPrepareListener告诉您MediaPlayer已准备好播放。

从以上链接:

  

void onPrepared (MediaPlayer mp)

     

媒体文件准备好播放时调用。

public class MyPlayer extends Fragment implements View.OnClickListener, MediaPlayer.OnBufferingUpdateListener, OnCompletionListener, MediaPlayer.OnPreparedListener, View.OnTouchListener {

    private MediaPlayer mediaPlayer;
    String url = "https://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // return super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.player, container, false);
        initView();
        .
        .
        .
        return view;
    }

    private void initView() {
        mediaPlayer = new MediaPlayer();
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.pauseaa){
            /** ImageButton onClick event handler. Method which start/pause mediaplayer playing */

            mediaPlayer.setOnPreparedListener(this);

            try {
                mediaPlayer.setDataSource(url.toString());
                // setup song from https://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();
            }

            if(!mediaPlayer.isPlaying()){
                mediaPlayer.start();
                playpause.setImageResource(R.drawable.pause);
            }else {
                mediaPlayer.pause();
                playpause.setImageResource(R.drawable.play);
            }

            primarySeekBarProgressUpdater();
        }
    }

    @Override
    public void onPrepared(MediaPlayer mp) {

        mp.start();

        mp.setOnBufferingUpdateListener(this);
        mp.setOnInfoListener(this);
        mp.setOnSeekCompleteListener(this);
        mp.setOnCompletionListener(this);
        mp.setOnErrorListener(this);
    }
}