Usman
Usman

Reputation: 2401

Can't use STREAM_VOICE_CALL to play audio via MediaPlayer in android java

I have tried to play many audio (mp3) files through MediaPlayer's setAudioStreamType(AudioManager.STREAM_VOICE_CALL); but mp.start(); does not play nor does it throw an exception. The setup works with SoundPool but it is limited to like 5 seconds, some files playing upto 8 seconds. I am attaching the part of code here:

    String s = absolutepath.get(position);
    Uri u = Uri.parse(s);
    playing = (MediaPlayer) MediaPlayer.create(MainActivity.this, u);
    playing.setOnPreparedListener(this);

onPrepared includes this:

    @Override
public void onPrepared(MediaPlayer mp) {
    // TODO Auto-generated method stub
    spProgress.cancel();
    mp.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
    try {
    mp.start();
    } catch (IllegalStateException e) {
        Toast.makeText(this, "exception", Toast.LENGTH_SHORT).show();
    }
}

I have tried this without the try/catch and even without listener. The only time it plays is when I don't use the stream type STREAM_VOICE_CALL.

The same files can be played with SoundPool:

SoundPool sp = new SoundPool(1, AudioManager.STREAM_VOICE_CALL, 0);
sp.load(s, 1);
sp.setOnLoadCompleteListener(this);

Listener:

@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
    // TODO Auto-generated method stub
    if (status == 0) {
        spProgress.cancel();
        sp.play(sampleId, 1, 1, 1, 0, 1);
    } else {
        Toast.makeText(this, "failed to load", Toast.LENGTH_SHORT).show();
    }
}

Upvotes: 4

Views: 2662

Answers (1)

Simi401
Simi401

Reputation: 74

I actually had the same problem, and Google's Guide is very bad here - it's indeed a bit tricky, but simple to explain:

As you need to change the STREAM, and then prepare() your MediaPlayer again, you'll get it working by doing this:

    Resources res = getResources();
    AssetFileDescriptor afd = res.openRawResourceFd(R.raw.tts_a);

    mp = new MediaPlayer();
    //mp.reset();
    mp.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
    mp.setLooping(false);
    try {
        mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        mp.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }

    mp.start();

The actual trick is to NOT use the MediaPlayer.create, as it's calling the prepare itself! Therefore you're not able to set the Stream. By setting the File with AssetFileDescriptor, you can set the Stream and call your prepare() afterwards!

Upvotes: 5

Related Questions