Why is MediaPlayer doesn't start? - android

I have a sound that is supposed to start when the activity starts onCreate because this is an alarm. THe problem is, the sounds doesn't start. I've checked my volume, it's on.
This is the code for the media player:
String tone = intent.getStringExtra("reminderTone");
MediaPlayer mPlayer = new MediaPlayer();
try {
Log.d("log", "try");
if (tone != null && !tone.equals("")) {
Log.d("log", "tone is not null");
Uri toneUri = Uri.parse(tone);
if (toneUri != null) {
Log.d("log", "mediaplayer starts");
mPlayer.setDataSource(this, toneUri);
mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mPlayer.setLooping(true);
mPlayer.prepare();
mPlayer.start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
and this is the log output
08-09 10:55:33.316 20706-20706/? D/log﹕ try
08-09 10:55:33.317 20706-20706/? D/log﹕ tone is not null
08-09 10:55:33.317 20706-20706/? D/log﹕ mediaplayer starts
I've already checked "reminderTone" there is a String URI in it.
This is how the String URI looks like. "android.media.Ringtone#ab91882"
I used another source of sound to test, and this one works:
//play ringtone
final MediaPlayer sounds = MediaPlayer.create(this, R.raw.sample);
sounds.start();
Do you guys know what's wrong with this?

Context appContext = getApplicationContext();
MediaPlayer resourcePlayer = MediaPlayer.create(appContext, R.raw.my_audio);
MediaPlayer filePlayer = MediaPlayer.create(appContext, Uri.parse("file:///sdcard/localfile.mp3"));
MediaPlayer urlPlayer = MediaPlayer.create(appContext, Uri.parse("URL"));
MediaPlayer contentPlayer = MediaPlayer.create(appContext, Settings.System.DEFAULT_RINGTONE_URI);
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource("/sdcard/test.3gp");
mediaPlayer.prepare();

You need to check your URI, make sure you use the proper URI.
Note: URI string is different for every storage media that you are
calling, in my example I am assuming that you are looking for the
Music inside your raw folder.
int i = R.raw.sample; // we assume that we want to get the URI of our sound from our RAW folder.
String uri = android.resource://com.example.myproject/" + i;
For playing the music you can use this simple method
MediaPlayer player = null;
public void playMusic(int i) throws RemoteException {
try {
if (player == null)
player = new MediaPlayer();
player.reset(); // optional if you want to repeat calling this method
player.setDataSource(getApplicationContext(), uri);
player.prepare();
player.start();
} catch (IOException e) {
e.printStackTrace();
}
}
The full working example can be downloaded here : Music Player Tutorial

Related

Vibration works fine, but sound does not on android

I want to apply a vibration and sound at the same time.
The vibration works fine, but the sound does not work.
I am getting the sound as an mp3.
How would I solve this issue?
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"Get Ready Bus is Near",Toast.LENGTH_LONG).show();
// Initializing instance of Vibrator.
Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
// Initializing instance of MediaPlayer.
MediaPlayer mediaPlayer = new MediaPlayer();
// Starting Vibration
v.vibrate(2000);
try {
// Setting the source of audio file.
//String path = "android.resource://"+"com.example.myproject"+"/raw/"+audioFile;
mediaPlayer.setDataSource(context,Uri.parse("android.resource://"+"com.example.fahad.finalyearprojectlayout"+"/raw/"+"sound.mp3")); // Fill the information accordingly.
mediaPlayer.prepare();
// playing audio.
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
This is a different, shorter way for how you can create a mediaPlayer:
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.sound);
mp.start();
So now, this is what your code should look like. You do not need the try or catch blocks:
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.sound);
mp.start();
v.vibrate(2000);
Try starting the mediaPlayer before you start the vibration. If this doesn't work, make sure that you have the sound turned on in your device. If there are still problems, post the new problem below. However, if you have enabled sounds and vibrations for your app, I do not see why it should not work.
this code is working for me
public void playNotificationSound() {
try {
Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
+ "://" + mContext.getPackageName() + "/raw/sound");
Ringtone r = RingtoneManager.getRingtone(mContext, alarmSound);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}

Unable to getPackageName() using MediaPlayer in fragment

While using fragment I'm trying to get audio file from raw folder like this:
mediaPlayer = MediaPlayer.create(this, getResources().getIdentifier(audioFile, "raw", getPackageName()));
I'm getting Cannot resolve method 'getPackageName()' error. How to solve this?
I was able to solve it by writing this code:
String path = "android.resource://"+"com.example.myproject"+"/raw/"+audioFile;
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(getActivity(), Uri.parse(path));
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}

Play short sound without interrupting playing music

I play music in my app using MediaPlayer. But music interrupts when I playing another sound (duration of sound is about 1 sec). The interruption is short, only a few ms, but it disturbs me.
What should I do to avoid this interruption?
UPDATE:
Here is code that I use to play short sounds:
private final Map<Integer,MediaPlayer> mediaPlayers = new HashMap<Integer,MediaPlayer>();
void playSound(int resId, boolean looping) {
MediaPlayer mediaPlayer = mediaPlayers.get(resId);
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayers.remove(resId);
}
try {
mediaPlayer = MediaPlayer.create(context, resId);
if (mediaPlayer == null){
throw new RuntimeException("Can't create MediaPlayer");
}
mediaPlayer.setLooping(looping);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.start();
} catch (IllegalStateException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
mediaPlayers.put(resId, mediaPlayer);
}
UPDATE2:
I solved the problem. The problem was that the short sound was in mp3 format, but all the other sounds in my app were in ogg format. So I converted this sound in ogg format and the music is no longer interrupted.

What is wrong with my music player for Android ???? It's going to CATCH in the try\catch statement every single time WHY?

I'm done my Android app, just need to add some looping background music. Here is my method for playing the song
public void playAudio(){
path = "android.resource://" + getPackageName() + "/" + R.raw.music1;
//set up MediaPlayer
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(path);
mp.prepare();
mp.setLooping(true);
mp.setVolume(100, 100);
mp.start();
} catch (Exception e) {
e.printStackTrace();
Log.d("NOTE WORKEING","NOT WORKING");
}
}
It's not working....It's going to catch everytime, and I don't know why. Please help me. Music1 is an mp3 file.
Thank you
Make sure your music1 file is in a Android playable Android format.
Then just use this code:
MediaPlayer mediaPlayer = MediaPlayer.create(YourActivity.this, R.raw.music1);
try {
mediaPlayer.setLooping(true);
mediaPlayer.setVolume(100, 100);
mediaPlayer.start();
}
catch (Exception e) {
e.printStackTrace();
Log.d("NOT WORKEING","NOT WORKING");
}
You don't even need to call prepare() method.
I tested it with an mp3 file and it works perfectly.
If #Squonk's answer does not work, then the problem has to do with trying to start the music file before the MediaPlayer has prepared it. Try changing the MediaPlayer's start code to the following:
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
start();
}
});
Let me know if this helps, I have a good amount of experience with the MediaPlayer class and can help you troubleshoot.
Using mp.setDataSource(path) requires a valid filesystem path or URL.
In your case, path is a string representation of a Uri in which case you need to use a different approach.
Try setDataSource(Context context, Uri uri). You'll obviously need to provide a valid Context and parse your path variable into a Uri. Example...
mp.setDataSource(getApplicationContext(), Uri.parse(path));
Also change the path to...
path = "android.resource://" + getPackageName() + "/raw/music1";

How to see the tittle/artist of a radio audio that is being played with MediaPlayer?

I made a program that connects to a radio and plays its audio using MediaPlayer. I want to print the artist, song title ... but I do not know how.
I tried to do this with MediaStore.Audio.Media.ARTIST, the but it didn't work, because I can't "link" the uri with the MediaStore, so when I used this command it searched in my SD target for music.
After that, I tried to do this with MetaMediadataRetriever with:
private void play() {
textView.setText("Conectando con la radio......");
Uri myUri = Uri.parse("http://streamingraddios.com:9169");
try {
if (mp == null) {
this.mp = new MediaPlayer();
} else {
mp.stop();
mp.reset();
}
mp.setDataSource(this, myUri);
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
// mmr.setDataSource(this, myUri);
//String ton= mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setOnBufferingUpdateListener(this);
mp.setOnErrorListener(this);
mp.prepareAsync();
Log.d(TAG, "LoadClip Done");
} catch (Throwable t) {
Log.d(TAG, t.toString());
}
}
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
textView.setText("");
textView.setText("Hola: " +ton);
}
But the application doesn't respond anymore (without closing the app) when connect with the URI with the variable mediametadataretriever . I think the problem is "context", do anyone know what is it? I don't know how to inicialize this variable.
Anyone can help me? Thanks you a lot.
Try
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
mmr.setDataSource(myContext, myUri)
String albumName = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM);
etc.
needs api 10 though

Categories

Resources