My app plays an alarm. In the Android Sound settings, this sound is controlled by the "Ring volume" slider and not the "Alarm volume" slider. How can I change the sound to be controlled by the "Alarm volume"?
public void doAlarm(){
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
r = RingtoneManager.getRingtone(getApplicationContext(), notification);
if (!r.isPlaying())
r.play();
}
I have tried using setAudioAttributes, but the result was that the "Media Volume" slider controlled the volume:
public void doAlarm(){
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), notification);
mp.setAudioAttributes(new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_ALARM).build());
mp.setLooping(true);
mp.start();
}
What am I missing?
I have found a solution: not using the .create() method. Instead use .setDataSource() and .prepare(). Code below:
public void ringAlarm() {
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null) {
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
}
if (alarmUri == null) {
Log.e("ringAlarm" , "alarmUri null. Unable to get default sound URI");
return;
}
MediaPlayer mp = new MediaPlayer();
// This is what sets the media type as alarm
// Thus, the sound will be influenced by alarm volume
mp.setAudioAttributes(new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ALARM).build());
try {
mp.setDataSource(getApplicationContext(), alarmUri);
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
}
// To continuously loop the alarm sound
mp.setLooping(true);
mp.start();
}
Related
Hello friends i am creating mp3 player application my application is successfully build i want implement click event notification when user goes on background they control media from notification panel my notification also build successfully but problem is that how control music and change image on notification .addaction() when user click on pause the image change to play and when song is play image back change to pause and media player is also and i am also want get songs title, and artist here my code you can easily understand!
public void play(int songindex) {
song = songList.get(songindex);
try {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
Uri uri = Uri.parse("file:///" + song.getGetpath());
mediaPlayer = MediaPlayer.create(mContext, uri);
title.setText(song.getTitle());
artist.setText(song.getArtist());
notificationTitleText=title.getText();
notificationDescText=artist.getText();
handler = VisualizerDbmHandler.Factory.newVisualizerHandler(getApplicationContext(), mediaPlayer);
audioVisualization.linkTo(handler);
mediaPlayer.start();
seekBar.setProgress(0);
seekBar.setMax(100);
updateProgressBar();
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
play.setVisibility(View.GONE);
pause.setVisibility(View.VISIBLE);
play_main.setVisibility(View.GONE);
pause_main.setVisibility(View.VISIBLE);
Animation aniRotate = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate);
rotate.startAnimation(aniRotate);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
if (checked) {
mediaPlayer.setLooping(true);
mediaPlayer.start();
} else if (isShuffle) {
// shuffle is on - play a random song
Random rand = new Random();
currentSongIndex = rand.nextInt((songList.size() - 1) - 0 + 1) + 0;
play(currentSongIndex);
} else {
// no repeat or shuffle ON - play next song
if (currentSongIndex < (songList.size() - 1)) {
play(currentSongIndex + 1);
currentSongIndex = currentSongIndex + 1;
} else {
// play first song
play(0);
currentSongIndex = 0;
}
}
}
});
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "" + e, Toast.LENGTH_SHORT).show();
}
}
public void shownotification(){
Bitmap largeImage = BitmapFactory.decodeResource(getResources(),R.drawable.dog);
Notification channel = new NotificationCompat.Builder(getApplicationContext(),CHANNEL_ID_1)
.setSmallIcon(R.drawable.ic_music)
.setContentTitle(notificationTitleText
)
.setContentText(notificationDescText)
.setLargeIcon(largeImage)
.addAction(R.drawable.ic_like,"like",null)
.addAction(R.drawable.ic_prev,"prev",null)
.addAction(R.drawable.ic_pause,"pause",null)
.addAction(R.drawable.ic_next,"next",null)
.addAction(R.drawable.ic_dislike,"dislike",null)
.setStyle(new android.support.v4.media.app.NotificationCompat.MediaStyle().
setShowActionsInCompactView(1,2,3))
.build();
mNotificationManagerCompat.notify(1,channel);
}
gettext()method is working fine but it work on first when any clicked event is happen if song play oncomplete and next song is not get text value
I am assuming that you are playing songs from an Activity but this will also work for a service.
Put this in your activity or service
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals("com.mypackage.ACTION_PAUSE_MUSIC")){
//Do whatever you want. Ex. Pause
}
//Similarly this can be done for all actions
}};
Make your show notification method like this
public void shownotification(){
Bitmap largeImage = BitmapFactory.decodeResource(getResources(),R.drawable.dog);
Intent pauseIntent = new Intent("com.mypackage.ACTION_PAUSE_MUSIC");
PendingIntent pausePendingIntent = PendingIntent.getBroadcast(this, 1, pauseIntent, 0);
// Similarly you can create an intent and pending intent pair for each action you want just change the string in intent constructor
Notification channel = new NotificationCompat.Builder(getApplicationContext(),CHANNEL_ID_1)
.setSmallIcon(R.drawable.ic_music)
.setContentTitle(notificationTitleText
)
.setContentText(notificationDescText)
.setLargeIcon(largeImage)
.addAction(R.drawable.ic_like,"like",null)
.addAction(R.drawable.ic_prev,"prev",null)
.addAction(R.drawable.ic_pause,"pause",pausePendingIntent) //like this attach every action with respective pending intent
.addAction(R.drawable.ic_next,"next",null)
.addAction(R.drawable.ic_dislike,"dislike",null)
.setStyle(new android.support.v4.media.app.NotificationCompat.MediaStyle()
.setShowActionsInCompactView(1,2,3))
.build();
mNotificationManagerCompat.notify(1,channel);}
I want to add one more thing to #Kumar Manas answer
i.e We need to register reciever that is being created in activity.
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals("com.mypackage.ACTION_PAUSE_MUSIC")){
//Do whatever you want. Ex. Pause
}
//Similarly this can be done for all actions
}};
To register your Reciever add these lines in onCreate()
IntentFilter intentFilter=new IntentFilter();
intentFilter.addAction("com.mypackage.ACTION_PAUSE_MUSIC");
registerReceiver(receiver,intentFilter);
Note: You can add as many actions you want
You may get your answer by following this tutorial "Android Music Player Controls on Lock Screen and Notifications"
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?
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();
}
}
After loading in all the current song information to the session metadata, the album art refuses to load on the lockscreen. I know for a fact that the bitmap is valid because I use the same resource for the notification art. I've also tried using just a static resource, but no luck. Any help would be much appreciated.
String more;
if (shuffled) {
more = Integer.toString(shufflePosition+1) + "/" + Integer.toString(playlist.size());
}
else{
more = Integer.toString(position+1) + "/" + Integer.toString(playlist.size());
}
int notificationAction = android.R.drawable.ic_media_pause;//needs to be initialized
//Build a new notification according to the current state of the MediaPlayer
if (mp.isPlaying()) {
notificationAction = android.R.drawable.ic_media_pause;
} else{
notificationAction = android.R.drawable.ic_media_play;
}
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),np.getArt());
} catch (IOException e) {
bitmap = BitmapFactory.decodeResource(getResources(),
R.mipmap.empty_track);
e.printStackTrace();
}
mSession.setMetadata(new MediaMetadataCompat.Builder()
.putBitmap(MediaMetadata.METADATA_KEY_ART, bitmap)
.putString(MediaMetadata.METADATA_KEY_ARTIST, np.getArtist())
.putString(MediaMetadata.METADATA_KEY_ALBUM, np.getAlbum())
.putString(MediaMetadata.METADATA_KEY_TITLE, np.getTrack())
.build());
Notification notification;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
notification = new android.support.v7.app.NotificationCompat.Builder(this)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setSmallIcon(R.mipmap.empty_artist)
.setShowWhen(false)
.addAction(new NotificationCompat.Action.Builder(android.R.drawable.ic_media_previous, "Previous", pendingPrev).build())
.addAction(new NotificationCompat.Action.Builder(notificationAction, "Pause", pendingPlay).build())
.addAction(new NotificationCompat.Action.Builder(android.R.drawable.ic_media_next, "Next", pendingNext).build())
.setColor(getResources().getColor(R.color.colorPrimary))
.setContentTitle(np.getTrack())
.setContentText(np.getArtist())
.setSubText(more)
.setPriority(Notification.PRIORITY_MAX)
.setLargeIcon(bitmap)
.setContentIntent(launchActivity)
.setStyle(new android.support.v7.app.NotificationCompat.MediaStyle()
.setMediaSession(mSession.getSessionToken()).setShowActionsInCompactView(0,1,2))
.build();
} else {
notification = new android.support.v7.app.NotificationCompat.Builder(this)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setSmallIcon(R.mipmap.empty_artist)
.setShowWhen(false)
.addAction(new NotificationCompat.Action.Builder(android.R.drawable.ic_media_previous, "Previous", pendingPrev).build())
.addAction(new NotificationCompat.Action.Builder(notificationAction, "Pause", pendingPlay).build())
.addAction(new NotificationCompat.Action.Builder(android.R.drawable.ic_media_next, "Next", pendingNext).build())
.setColor(getResources().getColor(R.color.colorPrimary))
.setContentTitle(np.getTrack())
.setContentText(np.getArtist())
.setSubText(more)
.setPriority(Notification.PRIORITY_MAX)
.setLargeIcon(bitmap)
.setContentIntent(launchActivity)
.setStyle(new android.support.v7.app.NotificationCompat.MediaStyle()
.setMediaSession(mSession.getSessionToken())
.setShowActionsInCompactView(0,1,2))
.build();
}
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(001, notification);
startForeground(001, notification);
As per the Working with a Media Session documentation page:
In Android 4.0 (API level 14) and greater, the background of the lock screen displays your album artwork - but only if the media session metadata includes a background bitmap.
You must set a background Bitmap in your MediaMetadataCompat by using putBitmap with either METADATA_KEY_ALBUM_ART or METADATA_KEY_ART
You have to use playbackstate after 3 days i found this one
public void pausePlayer() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
startForeground(false);
((MainActivity) context).notificationUpdated(false);
isPlay = false;
playbackStateCompat.setActions(PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_STOP);
playbackStateCompat.setState(PlaybackStateCompat.STATE_PAUSED, mediaPlayer.getCurrentPosition(), 1.0f, SystemClock.elapsedRealtime());
mediaSession.setPlaybackState(playbackStateCompat.build());
}
}
mediaPlayer = MediaPlayer.create(getApplicationContext(), Uri.parse(currentSong.getUrl()));
mediaSession.setMetadata(getMetadata());
playbackStateCompat.setActions(PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_STOP);
playbackStateCompat.setState(PlaybackStateCompat.STATE_PLAYING, mediaPlayer.getCurrentPosition(), 1.0f, SystemClock.elapsedRealtime());
mediaSession.setPlaybackState(playbackStateCompat.build());
mediaPlayer.start();
I am making a Call recorder app in Android. I have a service that detects the incoming and outgoing call and as soon as the service detects the incoming or outgoing call it starts the recording through media player. It is getting recorded sucessfully but I am unable to play it on speaker. The volume is very low even after enabling speakers through Audio Manager. Please let me know where I might be going wrong.
Note: I am guessing that my audio is not getting recorded properly because if I play the recorded file through my phone music player, then even there I am not able to play that file on speaker.
below is my code which is used to start the recording:
try{
MediaRecorder mediaRecorder = new MediaRecorder();
if(AUDIO_SOURCE_TYPE.equalsIgnoreCase("VOICE_COMMUNICATION"))
{
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION);
}
else if(AUDIO_SOURCE_TYPE.equalsIgnoreCase("VOICE_UPLINK"))
{
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_UPLINK);
}
else if(AUDIO_SOURCE_TYPE.equalsIgnoreCase("VOICE_DOWNLINK"))
{
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_DOWNLINK);
}
else if(AUDIO_SOURCE_TYPE.equalsIgnoreCase("MIC"))
{
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
}
else if(AUDIO_SOURCE_TYPE.equalsIgnoreCase("DEFAULT"))
{
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
}
else
{
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
}
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setOutputFile(getTempFilename());
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.prepare();
} catch (Exception e) {
e.printStackTrace();
}
mediaRecorder.start();
Below is the Media Playback Code :
final MediaPlayer mp=new MediaPlayer();
String uri= getIntent().getStringExtra("fileURI"); //fetches the string defining the path of file to be played
Uri fileURI = Uri.parse(uri);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
AudioManager mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
mAudioManager.setSpeakerphoneOn(true);
int maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, AudioManager.FLAG_PLAY_SOUND);
try{
try {
mp.setDataSource(getApplicationContext(), fileURI);
} catch (IOException e) {
e.printStackTrace();
}
}
mp.prepare();
}catch(Exception e){e.printStackTrace();}
mp.start();
i'm trying to stream live audio form the internet using setDataSource, however when I add the url it says it's an unhandled exception.. any ideas whats wrong here?
String daytonPolice = "http://relay.radioreference.com:80/691484064";
MediaPlayer mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(daytonPolice); // It will not take the string of my url
mp.prepareAsync();
mp.start();
The issue is because you are calling start() right after calling prepareAsync(). You need to set an onPreparedListener:
String daytonPolice = "http://relay.radioreference.com:80/691484064";
MediaPlayer mp = new MediaPlayer();
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(daytonPolice); // It will not take the string of my url
mp.prepareAsync();