androidvolumeandroid-audiomanagerandroid-seekbar

Control seekbar not working to control volume


I'm newbie and I'm creating my first java app for android, and I'm having some difficulties, can you please help me?

I created a seekbar to control my audio volume, but it's not working.

Another point is that when I click play(executarSom) I can start the audio, but after pausing(pausarSom), if I try to play it again by clicking Play, it doesn't work, only if I open the application again.

MainActivity.java

package com.example.mediaplayer;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.SeekBar;

public class MainActivity extends AppCompatActivity {

    MediaPlayer mediaPlayer;
    private SeekBar seekVolume;
    private AudioManager audioManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.shhh);

    }

    public void inicializarseekBar(View view) {

        seekVolume = findViewById(R.id.seekBar2);

        // configurar audio manager
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

        //recuperar volume máximo
        int volumeMaximo = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);

        //recuperar volume atual
        int volumeAtual = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

        //configurar volume máximo
        seekVolume.setMax(volumeMaximo);

        //configurar volume atual
        seekVolume.setProgress(volumeAtual);

        //comfigurar o progresso atual do seekbar
        seekVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, i ,AudioManager.FLAG_SHOW_UI);

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    public void executarSom(View view){
        if (mediaPlayer != null) {
            mediaPlayer.setLooping(true);
            mediaPlayer.start();
        }

    }

   public void pausarSom(View view){
       if (mediaPlayer != null) {
           mediaPlayer.stop();

        }
    }

    public void pararSom(View view){
        if (mediaPlayer.isPlaying()){
            mediaPlayer.stop();
            mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.shhh);
            mediaPlayer.release();
        }
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();
        if (mediaPlayer != null && mediaPlayer.isPlaying()){
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    @Override
    protected void onStop(){
        super.onStop();
        if (mediaPlayer != null) {
            mediaPlayer.stop();
        }
    }
}

activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/seekVolume"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:onClick="executarSom"
    tools:context=".MainActivity">

    <ImageButton
        android:id="@+id/buttonStop"
        style="?attr/borderlessButtonStyle"
        android:layout_width="75dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:background="?attr/selectableItemBackgroundBorderless"
        android:clickable="true"
        android:onClick="pararSom"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/buttonPause"
        app:layout_constraintTop_toBottomOf="@+id/seekBar2"
        app:srcCompat="@drawable/stop" />

    <ImageButton
        android:id="@+id/buttonPlay"
        style="?attr/borderlessButtonStyle"
        android:layout_width="75dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_marginEnd="10dp"
        android:background="?attr/selectableItemBackgroundBorderless"
        android:clickable="true"
        android:onClick="executarSom"
        app:layout_constraintEnd_toStartOf="@+id/buttonPause"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintHorizontal_chainStyle="packed"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/seekBar2"
        app:srcCompat="@drawable/play" />

    <ImageButton
        android:id="@+id/buttonPause"
        style="?attr/borderlessButtonStyle"
        android:layout_width="75dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_marginEnd="10dp"
        android:background="?attr/selectableItemBackgroundBorderless"
        android:clickable="true"
        android:onClick="pausarSom"
        app:layout_constraintEnd_toStartOf="@+id/buttonStop"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/buttonPlay"
        app:layout_constraintTop_toBottomOf="@+id/seekBar2"
        app:srcCompat="@drawable/pause" />

    <SeekBar
        android:id="@+id/seekBar2"
        android:layout_width="280dp"
        android:layout_height="18dp"
        android:layout_marginTop="356dp"
        android:onClick="inicializarseekBar"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Solution

  • I found the solution for seekBar in @Chirag's answer in Using SeekBar to Control Volume in android?

    import android.app.Activity;
    import android.content.Context;
    import android.media.AudioManager;
    import android.os.Bundle;
    import android.widget.SeekBar;
    import android.widget.SeekBar.OnSeekBarChangeListener;
    
    public class TestExample extends Activity 
    {
        /** Called when the activity is first created. */
    
        private SeekBar volumeSeekbar = null;
        private AudioManager audioManager = null; 
    
        @Override
        public void onCreate(Bundle savedInstanceState) 
        {
            super.onCreate(savedInstanceState);
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            setContentView(R.layout.main);
            initControls();
        }
    
        private void initControls()
        {
            try
            {
                volumeSeekbar = (SeekBar)findViewById(R.id.seekBar1);
                audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
                volumeSeekbar.setMax(audioManager
                        .getStreamMaxVolume(AudioManager.STREAM_MUSIC));
                volumeSeekbar.setProgress(audioManager
                        .getStreamVolume(AudioManager.STREAM_MUSIC));   
    
    
                volumeSeekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() 
                {
                    @Override
                    public void onStopTrackingTouch(SeekBar arg0) 
                    {
                    }
    
                    @Override
                    public void onStartTrackingTouch(SeekBar arg0) 
                    {
                    }
    
                    @Override
                    public void onProgressChanged(SeekBar arg0, int progress, boolean arg2) 
                    {
                        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                                progress, 0);
                    }
                });
            }
            catch (Exception e) 
            {
                e.printStackTrace();
            }
        }