Android MediaPlayer volume is very low ( already adjusted Volume ) - java

I m using the MediaPlayer to play one of the internal alarm ringtone.
i m using the setVolume(1.0f, 1.0f) to maximize the volume when the ringtone is played. but the ringtone doesn't play full volume ( when I compare it to playing the ringtone separately or through the built it android alarm)
here is my code
mediaPlayer.setDataSource(context, ringtoneUri);
mediaPlayer.setLooping(looping);
mediaPlayer.setVolume(1.0f, 1.0f);
mediaPlayer.prepare();
mediaPlayer.start();
I added the following permission android.permission.MODIFY_AUDIO_SETTINGS
( not sure if this is needed )
Any Idea why the mediaPlayer still won't play the sound at maximum?

Here is the solution I found.
AudioManager amanager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
int maxVolume = amanager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
amanager.setStreamVolume(AudioManager.STREAM_ALARM, maxVolume, 0);
MediaPlayer mediaPlayer= new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); // this is important.
mediaPlayer.setDataSource(context, ringtoneUri);
mediaPlayer.setLooping(looping);
mediaPlayer.prepare();
mediaPlayer.start();

I encountered the same issue, and then noticed this this in the MediaPlayer documentation:
While in the Prepared state, properties such as audio/sound volume, screenOnWhilePlaying, looping can be adjusted by invoking the corresponding set methods.
Calling setVolume after calling prepare fixes this, so that audio is played at max volume. Actually, according to the docs I just quoted, you should call setLooping after prepare as well:
mediaPlayer.setDataSource(context, ringtoneUri);
mediaPlayer.prepare();
mediaPlayer.setLooping(looping);
mediaPlayer.setVolume(1.0f, 1.0f);
mediaPlayer.start();

Since setAudioStreamType() is now deprecated you should use the method setAudioAttributes() instead. Below is the full example
var mediaPlayer: MediaPlayer = MediaPlayer()
fun playAudio(audioUrl: String) {
mediaPlayer.apply {
if (isPlaying) {
stop()
reset()
release()
}
}
mediaPlayer = MediaPlayer()
try {
mediaPlayer.apply {
setAudioAttributes(
AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.setUsage(AudioAttributes.USAGE_ALARM)
.build()
)
setVolume(2f,2f)
setDataSource(audioUrl)
prepare()
start()
}
} catch (e: IOException) {
e.printStackTrace()
}
}

Related

How can I stop youtube music?

I am using AudioManager in order to make this work.
This is what I have done:
private AudioManager isPlaying = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
if(isPlaying.isMusicActive()) {
isPlaying.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
} else{
Toast.makeText(getApplicationContext() , "There is no music playing..", Toast.LENGTH_SHORT).show();
}
I want to stop the music playing from youtube or any other app. In addition, how can I pause it and resume it?
In Stop MediaPlayer when an other app play music
A person answer
AudioManager manager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
if(manager.isMusicActive())
{
// do something - or don't
}

How to play a WAV file loaded from Assets folder in Android?

I'm trying to play a .wav audio in Android from assets folder.
The problem is that there is no error but the audio isn't playing.
Here's my code
AssetFileDescriptor afd = null;
try {
afd = getAssets().openFd("success.wav");
player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
player.setLooping(false);
player.prepare();
player.start();
} catch (IOException e) {
e.printStackTrace();
}
Your code is ok, i checked, its working.
Please ensure the \assets folder is placed
correctly(\app\src\main\assets)
Check your device volume level.
Play success.wav in PC media player and ensure it is audible.
Note:
Using device volume controls:
setVolumeControlStream(AudioManager.STREAM_MUSIC);
If your app is media related, use setVolumeControlStream API at your onResume() of activity or fragment and use device volume hard keys to increase/decrease volume. This set the application to only modify stream_music volume /media volume, otherwise it will modifiy ring volume.
Ref:https://developer.android.com/guide/topics/media-apps/volume-and-earphones
Did You try this?
MediaPlayer mediaPlayer = null;
public void playSound(final Context context, final String fileName) {
mediaPlayer = new MediaPlayer();
try {
AssetFileDescriptor afd = context.getAssets().openFd(fileName);
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mediaPlayer.prepare();
} catch (final Exception e) {
e.printStackTrace();
}
mediaPlayer.start();
}
}

Android Mediaplayer Selecttrack method fails

I am using the mediaplayer feature on Android. I basically have songs in the raw folder and I would just like to change to a new track but it fails. One music file plays and then I press a button after or during the music playing to skip to a random track but it fails.
Current code
mediaplayer.stop();
try {
mediaplayer.prepareAysn();
mediaPlayer.selectTrack(randomtrack_num - 1);
}
catch(Exception e){}
mediaplayer.start();
The error that I receive:
MediaPlayer: start called in state 64
MediaPlayer: error (-38, 0)
MediaPlayer: Error (-38,0)
I tried this without mediaplayer.stop() and still included mediaplayer.start() at the end and it would just replay the same track again.
Am I missing something?
Please let me know.
2nd Approach
After reading the document I realized this can only be done in the prepared state which I assume in my second approach it should work but it is not.
mediaPlayer.stop();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer mp) {
try{
mp.selectTrack(randomtrack_num - 1);
}catch(Exception e){}
mp.start();
}
});
mediaPlayer.prepareAsync();
I get this error:/MediaPlayer: Should have subtitle controller already set
Basically the same track plays again and it does not go to the selected track.
You are calling mediaplayer.start() in wrong state. Firstly read this documentation:
https://developer.android.com/reference/android/media/MediaPlayer.html
You will have a better idea of correct implementation.
EDITED:
String[] url ; // initiliaze your URL array here
MediaPlayer myMediaPlayer = new MediaPlayer();
myMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
myMediaPlayer.setDataSource(url[0]);
myMediaPlayer.prepareAsync(); // might take long! (for buffering, etc)
} catch (IOException e) {
Toast.makeText(this, "mp3 not found", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
//mp3 will be started after completion of preparing...
myMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer player) {
player.start();
}
});
Playing different track after completions
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp)
{
myMediaPlayer.reset();
/* load the new source */
myMediaPlayer.setDataSource(url[position]);//select the path according to your need
/* Prepare the mediaplayer */
myMediaPlayer.prepareAsync();
}

Error with MediaPlayer

I am trying to make music play in my app and have a song play after the first one has finished but i get some errors that i cannot resolve any help?
public class Music {
int count;
String[] titles = new String[] { "title1.mp3", "title2.mp3", "title3.mp3", "title4.mp3" };
public void GameMusic(){
count = 0;
MediaPlayer mp = MediaPlayer.create(this, R.raw.title1);
mp.start();
}
void onCompletion(MediaPlayer mp){
mp.stop();
if (count == titles.length -1) {
count = 0;
}
mp.setDataSource(titles[count]);
count++;
mp.prepare();
mp.start();
}
}
The errors are on:
MediaPlayer mp = MediaPlayer.create(this, R.raw.music);
(The method create(Context, int) in the type MediaPlayer is not applicable for the arguments (Music, int)
mp.setDataSource(titles[count]);
(Unhandled exception type IOException)
mp.prepare();
(Unhandled exception type IOException)
Any help would be appreciated.
Well the errors might be a little cryptic but they are self-explanatory.
You need to pass a Context to GameMusic() and use it to initialize MediaPlayer:
public void GameMusic(Context context){
count = 0;
MediaPlayer mp = MediaPlayer.create(context, R.raw.title1);
mp.start();
}
this only works if the class (in this case Music) extends Context, so you need to provide a Context another way.
And in onCompletion() use a try-catch block to handle the IOException:
try {
mp.setDataSource(titles[count]);
count++;
mp.prepare();
mp.start();
}
catch(IOException e) {
// Do something when MediaPlayer fails
}
Your Music Class is just a class and not an activity and hence the this passes an object and not a context. If this is your only music player class then you need it to extend Activity else you need to pass a context to it.
public void GameMusic(Context context){
count = 0;
MediaPlayer mp = MediaPlayer.create(context, R.raw.title1);
mp.start();
}
And for the other two exceptions, it states that the exceptions are unhandled. so you need to use a Try-Catch block the handle the uncaught IOException.
That should solve all the errors that you are getting now.
when setting the datasource to Mediaplayer try to use absolutepath of the music file
if it is stored in sd-card means ..try this
String ExternalStorageDirectoryPath = Environment.getExternalStorageDirectory()
.getAbsolutePath();
mp.setDataSource(ExternalStorageDirectoryPath +"/"+titles[count]);
after calling the
mp.prepare();
implement the onpreparedlistner ,after get the notification for this then start the mediaplayer
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
and handle the all kind of exception, so that u can easily track the issues.

MediaPlayer Volume issue-AudioStream issue

I am trying to provide a custom beep sound when I get a message in my Application. This beep sound should respect the master phone notification volume level(not ringer volume). Which means if phone notification vol =3/10 , then beep intensity should be 3/10.
I am not able to achieve this,
AudioManager audioMan = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
int volume;
if (mPlayer == null) {
mPlayer = MediaPlayer.create(context, R.raw.mytone);
}
if (mPlayer.isPlaying()) {
mPlayer.stop();
mPlayer.release();
mPlayer = MediaPlayer.create(context, R.raw.mytone);
}
volume = audioMan.getStreamVolume(AudioManager.STREAM_NOTIFICATION);
mPlayer.setVolume(volume, volume);//this doesn't work for me, beep sound is taking media player volume by default.
mPlayer.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer player, int what, int extra) {
player.stop();
player.reset();
return true;
}
});
if (mVibrator == null)
mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
mVibrator.cancel();
Can you please share your knowledge and give me directions. Thank you.
It looks like you are playing your sound over the music stream going by the reference to AudioManager.STREAM_MUSIC. Modifying the volume level modifies the level for everything played on that stream. This is why music/media playback is 'mucked up'.
If you want to use the ringer stream (and its volume setting) then you should be using AudioManager.STREAM_RING instead. You say you've tried this but the code snippet you've given just adjusts the volume - you've not shown how you create and configure your MediaPlayer before you ask it to play your sound.
You've got to select the appropriate stream when you set up your MediaPlayer instance. As I've successfully used different streams in the kind of scenario you are describing, this is where your problem lies. To select the audio stream over which your custom beep is played, use setAudioStream on your MediaPlayer instance like this:
// Get a reference to the MP3 file to play
AssetFileDescriptor afd = getContext().getResources().openRawResourceFd(R.raw.my_mp3);
// Create the media player
MediaPlayer mediaPlayer = new MediaPlayer();
// Give it the MP3 you want played
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
// Set the audio stream to play over
mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
// Now play the sound
mediaPlayer.prepare();
mediaPlayer.start();
Its good practice to offer your users the option to choose the stream for themselves - in addition to the music and ringer streams there are alarm and notification streams, each with an independent volume level (there are others too, but these are the core ones). Have a look at the Android documentation on AudioManager here.

Categories