简体   繁体   中英

How to set wave height of WaveView according to SeekBar's progress?

GIF

Above GIF is current look of my music player.

The center layout is WaveView and front of that is a simple musical note vector-drawable .

I first tried to set Waveview progress according to SeekBar 's progress without any song playing to test it. And it worked perfectly fine (Seekbars current progress/100 which is 0.01 to 1.00 ).

Now what I want to do is set WaveView 's Water Level (height of water) according to song progress.

When song will play, the water level will be set from 0.0f to 1.0f and revealing the White Music note icon.

Note that the WaveView 's water level can only be set from 0.0f to 1.0f .

I tried multiple ways but could not solve this problem.

Here is my code which should return 0.01, 0.02 and so on ... :

this.runOnUiThread(new Runnable() {
    @Override
    public void run() {
        if (mainMediaPlayer != null) {
            currentDurationPosition = mainMediaPlayer.getCurrentPosition()/1000;
            songSeekBar.setProgress(currentDurationPosition+1);
            topSongTitle.setText(songsList.get(currentSongPosition).getName());
            songCircleProgress.setWaterLevelRatio(currentDurationPosition/mainMediaPLayer.getDuration());
        } else {
            Toast.makeText(MainActivity.this, "No song is playing now", Toast.LENGTH_SHORT).show();
        }
        handler.postDelayed(this, 1000);
    }
});

After rereading your code, I think I see two issues here:

first, your staticFloat initialisation:

private static float staticFloat = 1/100;

By doing this, you are actually doing an integer division, then converting it to a float. 1/100 in integer division equals to 0, so your float will always be 0.0f. To have the 0.01 value, you need to do

private static float staticFloat = 1/100f; // or 1f/100

This way you are dividing an int by a float, or the opposite, and it will have a floating result.

Secondly, your getWaterPosition function. You are returning 0 when progress is 0. In every other case, you are returning, well... 0 too.

Why? You are returning on each case

returnPosition = minusPosition - (minusPosition - staticFloat);

which is equivalent to:

returnPosition = minusPosition - minusPosition + staticFloat;

and again equivalent to:

returnPosition = staticFloat;

and as we've seen before, this would always be 0, or even 0.01f when you will fix it.

I guess you made some errors when coming with that formula. But won't it work by doing only something like return progress / 100f; ?

You can also add in your xml a max value to your seekbar, so it's never above 100 and you'll have your return between 0.0f and 1.0f

<SeekBar
    // initialisation
    android:max="100"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM