Android Audio SeekBar

2020-02-28 09:19发布

问题:

I'm trying to create something where a single audio file is played and can be paused and manipulated with a progress/seek bar. I want to have an image taking up most of the screen and then a play pause button on the bottom left and the bar to the right of the button. Everything works the seekbar which isn't link to the audio. My progress bar coding is a probably a mess because if taken it from several i've seen on the internet but they are mostly confusing for me as they are for music player apps not for playing a single audio file.

Could someone please help me with the progress bar? Any other tips on improving my programming would be great too.

(I am very new to android and programming just to warn you)

This is my Java:

MediaPlayer mediaPlayer;
    Button buttonPlayPause;
    ImageView Image;
    SeekBar seekBar;

    private int stateMediaPlayer;
    private final int stateMP_NotStarter = 0;
    private final int stateMP_Playing = 1;
    private final int stateMP_Pausing = 2;
    int total;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.playerwere);

        Image = (ImageView) findViewById(R.id.pdfview);
        Image.setImageResource(R.drawable.wereim);

        seekBar = (SeekBar) findViewById(R.id.seekBar);

        buttonPlayPause = (Button) findViewById(R.id.playpause);

        buttonPlayPause.setOnClickListener(buttonPlayPauseOnClickListener);

        seekBar.setOnSeekBarChangeListener(seekBarOnSeekListener);

        initMediaPlayer();

        Thread currentThread = new Thread(this);
        currentThread.start();

    }

    private void initMediaPlayer() {
        mediaPlayer = new MediaPlayer();
        mediaPlayer = MediaPlayer.create(were.this, R.raw.were);
        stateMediaPlayer = stateMP_NotStarter;

        mediaPlayer.setOnPreparedListener(new OnPreparedListener() {

            @Override
            public void onPrepared(MediaPlayer arg0) {
                // TODO Auto-generated method stub
                total = mediaPlayer.getDuration();
            }

        });

        seekBar.setProgress(0);
        seekBar.setMax(total);
    }

    Button.OnClickListener buttonPlayPauseOnClickListener = new Button.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (stateMediaPlayer) {
            case stateMP_NotStarter:
                mediaPlayer.start();
    buttonPlayPause.setBackgroundResource(android.R.drawable.ic_media_pause);
                stateMediaPlayer = stateMP_Playing;
                break;
            case stateMP_Playing:
                mediaPlayer.pause();
    buttonPlayPause.setBackgroundResource(android.R.drawable.ic_media_play);
                stateMediaPlayer = stateMP_Pausing;
                break;
            case stateMP_Pausing:
                mediaPlayer.start();
    buttonPlayPause.setBackgroundResource(android.R.drawable.ic_media_pause);
                stateMediaPlayer = stateMP_Playing;
                break;
            }

        }
    };

    SeekBar.OnSeekBarChangeListener seekBarOnSeekListener = new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress,
                boolean fromUser) {
            // TODO Auto-generated method stub

            if (fromUser) {
                mediaPlayer.seekTo(progress);
                seekBar.setProgress(progress);
            }

        }
    };

    @Override
    public void run() {
        // TODO Auto-generated method stub

        try {
            while (mediaPlayer != null) {
                int currentPosition = mediaPlayer.getCurrentPosition();
                Message msg = new Message();
                msg.what = currentPosition;
                threadHandler.sendMessage(msg);
            }
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private Handler threadHandler = new Handler() {
        public void handleMessage(Message msg) {
            seekBar.setProgress(msg.what);
        }
    };

And this is what my java was before i tried to use the seekBar:

    MediaPlayer mediaPlayer;
    Button buttonPlayPause;
    ImageView Image;

    private int stateMediaPlayer;
    private final int stateMP_NotStarter = 0;
    private final int stateMP_Playing = 1;
    private final int stateMP_Pausing = 2;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.playerwere);

        Image = (ImageView) findViewById(R.id.pdfview);
        Image.setImageResource(R.drawable.wereim);

        buttonPlayPause = (Button) findViewById(R.id.playpause);

        buttonPlayPause.setOnClickListener(buttonPlayPauseOnClickListener);

        initMediaPlayer();

    }

    private void initMediaPlayer() {
        mediaPlayer = new MediaPlayer();
        mediaPlayer = MediaPlayer.create(were.this, R.raw.were);
        stateMediaPlayer = stateMP_NotStarter;
    }

    Button.OnClickListener buttonPlayPauseOnClickListener = new Button.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (stateMediaPlayer) {
            case stateMP_NotStarter:
                mediaPlayer.start();
    buttonPlayPause.setBackgroundResource(android.R.drawable.ic_media_pause);
                stateMediaPlayer = stateMP_Playing;
                break;
            case stateMP_Playing:
                mediaPlayer.pause();
    buttonPlayPause.setBackgroundResource(android.R.drawable.ic_media_play);
                stateMediaPlayer = stateMP_Pausing;
                break;
            case stateMP_Pausing:
                mediaPlayer.start();
    buttonPlayPause.setBackgroundResource(android.R.drawable.ic_media_pause);
                stateMediaPlayer = stateMP_Playing;
                break;
            }

        }
    };

This is my java after Vishal Vaja's answer:

MediaPlayer mediaPlayer;
    Button buttonPlayPause;
    ImageView Image;
    SeekBar seekBar;
    Handler handler;

    private int stateMediaPlayer;
    private final int stateMP_NotStarter = 0;
    private final int stateMP_Playing = 1;
    private final int stateMP_Pausing = 2;
    private int mediaPos;
    private int mediaMax;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.playerwere);

        Image = (ImageView) findViewById(R.id.pdfview);

        Image.setImageResource(R.drawable.wereim);

        seekBar = (SeekBar) findViewById(R.id.seekBar);

        buttonPlayPause = (Button) findViewById(R.id.playpause);

        buttonPlayPause.setOnClickListener(buttonPlayPauseOnClickListener);

        seekBar.setOnSeekBarChangeListener(seekBarOnSeekChangeListener);

        initMediaPlayer();

    }

    private void initMediaPlayer() {
        handler = new Handler();
        mediaPlayer = new MediaPlayer();
        mediaPlayer = MediaPlayer.create(were.this, R.raw.were);
        stateMediaPlayer = stateMP_NotStarter;
        mediaPos = mediaPlayer.getCurrentPosition();

        mediaMax = mediaPlayer.getDuration();

        seekBar.setMax(mediaMax); // Set the Maximum range of the
                                    // seekBar.setProgress(mediaPos);// set
                                    // current progress to song's

        handler.removeCallbacks(moveSeekBarThread);
        handler.postDelayed(moveSeekBarThread, 100);
    }

    private Runnable moveSeekBarThread = new Runnable() {

        public void run() {
            if (mediaPlayer.isPlaying()) {

                int mediaPos_new = mediaPlayer.getCurrentPosition();
                int mediaMax_new = mediaPlayer.getDuration();
                seekBar.setMax(mediaMax_new);
                seekBar.setProgress(mediaPos_new);

                handler.postDelayed(this, 100); // Looping the thread after 0.1
                                                // second
                                                // seconds
            }
        }
    };

    Button.OnClickListener buttonPlayPauseOnClickListener = new Button.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (stateMediaPlayer) {
            case stateMP_NotStarter:
                mediaPlayer.start();
                buttonPlayPause
                        .setBackgroundResource(android.R.drawable.ic_media_pause);
                stateMediaPlayer = stateMP_Playing;
                break;
            case stateMP_Playing:
                mediaPlayer.pause();
                buttonPlayPause
                        .setBackgroundResource(android.R.drawable.ic_media_play);
                stateMediaPlayer = stateMP_Pausing;
                break;
            case stateMP_Pausing:
                mediaPlayer.start();
                buttonPlayPause
                        .setBackgroundResource(android.R.drawable.ic_media_pause);
                stateMediaPlayer = stateMP_Playing;
                break;
            }

        }
    };

    SeekBar.OnSeekBarChangeListener seekBarOnSeekChangeListener = new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress,
                boolean fromUser) {
            // TODO Auto-generated method stub

            if (fromUser) {
                mediaPlayer.seekTo(progress);
                seekBar.setProgress(progress);
            }

        }
    };

回答1:

I think this can be work for you.

Create one thread that will check song position and will move seekbar like this,

private Runnable moveSeekBarThread = new Runnable() {

    public void run() {
        if(mediaPlayer.isplaying){

        int mediaPos_new = mediaPlayer.getCurrentPosition();
        int mediaMax_new = mediaPlayer.getDuration();
        seekBar.setMax(mediaMax_new);
        seekBar.setProgress(mediaPos_new);

        handler.postDelayed(this, 100); //Looping the thread after 0.1 second
                                        // seconds
        }  
    }
};

And call that thread like this,

  mediaPos = mediaPlayer.getCurrentPosition();
  mediaMax = mediaPlayer.getDuration();

  seekBar.setMax(mediaMax); // Set the Maximum range of the
  seekBar.setProgress(mediaPos);// set current progress to song's

  handler.removeCallbacks(moveSeekBarThread);
  handler.postDelayed(moveSeekBarThread, 100);


回答2:

public class DetailMusic extends Activity implements View.OnClickListener {

SeekBar seek_bar;
Button play_button, pause_button;
TextView text_shown;
Handler seekHandler = new Handler();
Bundle bundle = new Bundle();
String Musicnames;
int mediaMax;
int mediaPos = 0;
MediaPlayer mp = new MediaPlayer();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detailmusic);
    bundle = getIntent().getExtras();
    if (bundle != null) {
        Musicnames = bundle.getString("musicnbames");
        System.out.println("++++++++++++++++++++++++++++++++" + Musicnames);
        Log.e("musicfoldername", Musicnames);
    }
    seek_bar = (SeekBar) findViewById(R.id.seek_bar);
    play_button = (Button) findViewById(R.id.play_button);
    pause_button = (Button) findViewById(R.id.pause_button);
    text_shown = (TextView) findViewById(R.id.text_shown);
    play_button.setOnClickListener(this);
    pause_button.setOnClickListener(this);
    //seekUpdation();

    String PATH_TO_FILE = Musicnames;
    // MediaPlayer mp = new MediaPlayer();
    try {
        mp.setDataSource(PATH_TO_FILE);
        mp.prepare();
    } catch (IOException e) {

    }
    mp.start();
    seek_bar.setMax(mp.getDuration());

    try {
        mp.setDataSource(Musicnames);
    } 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();
    }
    mediaPos = mp.getCurrentPosition();
    mediaMax = mp.getDuration();
    seek_bar.setMax(mediaMax); // Set the Maximum range of the
    seek_bar.setProgress(mediaPos);// set current progress to song's
    seekHandler.removeCallbacks(moveSeekBarThread);
    seekHandler.postDelayed(moveSeekBarThread, 100); //cal the thread after 100 milliseconds

}

private Runnable moveSeekBarThread = new Runnable() {
    public void run() {
        if (mp.isPlaying()) {
            int mediaPos_new = mp.getCurrentPosition();
            int mediaMax_new = mp.getDuration();
            seek_bar.setMax(mediaMax_new);
            seek_bar.setProgress(mediaPos_new);
            seekHandler.postDelayed(this, 100); //Looping the thread after 0.1 second
        }
    }
};


@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.play_button:
            mp.reset();

// mp.start(); text_shown.setText("Playing...");

            break;
        case R.id.pause_button:
            mp.pause();
            text_shown.setText("Paused...");
    }
}

}