Question

I use this code to try:

AudioManager audioManager = (AudioManager)getApplication().getSystemService(Context.AUDIO_SERVICE); 
        audioManager.setMode(AudioManager.MODE_IN_CALL);
        audioManager.setSpeakerphoneOn(true);

And then:

Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), Uri.parse("url.mp3"));
                        r.play();

But my app doesn' reproduce any sound.

How can i solve my problem?

Was it helpful?

Solution

According to the OP, the best answer can be found using the MediaPlayer (a link with an example is given in the comments section of this answer).

-- Previous Edits --

Haven't tested this so forgive me if it is buggy, but I think it may work better by setting the default value for the ringtone and then calling that default value. I haven't had a chance to test the code, but it should look something like...

To route the audio to your earpiece:

private AudioManager audioManager;  
audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);  
audioManager.setMode(AudioManager.MODE_IN_CALL); 
audioManager.setSpeakerphoneOn(false);

Then check out AudioTracks, it might be the way to go with what you want to do as Ringtone's have default actions based on Android's native processing; it should be something like

InputStream in =getResources().openRawResource("user_mp3");      
AudioTrack audio = new AudioTrack(AudioManager.STREAM_MUSIC, 11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, buffersize, AudioTrack.MODE_STREAM);

byte[] sound = null;
sound = new byte[in.available()]; 
sound =convertStreamToByteArray(in);
in.close();
audio.write(sound, 0, sound.length());
audio.play();

But be sure to set your mode back to normal with your AudioManager when you are done. I think this should work. There is also the deprecated AudioManager.ROUTE_EARPIECE call, you might want to check and see how they have replaced it.

Again, didn't have time to test this, just typed it up on the fly. Let me know if you find an error.

My original "ringtone" style output:

Uri soundPath = Uri.parse("uri_link_for_mp3");
RingtoneManager.setActualDefaultRingtoneUri(getApplicationContext(), 
        RingtoneManager.TYPE_RINGTONE, soundPath);

Uri ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), ringtone);
r.play();

Had to type this up kind of quick, might have missed something just not thinking of it. There is a good link for this though: Setting Ringtone in Android

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top