Reputation: 339
I created a music player app and I want to set the volume up/down programmatically. I want to implement two Button
s to increase/decrease the volume and set to the media player.
Activity:
control = (ImageView) findViewById(R.id.control);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
control.setOnClickListener(pausePlay);
control.setBackgroundResource(R.drawable.pause);
control id is my play and pause button :
{
// TODO Auto-generated method stub
// TODO Auto-generated method stub
if (playPause) {
control.setBackgroundResource(R.drawable.play);
if (mediaPlayer.isPlaying())
mediaPlayer.pause();
media.stop();
intialStage = false;
playPause = false;
} else {
control.setBackgroundResource(R.drawable.pause);
if (intialStage) {
new Player()
.execute("http://streaming.shoutcast.com/MUKILFMRADIO");
} else {
if (!mediaPlayer.isPlaying())
mediaPlayer.start();
}
playPause = true;
}
}
Layout:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:id="@+id/control1"
android:layout_margin="10dp"
android:layout_gravity="center"
android:background="@drawable/decrement"
android:layout_above="@+id/latestAddedSongs"
android:layout_alignEnd="@+id/musicArtistName" />
<ImageView
android:layout_width="70dp"
android:layout_height="70dp"
android:id="@+id/control"
android:layout_margin="10dp"
android:layout_gravity="center"
android:background="@drawable/play"
android:layout_above="@+id/latestAddedSongs"
android:layout_alignEnd="@+id/musicArtistName" />
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:id="@+id/control2"
android:layout_margin="10dp"
android:layout_gravity="center"
android:background="@drawable/increment"
android:layout_above="@+id/latestAddedSongs"
android:layout_alignEnd="@+id/musicArtistName" />
</LinearLayout>
Upvotes: 27
Views: 77357
Reputation: 301
fellow coders. I have tried to make the code as simple as possible as far as I can. I hope this is helpful for someone. Have a nice day!
I am using: Android Studio 4.2.2 Build #AI-202.7660.26.42.7486908, built on June 24, 2021 Runtime version: 11.0.8+10-b944.6842174 amd64 VM: OpenJDK 64-Bit Server VM by N/A Windows 10 10.0
For the MainActivity.java, here is the code.
package com.tutorial.android.mediaplayertest;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private MediaPlayer mediaPlayer;
private AudioManager audioManager;
private Button play, pause, decVolume, incVolume;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// I want my media player instantiated as soon as the app starts
mediaPlayer = MediaPlayer.create(this, R.raw.test);
// play button
play = findViewById(R.id.play_button);
play.setOnClickListener(view -> {
Toast.makeText(this, "Music Start", Toast.LENGTH_SHORT).show();
mediaPlayer.start();
});
// pause button
pause = findViewById(R.id.pause_button);
pause.setOnClickListener(view -> {
Toast.makeText(this, "Pause", Toast.LENGTH_SHORT).show();
mediaPlayer.pause();
});
audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
// volume down button
decVolume = findViewById(R.id.volume_down);
decVolume.setOnClickListener(view -> {
Toast.makeText(this, "Volume down", Toast.LENGTH_SHORT).show();
audioManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND);
});
// volume up button
incVolume = findViewById(R.id.volume_up);
incVolume.setOnClickListener(view -> {
Toast.makeText(this, "Volume up", Toast.LENGTH_SHORT).show();
audioManager.adjustVolume(AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND);
});
}
}
In case of activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/play_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play" />
<Button
android:id="@+id/pause_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pause" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/volume_down"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-" />
<Button
android:layout_marginLeft="16dp"
android:id="@+id/volume_up"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+" />
</LinearLayout>
</LinearLayout>
Upvotes: 1
Reputation: 738
Create an object for audio manager
AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
Button upButton = (Button) findViewById(R.id.upButton);
upButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//To increase media player volume
audioManager.adjustVolume(AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND);
}
});
Button downButton = (Button) findViewById(R.id.downButton);
downButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//To decrease media player volume
audioManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND);
}
});
The above example used Button label
for volume up and down code
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
int action = event.getAction();
int keyCode = event.getKeyCode();
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
if (action == KeyEvent.ACTION_DOWN) {
audioManager.adjustVolume(AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND);
}
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (action == KeyEvent.ACTION_DOWN) {
audioManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND);
}
return true;
default:
return super.dispatchKeyEvent(event);
}
}
Upvotes: 57
Reputation: 497
This code will set the volume 100 instantly with no feedback to the user when buttonSES is pressed.
public void perform_actionSES(View v) {
Button buttonSES = (Button) findViewById(R.id.buttonSES);
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 100, 0);
}
Upvotes: 4
Reputation: 11
AudioManager aManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
Button buttonUp= (Button) findViewById(R.id.upButton);
buttonUp.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
enter code here
//To increase media player volume
`enter code here`aManager.adjustVolume(AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND);
}
});
Button downButton = (Button) findViewById(R.id.downButton);
buttondown.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
aManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND);
}
});
Upvotes: 0
Reputation: 156
if your type is AudioManager.STREAM_MUSIC: use this code ,follow phone volume button
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
audio.adjustStreamVolume(
AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_RAISE,
AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
audio.adjustStreamVolume(
AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_LOWER,
AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
return true;
default:
break;
}
return super.onKeyDown(keyCode, event);
}
Upvotes: 6
Reputation: 6480
Below code worked great
There are several streams available in Android using which audio can be managed
/** The audio stream for phone calls */
public static final int STREAM_VOICE_CALL = AudioSystem.STREAM_VOICE_CALL;
/** The audio stream for system sounds */
public static final int STREAM_SYSTEM = AudioSystem.STREAM_SYSTEM;
/** The audio stream for the phone ring */
public static final int STREAM_RING = AudioSystem.STREAM_RING;
/** The audio stream for music playback */
public static final int STREAM_MUSIC = AudioSystem.STREAM_MUSIC;
/** The audio stream for alarms */
public static final int STREAM_ALARM = AudioSystem.STREAM_ALARM;
/** The audio stream for notifications */
public static final int STREAM_NOTIFICATION = AudioSystem.STREAM_NOTIFICATION;
/** @hide The audio stream for phone calls when connected to bluetooth */
public static final int STREAM_BLUETOOTH_SCO = AudioSystem.STREAM_BLUETOOTH_SCO;
/** @hide The audio stream for enforced system sounds in certain countries (e.g camera in Japan) */
public static final int STREAM_SYSTEM_ENFORCED = AudioSystem.STREAM_SYSTEM_ENFORCED;
/** The audio stream for DTMF Tones */
public static final int STREAM_DTMF = AudioSystem.STREAM_DTMF;
/** @hide The audio stream for text to speech (TTS) */
public static final int STREAM_TTS = AudioSystem.STREAM_TTS;
Depending on your need you can change the stream here is STREAM_MUSIC example :
You can get constant value using refelction from AudioSytem class:
private int getStreamType(String streamName) {
final String streamSourceClassName = "android.media.AudioSystem";
int streamType = 0;
try {
streamType = (int) Class.forName(streamSourceClassName).getDeclaredField(streamName).get(null);
} catch (ClassNotFoundException | IllegalAccessException | NoSuchFieldException e) {
e.printStackTrace();
}
return streamType;
}
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
seekbar.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int newVolume, boolean b) {
textview.setText("Media Volume : " + newVolume);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, newVolume, 0);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {}
});
Upvotes: 9
Reputation: 3201
Try below code
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
seekbar.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int newVolume, boolean b) {
textview.setText("Media Volume : " + newVolume);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, newVolume, 0);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {}
});
Upvotes: 31
Reputation: 383
Following up on solution of jesu, if you want to change volume within Service instead of Activity, replace:
AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
with:
AudioManager audioManager;
audioManager = (AudioManager) YourServiceName.this.getSystemService(Context.AUDIO_SERVICE);
Upvotes: 5