android - 搜索栏和媒体播放器以及轨道的时间

标签 android media-player seekbar

在我的媒体播放器 (mp3) 中有一个搜索栏。要播放下一首歌曲,我使用以下逻辑:

if (seek bar progress == mediaplayerObject.getDuration())

如果是 播放下一首歌曲

但是这个条件不起作用,因为在完整的搜索栏进度和 mediaplayerObject.getDuration() 值之间有一个小的 mili 秒差距,差异不是静态的,它会改变。我认为这是因为处理时间延迟。如果我可以使用像 if seek bar progress is 100% 这样的条件,我可以使用它,但我试过它似乎不起作用

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;

public class AndroidMediaPlayerExample extends Activity {

    private MediaPlayer mediaPlayer;
    public TextView songName, duration;
    private double timeElapsed = 0, finalTime = 0;
    private int forwardTime = 2000, backwardTime = 2000;
    private Handler durationHandler = new Handler();
    private SeekBar seekbar;
    private Field[] fields;
    private String name;
    private int resourceID;
    private List<String> songNames;
    private int nameIntRandom;

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

        //set the layout of the Activity
        setContentView(R.layout.activity_main);
        songNames = new ArrayList();
        //initialize views
        initializeViews();



        seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            //  seekBar.setMax(mediaPlayer.getDuration());

                System.out.println("progress"+ (progress));
                System.out.println("progress final - "+ finalTime);

                if(progress == finalTime){
                    System.out.println("progress 100 compleated ");
                }

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }


    public void initializeViews(){
        listRaw();
        songName = (TextView) findViewById(R.id.songName);

        nameIntRandom = Integer.parseInt(songNames.get(2));


        mediaPlayer = MediaPlayer.create(this, nameIntRandom);
        finalTime = mediaPlayer.getDuration();


        duration = (TextView) findViewById(R.id.songDuration);
        seekbar = (SeekBar) findViewById(R.id.seekBar);
        songName.setText("Sample_Song.mp3");

        seekbar.setMax((int) finalTime);
        seekbar.setClickable(false);
    }

    // play mp3 song
    public void play(View view) {
        System.out.println("AndroidMediaPlayerExample play");
        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 remaing
            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);
        }

    }

    public void listRaw() {

        fields = R.raw.class.getFields();
        for (int count = 0; count < fields.length; count++) {
            Log.i("Raw Asset: ", fields[count].getName());

            System.out.println("length .... " + fields[count].getName());

            try {
                System.out.println("trytrytrytry");
                resourceID = fields[count].getInt(fields[count]);
                System.out.println("resourceIDresourceID " + resourceID);
                name = String.valueOf(resourceID);
                songNames.add(name);
                System.out.println("songNames.size();" +songNames.size());
                songNames.size();

            } catch (IllegalAccessException e) {
                e.printStackTrace();
                System.out.println("catch" + e);
            }
        }

        System.out.println("resourceIDresourceID---------lastone " + resourceID);

        System.out.println("resourceIDresourceID---------set " + fields.toString());
    }


    // 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);
        }
    }

}

目前 mp3 arraylist id 是硬编码的

此处为 XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:background="#333333"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

    <TextView
        android:id="@+id/songName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="songName" />

    <ImageView
        android:id="@+id/mp3Image"
        android:layout_width="match_parent"
        android:layout_height="200dp"
         android:padding="30dp"
        android:src="@drawable/music"
        android:background="#ffffff"
        android:layout_margin="30dp" />

    <TextView
        android:id="@+id/songDuration"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="songDuration" />

    <SeekBar
        android:id="@+id/seekBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="30dp"
        android:gravity="center_horizontal"
        android:orientation="horizontal" >

        <ImageButton
            android:id="@+id/media_rew"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14dp"
            android:onClick="rewind"
            android:src="@android:drawable/ic_media_rew" />

        <ImageButton
            android:id="@+id/media_pause"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14dp"
            android:onClick="pause"
            android:src="@android:drawable/ic_media_pause" />

        <ImageButton
            android:id="@+id/media_play"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14dp"
            android:onClick="play"
            android:src="@android:drawable/ic_media_play" />

        <ImageButton
            android:id="@+id/media_ff"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14dp"
            android:onClick="forward"
            android:src="@android:drawable/ic_media_ff" />
    </LinearLayout>

</LinearLayout>

最佳答案

找到答案了,下面我计算timeElapsed,设置seekbar进度,计算剩余时间&显示已经播放的时间分秒

我用的是这个方法

Ps:2015 年完成的,没有时间审查代码,但解释我做了什么。

Runnable - 此接口(interface)旨在为希望在 Activity 时执行代码的对象提供通用协议(protocol)。 Activity 仅意味着线程已启动且尚未停止。

变量 -

  1. timeElapsed - 已播放的剪辑时间
  2. finalTime - 相关媒体播放器剪辑对象的时间
  3. duration - 我用来以分钟和秒为单位显示 timeElapsed 的字符串
  4. timeRemaining - 播放剪辑的剩余时间

.

    private Runnable updateSeekBarTime = new Runnable() {
            public void run() {

                //get current position
                timeElapsed = mediaPlayer.getCurrentPosition();

                //set seekbar progress using time played
                seekbar.setProgress((int) timeElapsed);

                //set time remaining in minutes and seconds 
                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))));

                //holding time for 100 miliseconds
                durationHandler.postDelayed(this, 100);
            }
        };

所以我可以检查 timeRemaining == 0

是的,媒体播放器中有一个方法 mediaPlayer.isPlaying() <--- 但我没有使用它

关于android - 搜索栏和媒体播放器以及轨道的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35027321/

相关文章:

android - Android 应用程序的 Beta 测试人员如何在同一设备上同时安装生产和 Beta 应用程序?

android - 改造 http 缓存控制检查发回缓存,即使它已过时并再次进行网络调用

android - android :windowSoftInputMode attribute的Java方法

android - 安卓中的 SeekBar 和媒体播放器

android - 当我尝试引用一首歌曲时,Eclipse 中的 MediaPlayer 错误

android - 如何与自定义媒体播放器一起显示搜索栏

java - MediaPlayer-javaFX 中的简单 URI 和本地路径使用

android - SeekBar 可绘制对象在被适配器重用后未绘制

android - 对话框中的控制音量 seekBar (AsyncTask)

android - 在 Android 中将文本作为 SeekBar 的背景