This is the function that suppose to play some sound when a notification is set
private void playRingtone() {
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if (am.getRingerMode() == AudioManager.RINGER_MODE_NORMAL) {
try {
MediaPlayer mp = MediaPlayer.create(this, R.raw.notification_ringtone);
mp.start();
} catch (IllegalStateException e) {
Log.d(TAG, "MediaPlayer problem");
e.printStackTrace();
}
}
}
using the debugger everything goes smoothly but no sound is played. WHY???
MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource("android.resource://YOURPACKAGE_NAME/raw/"+file anme);
mediaPlayer.prepare();
mediaPlayer.start();
}catch(Exceptions e){
}
Related
I try to run file mp3 with volume of ringtone (not of media, alarm or notification), but it not working. My code:
AudioManager mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
mAudioManager.setMode(AudioManager.MODE_IN_CALL);
mAudioManager.setStreamVolume(
AudioManager.STREAM_RING,
mAudioManager.getStreamMaxVolume(AudioManager.STREAM_RING),
AudioManager.FLAG_PLAY_SOUND);
mAudioManager.setSpeakerphoneOn(true);
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(this, Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.nhaccho));
} catch (IOException e) {
e.printStackTrace();
}
mp.setAudioStreamType(AudioManager.STREAM_RING);
mp.setLooping(true);
try {
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
please help. thanks!
I'm trying to play notification sound even if silent mode is on
Uri uri = Uri.parse(alarmSound);
notification.setSound(uri);
AudioManager mobileMode = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
int previousNotificationVolume = mobileMode.getStreamVolume(AudioManager.STREAM_NOTIFICATION);
if (ignoreSilent) {
mobileMode.setStreamVolume(AudioManager.STREAM_NOTIFICATION, mobileMode.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION), 0);
}
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(UNIQUE_ID, n);
try {
// to delay make a space to finish play sound before return back to original stat.
Thread.sleep(2000);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
mobileMode.setStreamVolume(AudioManager.STREAM_NOTIFICATION, previousNotificationVolume, 0);
This should be option that user enable or disable, I'm trying the code above but the things not going well, the sound heard "sometimes" and the phone return to the Vibration mode instead of silent, I want to handle lollipop case:
In Silent mode , timed or indefinitely.
In priority mode, timed or indefinitely.
In another world, I want something to save full stat and return it as it was.
Or, since I know how to play sound with media player, way to get the stat of phone, and if it is silent, make sound playing as a media, with max sound of media, the following how I can play sound with MediaPlayer :
public static void playSound(Context context, Uri alert) {
MediaPlayer mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(context, alert);
final AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
}
And then like this (but I want to know if phone in silent or vibration or priority mode) :
if (ignoreSilent) {
CoreServices.playSound(context, uri);
} else {
// else just follow normal behavior
notification.setSound(uri);
}
Finally, I prefer to solve by switching status, at least I will know how android deal things in this part, and working with API 14+.
public void playSound(){
final MediaPlayer mMediaPlayer;
Uri notification = null;
try {
notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(getApplicationContext(), notification);
// mMediaPlayer = MediaPlayer.create(ctx, notification);
final AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
try {
mMediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
// mMediaPlayer.start();
mMediaPlayer.setLooping(false);
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer arg0) {
/* if (mMediaPlayer != null) {
mMediaPlayer.stop();
}*/
mMediaPlayer.seekTo(0);
mMediaPlayer.start();
}
});
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
}
});
}catch (Exception e){
e.printStackTrace();
}
}
I have the following code to play an mp3 file from the web and this is working but when I use the stop functionality the audio does not stop. Can anyone point me towards a resource to find out more about this or tell me where I am going wrong? Thanks.
showAudio.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
if (!showAudio.getText().equals("Stop")) {
try {
String url = lblAudio.getText().toString();
if (url.length() > 2) {
mediaPlayer.setDataSource(url);
mediaPlayer.prepare();
mediaPlayer.start();
showAudio.setText("Stop");
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), "Sorry, there was a problem playing audio.", Toast.LENGTH_SHORT).show();
}
} else {
try {
mediaPlayer.stop();
mediaPlayer.release();
} catch (Exception ex) {
ex.printStackTrace();
}
showAudio.setText("Audio");
}
}
});
You are creating a new MediaPlayer every time you click the button. Create the player outside of the click handler.
Try out :
try {
if(mediaPlayer.isPlaying())
{
mediaPlayer.stop();
mediaPlayer.release();
}
} catch(Exception ex) {
ex.printStackTrace();
}
Try making your media player a global variable and make it static....
I have a working media player that starts and stops
Uri ringtone;
MediaPlayer mp;
ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
mp = MediaPlayer.create(getApplicationContext(), ringtone);
//code to start the mediaplayer
if (Flags.notificationReceived) {
showAlert(Flags.patientModel);
Flags.notificationReceived = false;
mp.start();
mp.setLooping(true);
vibrate(2000);
}
//code to stop the media player
if (mp.isPlaying()) {
mp.stop();
mp.reset();
mp.release();
mp = MediaPlayer.create(getApplicationContext(), ringtone);
}
I have a lot of short .mp3 files that I want to play one after the other.. I tried to use onCompletion event and start the next mp3, though this causes a brief gap between the 2 mp3s..
Here is the code:
void StartSound() {
mediaplayer = MediaPlayer.create(this, Uri.parse(FILE_PATH + counter + ".mp3"));
try {
mediaplayer.start();
mediaplayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
counter++;
try {
mp.reset();
mp.setDataSource(FILE_PATH + counter + ".mp3");
mp.prepare();
} catch (Exception e) {
e.printStackTrace();
}
mp.start();
}
});
} catch (Exception e) {
}
}
Is there a work around to this issue?
There's a workaround, but whether it's worth the trouble is up to you.
The basic idea is to decode the MP3 files to a PCM buffer, stitch them together in a byte array, and play with an AudioTrack. Seamless MP3 playback doesn't really exist with MediaPlayer. This could be a pain in the ass, though, and memory problems are likely if you're talking about full songs. For short clips, it may work, but SoundPool might be the better option.
If you're just trying to narrow the gap a bit, you can try preparing the following MediaPlayer objects before onCompletionListener. Instead of waiting to be done, prepare the next two so you can start playback faster. Then when you hit onCompletion, you can just flip which object you're using and start(). Crude double buffering, in a way.
Try this:
public class MainActivity extends Activity
{
private int[] tracks = {R.raw.explosion,R.raw.pianothingy_one,R.raw.car_horn_x};
int mCompleted = 0;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MediaPlayer mp = MediaPlayer.create(this, tracks[0]);
mp.setOnCompletionListener(new OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
mCompleted++;
mp.reset();
if (mCompleted < tracks.length)
{
try
{
AssetFileDescriptor afd = getResources().openRawResourceFd(tracks[mCompleted]);
if (afd != null)
{
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mp.prepare();
mp.start();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
else if (mCompleted>=tracks.length)
{
mCompleted =0;
try
{
AssetFileDescriptor afd = getResources().openRawResourceFd(tracks[mCompleted]);
if (afd != null)
{
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mp.prepare();
mp.start();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
else
{
mCompleted=0;
mp.release();
mp = null;
}
}
});
mp.start();
I'm working on a game in which one single sound is played each time the phone is shaked.
Does it make sense to use a SoundPool and load sounds in the onCreate of my activity, or is it ok to create a mediaplayer each time, as shown below:
private void onShake() {
MediaPlayer mp= MediaPlayer.create(this, whipSound[currentWhip][force]);
mp.start();
}
My guess is that SoundPool is better because the sounds are loaded only once. Am I right?
Thanks
Julien
As expected, SoundPool is much faster...
You can create the mediaPlayer outside the onShake method, and then reset and start it on every shake:
MediaPlayer mp= MediaPlayer.create(this, whipSound[currentWhip][force]);
...
private void onShake() {
mp.reset();
mp.start();
}
//or
private void onShake() {
try {
mp.stop();
mp.prepare();
} catch (IllegalStateException e) { /* Ignore */
} catch (IOException e) {/* Ignore */ }
try {
mp.start();
} catch (IllegalStateException e) {
Log.e(TAG, "MediaPlayer failed ", e);
}
}