Vibration works fine, but sound does not on android - 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();
}
}

Related

Why is MediaPlayer doesn't start?

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

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";

Android MediaPlayer: Play Audio Resource in Raw Based on URI

The problem I am trying to solve is in an activity that needs to play back audio files. Most of the files will be user created (and saved into external storage), and therefore played with the following code (based on Google's example code):
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setDataSource(filename);
mPlayer.prepare();
mPlayer.start();
Some of the audio files, though, are going to be included with the app, are usually played with the following code:
MediaPlayer mPlayer = MediaPlayer.create(getBaseContext(), R.raw.filename);
mPlayer.prepare();
mPlayer.start();
The issue is that I would like to be able to play the audio files in the raw folder in the same way that I am playing the user created files since I don't necessarily know which will be needed. I tried tried to get the URI of the audio file in the raw folder and play it with the following code:
Uri uri = Uri.parse("android/resource://com.my.package/" + R.raw.filename);
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setDataSource(uri.toString());
mPlayer.prepare();
mPlayer.start();
But nothing happens. No error messages, no playing audio.
I outlined what I thought was the simplest solution, but I am willing to go another route if it accomplishes the task. Any assistance is greatly appreciated.
I've managed to get it working, here is the code I used.
mMediaPlayer = new MediaPlayer();
Uri mediaPath = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.filename);
try {
mMediaPlayer.setDataSource(getApplicationContext(), mediaPath);
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
I see two problems I see with your code. The first is that "android/resource" needs to become "android.resource"
The second is that setDataSource(String) won't work in this case due to the fact that you need context to use raw files as otherwise it tries to open the file incorrectly. (See the top answer in MediaPlayer.setDataSource(String) not working with local files)
final int[] song = {R.raw.letmeloveyou,R.raw.aarti,R.raw.answer};
final MediaPlayer mp = new MediaPlayer();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try {
if (true == mp.isPlaying()) {
mp.stop();
mp.reset();
Toast.makeText(getBaseContext(), "Again Playing", Toast.LENGTH_LONG).show();
mp.setDataSource(Result.this, Uri.parse("android.resource://" + getPackageName() + "/" + song[position]));
mp.prepare();
mp.start();
} else {
Toast.makeText(getBaseContext(), "Playing", Toast.LENGTH_LONG).show();
mp.setDataSource(Result.this, Uri.parse("android.resource://" + getPackageName() + "/" + song[position]));
mp.prepare();
mp.start();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(),e.toString(),Toast.LENGTH_LONG).show();
}
}
});
When I used toString() in Uri it failed, when I used direct Uri it played well.
Uri musicUri = Uri.parse("android.resource://" + context.getPackageName() + "/" + resourceID);
Log.d(TAG, "musicUri: " + musicUri);
mediaPlayer.setDataSource(context, musicUri);

Playing sounds regardless of device volume level

So on my 2.3 devices, I can play a sound with SoundPool or MediaPlayer at full volume, even if the device volume is set to 0/mute. It was my understanding that you had to manually get the device level and set it when you played back a sound.
This is how I want the behavior to work.
However, I now notice on my 4.0 device, that the sounds are automatically played at the device's set level, which I do not want!
Is this a difference between versions of the OS? If so, is there a way to ignore the devices volume? So even if it is muted, I can play a sound and have it be heard?
I can't go into why I need this feature, but I really really do.
Thanks!
I had a similar need for an alarm clock application. Here is the relevant code with comments regarding the volume.
This works on my HTC Rezound Android Version 4.0.3 when the sound profile is set to silent, when the alarm stream volume is manually set to zero and when the ringtone volume is set to zero.
Context context;
MediaPlayer mp;
AudioManager mAudioManager;
int userVolume;
public AlarmController(Context c) { // constructor for my alarm controller class
this.context = c;
mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
//remeber what the user's volume was set to before we change it.
userVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_ALARM);
mp = new MediaPlayer();
}
public void playSound(String soundURI){
Uri alarmSound = null;
Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
try{
alarmSound = Uri.parse(soundURI);
}catch(Exception e){
alarmSound = ringtoneUri;
}
finally{
if(alarmSound == null){
alarmSound = ringtoneUri;
}
}
try {
if(!mp.isPlaying()){
mp.setDataSource(context, alarmSound);
mp.setAudioStreamType(AudioManager.STREAM_ALARM);
mp.setLooping(true);
mp.prepare();
mp.start();
}
} catch (IOException e) {
Toast.makeText(context, "Your alarm sound was unavailable.", Toast.LENGTH_LONG).show();
}
// set the volume to what we want it to be. In this case it's max volume for the alarm stream.
mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, mAudioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM), AudioManager.FLAG_PLAY_SOUND);
}
public void stopSound(){
// reset the volume to what it was before we changed it.
mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, userVolume, AudioManager.FLAG_PLAY_SOUND);
mp.stop();
mp.reset();
}
public void releasePlayer(){
mp.release();
}
An easy and alternative way for playing music from raw folder;
try {
String uri = "android.resource://" + getPackageName() + "/" + R.raw.beep;
//Strign uri = "http://bla-bla-bla.com/bla-bla.wav"
Uri notification = Uri.parse(uri);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}

Categories

Resources