java - 修复我的 Android 音乐播放器上的搜索栏

标签 java android seekbar audio-player android-music-player

我在 Android 中创建了一个简单的音乐播放器,它有一个搜索栏,显示歌曲播放的当前位置。前进、后退、播放和暂停功能正常工作。我想要做的是让搜索栏实际移动歌曲中的位置。 (目前搜索栏不会改变歌曲中的位置。这是我的代码

public class MusicPlayerA extends Activity {

private MediaPlayer mediaPlayer;
public TextView songName, duration;
private double timeElapsed = 0, finalTime = 0;
private int forwardTime = 2500, backwardTime = 2500;
private Handler durationHandler = new Handler();
private SeekBar seekbar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //set the layout of the Activity
    setContentView(R.layout.musicplayerview);
    //initialize views
    initializeViews();
}

@Override
protected void onPause() {
    super.onPause();
    if (mediaPlayer != null) {
        mediaPlayer.pause();
        if (isFinishing()) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }
    }
}

public void initializeViews(){
    songName = (TextView) findViewById(R.id.songName);
    mediaPlayer = MediaPlayer.create(this, R.raw.druidsad);
    finalTime = mediaPlayer.getDuration();
    duration = (TextView) findViewById(R.id.songDuration);
    seekbar = (SeekBar) findViewById(R.id.seekBar);
    songName.setText("Druids Ad");  
    seekbar.setMax((int) finalTime);
    seekbar.setClickable(true);
}

// play mp3 song
public void play(View view) {
    mediaPlayer.start();
    timeElapsed = mediaPlayer.getCurrentPosition();
    seekbar.setProgress((int) timeElapsed);
    durationHandler.postDelayed(updateSeekBarTime, 100);
}

//handler to change seekBarTime
private Runnable updateSeekBarTime = new Runnable() {
    public void run() {
        //get current position
        timeElapsed = mediaPlayer.getCurrentPosition();
        //set seekbar progress
        seekbar.setProgress((int) timeElapsed);
        //set time remaining
        double timeRemaining = finalTime - timeElapsed;
        duration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining), TimeUnit.MILLISECONDS.toSeconds((long) timeRemaining) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining))));

        //repeat yourself that again in 100 miliseconds
        durationHandler.postDelayed(this, 100);
    }
};

// pause mp3 song
public void pause(View view) {
    mediaPlayer.pause();
}

// go forward at forwardTime seconds
public void forward(View view) {
    //check if we can go forward at forwardTime seconds before song endes
    if ((timeElapsed + forwardTime) <= finalTime) {
        timeElapsed = timeElapsed + forwardTime;

        //seek to the exact second of the track
        mediaPlayer.seekTo((int) timeElapsed);
    }
}

// go backwards at backwardTime seconds
public void rewind(View view) {
    //check if we can go back at backwardTime seconds after song starts
    if ((timeElapsed - backwardTime) > 0) {
        timeElapsed = timeElapsed - backwardTime;

        //seek to the exact second of the track
        mediaPlayer.seekTo((int) timeElapsed);
    }
}

 // handler for back button used on music player screen
 public void BackButton2 (View view) {

    MediaPlayer mMediaPlayer = MediaPlayer.create(this, R.raw.soundbackbutton) ;
    mMediaPlayer.start();

    Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    vib.vibrate(200);

    Intent mus = new Intent (this, Music.class);
    startActivity(mus);
 }

// handler for home button used on all screens
public void BackButton (View view) {

    MediaPlayer mMediaPlayer = MediaPlayer.create(this, R.raw.soundbackbutton) ;
    mMediaPlayer.start();

    Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    vib.vibrate(200);

    Intent mn = new Intent (this, Music.class);
    startActivity(mn);
 }

最佳答案

很简单。请按照以下步骤操作:-

  1. 添加一个搜索栏更改监听器。

    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {         
        int seeked_progess;
    
        @Override
        public void onProgressChanged(final SeekBar seekBar, int progress, boolean fromUser) {
    
            seeked_progess = progress;
            seeked_progess = seeked_progess * 1000;
    
            if (fromUser) {                 
            }
        }
    
        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
    
        }
    
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
    
        }
    });
    
  2. 现在在 if(fromUser) 中,您需要添加实现。

      if (fromUser) {
    
                Runnable mRunnable = new Runnable() {
    
                    @Override
                    public void run() {
                        int min, sec;
    
                        if (mediaPlayer != null /*Checking if the
                           music player is null or not otherwise it
                           may throw an exception*/) {
                            int mCurrentPosition = seekBar.getProgress();
    
                            min = mCurrentPosition / 60;
                            sec = mCurrentPosition % 60;
    
                            Log.e("Music Player Activity", "Minutes : "+min +" Seconds : " + sec);
    
                            /*currentime_mm.setText("" + min);
                            currentime_ss.setText("" + sec);*/
                        }
                        mHandler.postDelayed(this, 1000);
                    }
                };
                mRunnable.run();}
    
  3. 最后在 onStopTrackingTouch() 中添加这个

    @Override
     public void onStopTrackingTouch(SeekBar seekBar) {
         mediaPlayer.seekTo(seeked_progess);
        }
    });
    

注意:-

全局变量中的mHandler。 初始化如下。

Handler mHandler = new Handler();

其次,currentime_mmcurrenttime_ss 是显示搜索栏当前搜索时间的 TextView 。

最重要的是, 歌曲开始时不要忘记添加这些

seekBar.setProgress(0);// To set initial progress, i.e zero in starting of the song
seekBar.setMax(mediaDuration);// To set the max progress, i.e duration of the song

关于java - 修复我的 Android 音乐播放器上的搜索栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32296712/

相关文章:

java - Tomcat 新安装到 Eclipse 的问题

android - 如何仅以恒定间隔停止搜索栏的进度

android - 修改 Android seekbar 小部件以垂直操作

android - 如何在 Android 设备上安装 SQLite 可执行文件?

Android SeekBar 的 progressBackgroundTint 在 API v21 中没有效果

java - 如何将字符串数组翻译为另一种语言?

java - 在 fragment 中执行操作

java - 正则表达式正好 n 或 m 次

android - 从 fragment 调用 Activity 方法

android - 无法找到或加载主类 com.google.devtools.build.android.desugar.Desugar android studio