【问题标题】:Can not add SeekBar to MediaPlayer.无法将 SeekBar 添加到 MediaPlayer。
【发布时间】:2015-06-21 16:30:52
【问题描述】:

我也试过 Runnable 但没用。这是我的代码,这里可以做什么? 我已经使用 Parecelable 方法将我当前选择的歌曲从主要活动中获取到此播放屏幕活动。现在我想将搜索栏附加到我的媒体播放器 mPlayer 启动时收到的“currsong”

package com.musicplayer;

import android.content.ContentUris;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.PowerManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.Random;


public class PlayScreen extends ActionBarActivity {

private Song currsong;
public MainActivity mainActivity;
private MediaPlayer mPlayer;
public TextView songTitle , songArtist;
public ImageView playPause, next, prev;
public SeekBar seekbar;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_play_screen);
    currsong = (Song)getIntent().getParcelableExtra("currSong");
    final RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.playScreen);
    Drawable drawable=new BitmapDrawable(getResources(), currsong.getAlbumart(getApplicationContext()));
    relativeLayout.setBackground(drawable);
    songTitle=(TextView)findViewById(R.id.stitle);
    songArtist=(TextView)findViewById(R.id.artist);
    playPause= (ImageView)findViewById(R.id.playPause);
    next= (ImageView)findViewById(R.id.next);
    prev= (ImageView)findViewById(R.id.prev);
    seekbar=(SeekBar)findViewById(R.id.progress);

    next.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(mPlayer.isPlaying()){
                mPlayer.stop();
                try {
                    mPlayer.prepare();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            mainActivity.songPos++;
            currsong=mainActivity.songList.get(mainActivity.songPos);
            Drawable drawable=new BitmapDrawable(getResources(), currsong.getAlbumart(getApplicationContext()));
            relativeLayout.setBackground(drawable);
            seekbar.setMax(mPlayer.getDuration());
            playSong();
        }
    });
    prev.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(mPlayer.isPlaying()){
                mPlayer.stop();
                try {
                    mPlayer.prepare();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            mainActivity.songPos--;
            currsong=mainActivity.songList.get(mainActivity.songPos);
            Drawable drawable=new BitmapDrawable(getResources(), currsong.getAlbumart(getApplicationContext()));
            relativeLayout.setBackground(drawable);
            seekbar.setMax(mPlayer.getDuration());
            playSong();
        }
    });
    playPause.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            if(mPlayer.isPlaying() ){
                mPlayer.pause();
                playPause.setImageResource(R.drawable.play);
            }
            else {
                mPlayer.start();
                playPause.setImageResource(R.drawable.pause);
                }

        }
    });

    playSong();


}


public void playSong(){

    mPlayer= new MediaPlayer();
    mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

    songTitle.setText(currsong.getTitle());
    songArtist.setText(currsong.getArtist());
    //set uri
    Uri trackUri = ContentUris.withAppendedId(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,currsong.getID());
    //set the data source

    try{
        mPlayer.setDataSource(getApplicationContext(), trackUri);
    }
    catch(Exception e){
        Log.e("MUSIC SERVICE", "Error setting data source", e);
    }
    try {
        mPlayer.prepare();
    } catch (IllegalStateException e) {
        Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
    } catch (IOException e) {
        Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
    }
    //seekbar.setMax(mPlayer.getDuration());
    mPlayer.start();
    playPause.setImageResource(R.drawable.pause);



}






public void initMusicPlayer(){
    //set player properties
    mPlayer.setWakeMode(getApplicationContext(),
            PowerManager.PARTIAL_WAKE_LOCK);
    mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mPlayer.setOnPreparedListener((MediaPlayer.OnPreparedListener) this);
    mPlayer.setOnCompletionListener((MediaPlayer.OnCompletionListener) this);
    mPlayer.setOnErrorListener((MediaPlayer.OnErrorListener) this);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_play_screen, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

【问题讨论】:

    标签: android-mediaplayer runnable seekbar android-seekbar


    【解决方案1】:

    经过大量搜索后,我找到了一种方法,因为没有人回答这个问题,所以为了帮助其他有同样问题的人,我在下面提供了我解决的 java 文件代码-

    package com.musicplayer;
    
    import android.content.ContentResolver;
    import android.content.ContentUris;
    import android.content.Intent;
    import android.database.Cursor;
    import android.graphics.Bitmap;
    import android.graphics.Color;
    import android.graphics.drawable.BitmapDrawable;
    import android.graphics.drawable.ColorDrawable;
    import android.graphics.drawable.Drawable;
    import android.media.AudioManager;
    import android.media.MediaPlayer;
    import android.net.Uri;
    import android.os.PowerManager;
    import android.provider.MediaStore;
    import android.support.v7.app.ActionBarActivity;
    import android.os.Bundle;
    import android.text.StaticLayout;
    import android.util.Log;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.ImageButton;
    import android.widget.ImageView;
    import android.widget.RelativeLayout;
    import android.widget.SeekBar;
    import android.widget.TextView;
    import android.widget.Toast;
    import android.widget.SeekBar.OnSeekBarChangeListener;
    import android.view.View.OnClickListener;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Date;
    import java.util.Random;
    
    
    public class PlayScreen extends ActionBarActivity implements Runnable,
        OnClickListener, OnSeekBarChangeListener, MediaPlayer.OnCompletionListener {
    
    protected static Song currsong ;
    protected TextView songTitle , songArtist;
    protected ImageView playPause, next, prev, loop ,shuffle;
    protected SeekBar seekbar;
    protected RelativeLayout relativeLayout;
    protected Uri trackpath;
    protected static boolean looping=false, shuffling=false;
    protected ArrayList<Song> shuffleSong;
    protected MediaPlayerSingleton mPlayer = MediaPlayerSingleton.getInstance();
    protected ArrayList<Song> songList;
    
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_screen);
        currsong = (Song)getIntent().getParcelableExtra("currSong");
        songList =new ArrayList<Song>();
        Bundle b = this.getIntent().getExtras();
        songList = b.getParcelableArrayList("categories");
        relativeLayout = (RelativeLayout) findViewById(R.id.playScreen);
        Drawable drawable=new BitmapDrawable(getResources(), currsong.getAlbumart(getApplicationContext()));
        relativeLayout.setBackground(drawable);
        songTitle=(TextView)findViewById(R.id.stitle);
        songArtist=(TextView)findViewById(R.id.artist);
        playPause= (ImageView)findViewById(R.id.playPause);
        next= (ImageView)findViewById(R.id.next);
        prev= (ImageView)findViewById(R.id.prev);
        loop = (ImageView)findViewById(R.id.loop);
        shuffle = (ImageView)findViewById(R.id.shuffle);
        seekbar=(SeekBar)findViewById(R.id.progress);
        next.setOnClickListener(this);
        prev.setOnClickListener(this);
        playPause.setOnClickListener(this);
        loop.setOnClickListener(this);
        shuffle.setOnClickListener(this);
        seekbar.setOnSeekBarChangeListener(this);
        seekbar.setEnabled(true);
        loop.setImageResource(R.drawable.loop);
        shuffle.setImageResource(R.drawable.shuffle);
        shuffleSong = new ArrayList<Song>();
    
        playSong();
    }
    
    public void getSongList() {
        shuffleSong.addAll(songList);
        Collections.shuffle(shuffleSong);
    }
    
    
    public void playSong(){
        mPlayer.reset();
        int minute = 60*1000;
        Toast.makeText(getApplicationContext(), "Can't play this song: "+ currsong.getPath(), Toast.LENGTH_LONG).show();
        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        TextView totaltime =(TextView)findViewById(R.id.timeleft);
    
        //set uri
        Uri trackUri = ContentUris.withAppendedId(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,currsong.getID());
        trackpath=trackUri;
        //set the data source
    
        try{
            mPlayer.setDataSource(getApplicationContext(), trackUri);
        }
        catch(Exception e){
            Log.e("MUSIC SERVICE", "Error setting data source", e);
        }
        try {
            mPlayer.prepare();
        } catch (IllegalStateException e) {
            Toast.makeText(getApplicationContext(), "Can't play this song: "+ currsong.getTitle(), Toast.LENGTH_LONG).show();
            next.performClick();
        } catch (IOException e) {
            Toast.makeText(getApplicationContext(), "Can't play this song: "+ currsong.getTitle(), Toast.LENGTH_LONG).show();
            next.performClick();
        }
        songTitle.setText(currsong.getTitle());
        songArtist.setText(currsong.getArtist());
        seekbar.setMax(mPlayer.getDuration());
        seekbar.setEnabled(true);
    
        new Thread(this).start();
        if(mPlayer.getDuration()<minute) {
            totaltime.setText(String.format("0:%1$tS", new Date(mPlayer.getDuration()-60*1000*30)));
        }else{
            totaltime.setText(String.format("%1$tM:%1$tS", new Date(mPlayer.getDuration()-60*1000*30)));
        }
        mPlayer.start();
        playPause.setImageResource(R.drawable.pause);
        mPlayer.setOnCompletionListener(this);
    
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_play_screen, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
    
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
    
        return super.onOptionsItemSelected(item);
    }
    
    @Override
    public void onClick(View v) {
        if (v.equals(playPause)){
            if(mPlayer == null){
                try{
                    mPlayer.setDataSource(getApplicationContext(), trackpath);
                }
                catch(Exception e){
                    Log.e("MUSIC SERVICE", "Error setting data source", e);
                }
                try {
                    mPlayer.prepare();
                } catch (IllegalStateException e) {
                    Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
                } catch (IOException e) {
                    Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
                }
                seekbar.setEnabled(true);
            }
            if (mPlayer.isPlaying()) {
                mPlayer.pause();
                playPause.setImageResource(R.drawable.play);
            }
            else {
                mPlayer.start();
                playPause.setImageResource(R.drawable.pause);
                seekbar.setMax(mPlayer.getDuration());
                new Thread(this).start();
            }
        }
        if(v.equals(next) && mPlayer != null){
            if(shuffling==false) {
                if (mPlayer.isPlaying()) {
                    mPlayer.stop();
                    try {
                        mPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (looping == true) {
                    if (AllSongs.songPos == songList.size() - 1) {
                        AllSongs.songPos = 0;
                        currsong = songList.get(AllSongs.songPos);
                    } else {
                        AllSongs.songPos++;
                        currsong = songList.get(AllSongs.songPos);
                    }
                } else {
                    if (AllSongs.songPos == songList.size() - 1) {
                        Toast.makeText(getApplicationContext(), "List Ended", Toast.LENGTH_SHORT).show();
                        //currsong=mainActivity.songList.get(mainActivity.songPos);
                    } else {
                        AllSongs.songPos++;
                        currsong = songList.get(AllSongs.songPos);
                    }
                }
            }else{
                if (mPlayer.isPlaying()) {
                    mPlayer.stop();
                    try {
                        mPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                /*Random rand = new Random();
                int randomNum = mainActivity.songPos;
                while(randomNum==mainActivity.songPos) {
                    randomNum = rand.nextInt(shuffleSong.size());
                }
                currsong = shuffleSong.get(randomNum);
                shuffleSong.remove(randomNum);*/
                if (looping == true) {
                    if (AllSongs.songPos == shuffleSong.size() - 1) {
                        AllSongs.songPos = 0;
                        currsong = shuffleSong.get(AllSongs.songPos);
                    } else {
                        AllSongs.songPos++;
                        currsong = shuffleSong.get(AllSongs.songPos);
                    }
                } else {
                    if (AllSongs.songPos == shuffleSong.size() - 1) {
                        Toast.makeText(getApplicationContext(), "List Ended", Toast.LENGTH_SHORT).show();
                        //currsong=mainActivity.songList.get(mainActivity.songPos);
                    } else {
                        AllSongs.songPos++;
                        currsong = shuffleSong.get(AllSongs.songPos);
                    }
                }
    
            }
    
    
            Drawable drawable=new BitmapDrawable(getResources(), currsong.getAlbumart(getApplicationContext()));
            relativeLayout.setBackground(drawable);
            seekbar.setMax(mPlayer.getDuration());
            seekbar.setProgress(0);
            playSong();
        }
        if(v.equals(prev) && mPlayer != null){
            if(shuffling==false) {
                if(mPlayer.isPlaying()){
                    mPlayer.stop();
                    try {
                        mPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (looping == true) {
                    if (AllSongs.songPos == 0) {
                        AllSongs.songPos = songList.size() - 1;
                        currsong = songList.get(AllSongs.songPos);
                    } else {
                        AllSongs.songPos--;
                        currsong = songList.get(AllSongs.songPos);
                    }
                } else {
                    if (AllSongs.songPos == 0) {
                        Toast.makeText(getApplicationContext(), "List Ended", Toast.LENGTH_SHORT).show();
                    } else {
                        AllSongs.songPos--;
                        currsong = songList.get(AllSongs.songPos);
                    }
                }
            }else{
                if (mPlayer.isPlaying()) {
                    mPlayer.stop();
                    try {
                        mPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (looping == true) {
                    if (AllSongs.songPos == 0) {
                        AllSongs.songPos = shuffleSong.size() - 1;
                        currsong = shuffleSong.get(AllSongs.songPos);
                    } else {
                        AllSongs.songPos--;
                        currsong = shuffleSong.get(AllSongs.songPos);
                    }
                } else {
                    if (AllSongs.songPos == 0) {
                        Toast.makeText(getApplicationContext(), "List Ended", Toast.LENGTH_SHORT).show();
                    } else {
                        AllSongs.songPos--;
                        currsong = shuffleSong.get(AllSongs.songPos);
                    }
                }
                /*Random rand = new Random();
                int randomNum = mainActivity.songPos;
                while(randomNum==mainActivity.songPos) {
                    randomNum = rand.nextInt(shuffleSong.size());
                }
                currsong = shuffleSong.get(randomNum);
                shuffleSong.remove(randomNum);*/
            }
    
            Drawable drawable=new BitmapDrawable(getResources(), currsong.getAlbumart(getApplicationContext()));
            relativeLayout.setBackground(drawable);
            seekbar.setMax(mPlayer.getDuration());
            seekbar.setProgress(0);
            playSong();
    
        }
        if(v.equals(loop)){
            if(looping==false) {
                loop.setImageResource(R.drawable.loopactive);
                looping = true;
            }
            else{
                looping=false;
                loop.setImageResource(R.drawable.loop);
            }
        }
        if(v.equals(shuffle)){
            if(shuffling==false) {
                getSongList();
                shuffle.setImageResource(R.drawable.shuffleactive);
                shuffling = true;
                Collections.shuffle(shuffleSong);
                //setNextSongDetails();
                //shuffleList();
            }else{
                shuffleSong.clear();
                shuffling=false;
                shuffle.setImageResource(R.drawable.shuffle);
                //setNextSongDetails();
            }
        }
    }
    
    /*private void shuffleList() {
        for(int i=0;i<mainActivity.songList.size();i++){
            Random rand = new Random();
            int randomNum = rand.nextInt((mainActivity.songList.size() - i)) + i;
            int j=0,k=0;
            int flag=0;
            k=mainActivity.posList.size();
            for(j=0;j<k;j++){
    
                if(MainActivity.posList.get(j) == randomNum){
                    flag=1;
                }
                //j=j+1;
            }
            if(flag==1){
                i=i-1;
            }else{
                MainActivity.posList.add(new Integer(randomNum));
                tempsong=MainActivity.songList.get(randomNum);
                shuffleSong.add(new Song(tempsong.getID(), tempsong.getTitle(), tempsong.getArtist(), tempsong.getAlbumID()));
            }
        }
    }*/
    
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        try {
            if (mPlayer.isPlaying() || mPlayer != null) {
                if (fromUser)
                    mPlayer.seekTo(progress);
            } else if (mPlayer == null) {
                Toast.makeText(getApplicationContext(), "Media is not running",
                        Toast.LENGTH_SHORT).show();
                seekBar.setProgress(0);
            }
        } catch (Exception e) {
            //Log.e("seek bar", "" + e);
            seekBar.setEnabled(false);
    
        }
    
    }
    
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
    
    }
    
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
    
    }
    
    @Override
    public void run() {
        int currentPosition = mPlayer.getCurrentPosition();
        int total = mPlayer.getDuration();
    
    
        while (mPlayer != null && currentPosition < total) {
            try {
                Thread.sleep(1000);
                currentPosition = mPlayer.getCurrentPosition();
            } catch (InterruptedException e) {
                return;
            } catch (Exception e) {
                return;
            }
            seekbar.setProgress(currentPosition);
        }
    
    
    }
    
    @Override
    public void onCompletion(MediaPlayer mp) {
        if(mPlayer.getCurrentPosition()>0){
            mp.reset();
            next.performClick();
        }
    
    }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多