Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play mp3 file in raw folder as notification sound alert in android

Tags:

android

I am having my own audio file placed in raw folder inside resource folder.I want to set it as notification sound alert. how should i proceed

like image 517
Sando Avatar asked Jun 24 '11 06:06

Sando


People also ask

How do I play sound notifications?

Open your device's Settings app . Tap Accessibility. Sound Notifications. Tap Open Sound Notifications.


2 Answers

Please used below code when you get notification in BroadcastReceiver then call activity in that activity class used below code so play sound file.

mMediaPlayer = MediaPlayer.create(this, R.raw.sound1);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setLooping(true);
mMediaPlayer.start();

Happy Coding..

like image 137
Nikhil Avatar answered Oct 16 '22 18:10

Nikhil


This is often achieved using the MediaPlayer but that is not an ideal solution because it runs a little independently of notifications, and therefore will behave in unexpected ways for muting, blocking mode, and various other things. For consistency and compatibility, the sound should be played using the audio mechanism of notifications themselves. This can be accomplished by setting an appropriate URI, along the lines of:

NotificationCompat.Builder builder = new NotificationCompat.Builder(
    this).setSmallIcon(R.drawable.ic_myicon)
    .setContentTitle(title).setAutoCancel(true);
Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
                    + "://" + getPackageName() + "/raw/mymp3");
builder.setSound(alarmSound);
...
builder.setContentIntent(pendingIntent);
NotificationManager manager = (NotificationManager)
    getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(1, builder.build());

The key part is:

Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
                    + "://" + getPackageName() + "/raw/mymp3");

The mp3 file is stored in your /res/raw folder.

like image 21
Simon Avatar answered Oct 16 '22 16:10

Simon