Reputation: 23
I am trying to add sound while vibration.
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"Get Ready Bus is Near",Toast.LENGTH_LONG).show();
Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(2000);
}
Vibration Applied successfully, but how to add sound while phone vibrate?
Upvotes: 1
Views: 569
Reputation: 3366
You can easily do that using MediaPlayer
.
Firstly, Create an instance of MediaPlayer
class:
MediaPlayer mediaPlayer = new MediaPlayer();
Then, set the source file, in order to this, firstly place the audio file in res/raw
folder of your Project
directory, then use this code:
mediaPlayer.setDataSource(context, Uri.parse("android.resource://{package name}/res/raw/{audio file name}");
Then play that file using this code:
mediaPlayer.prepare();
mediaPlayer.start();
Keep in mind that you have to put this code in try | catch
block.
Now your whole code will be this:
@Override
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.
mediaPlayer.setDataSource(context, Uri.parse("android.resource://{package name}/res/raw/{audio file name}"); // Fill the information accordingly.
mediaPlayer.prepare();
// playing audio.
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
Upvotes: 1