Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

android - controlling volume in MediaPlayer

I'm playing audio (narration) in an audiobook. The audio files are in .ogg format, between 10 and 15 seconds long each.

Edit to add: I'm using Android 2.2, API 8, and I have this in my Manifest:

<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />

I've got setVolumeControlStream(AudioManager.STREAM_MUSIC); in my onCreate() method.

My sounds are being played via code similar to this:

mp = MediaPlayer.create(mContext, resource);
mp.setOnCompletionListener(this);
mp.seekTo(0);
mp.setLooping(looping);
if(isSoundEnabled())
{
    mp.setVolume(1, 1);
}
else
{
    // I still need sounds to call their onComplete listeners to drive action
    mp.setVolume(0,0);
}
nowPlaying = true;
mp.start();

But, despite more assurances (33 and counting!) that one simply needs setVolumeControlStream(AudioManager.STREAM_MUSIC); in onCreate(), my sounds don't change in volume when I press the volume keys on my device (Motorola Xoom).

To verify my volume keys were doing something, I overrode onKeyDown:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    boolean result = true;
    if (keyCode == KeyEvent.KEYCODE_VOLUME_UP)
    {
        DebugLog.d(TAG, "volume up");
    }
    else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
    {
        DebugLog.d(TAG, "volume down");
    }
}

and confirmed via LogCat that I'm pressing the correct volume keys:

07-19 12:16:31.440: DEBUG/BookReader(17830): volume down; thread 1
07-19 12:16:31.710: DEBUG/BookReader(17830): volume down; thread 1
07-19 12:16:31.980: DEBUG/BookReader(17830): volume down; thread 1
07-19 12:16:32.440: DEBUG/BookReader(17830): volume up; thread 1
07-19 12:16:32.820: DEBUG/BookReader(17830): volume up; thread 1

Though the following link is about SoundPool, should I be calculating stream volume instead of using mp.setVolume(1, 1); in my first code sample above?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Check to make sure you're not returning true every time onKeyDown is called. If that's the case then you're telling android that you'll handle all onKeyDown events, so android might be ignoring the volume key.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...