尝试将STREAM_MUSIC路由到扬声器,将STREAM_VOICE_CALL路由到耳机/耳塞

时间:2016-05-02 00:11:51

标签: android audio android-audiomanager audio-route

我正在尝试@Michael从之前的SO answer提出的技术,但没有任何运气。我正在尝试同时向播放器播放STREAM_MUSIC流,同时将STREAM_VOICE_CALL流发送到插入的耳塞。

结果是两个声音都在耳塞中播放(插入时),或者两者都在扬声器中播放。

我在运行4.4.4的Samsung Tab E Lite上尝试这个。我意识到我引用的链接提到并非所有硬件都支持这样的功能,但我想知道我是否还没有正确设置它。

    public class MainActivity extends AppCompatActivity {

    MediaPlayer mpVoice;
    MediaPlayer mpMusic;

    private AudioManager mAudioManager;

    @Override
    protected void onCreate(Bundle savedInstanceState)  {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
        //mAudioManager.setMode(AudioManager.MODE_IN_CALL);
        //mAudioManager.setSpeakerphoneOn(false);
        //mAudioManager.setWiredHeadsetOn(false);

        configureForceSpeaker();
    }


    private void configureForceSpeaker() {
        int FOR_MEDIA = 1;
        int FORCE_NONE = 0;
        int FORCE_SPEAKER = 1;

        Class audioSystemClass;
        Method setForceUse;

        try {
            audioSystemClass = Class.forName("android.media.AudioSystem");
            setForceUse = audioSystemClass.getMethod("setForceUse", int.class, int.class);
            setForceUse.invoke(null, FOR_MEDIA, FORCE_SPEAKER);
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    public void startVoice(View view){
        if (mpVoice == null) {
            AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.voice);
            mpVoice = new MediaPlayer();
            try {
                mpVoice.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
                mpVoice.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                mpVoice.setLooping(true);
                mpVoice.prepare();
            } catch (Exception e) {
                e.printStackTrace();
            }
            mpVoice.start();
        }
    }

    public void stopVoice(View view){
        mpVoice.stop();
        mpVoice = null;
    }

    public void startMusic(View view){
        if (mpMusic == null) {
            AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.music);
            mpMusic = new MediaPlayer();
            try {
                mpMusic.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mpMusic.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                mpMusic.setLooping(true);
                mpMusic.setVolume(0.3f, 0.3f);
                mpMusic.prepare();
            } catch (Exception e) {
                e.printStackTrace();
            }
            mpMusic.start();
        }
    }

    public void stopMusic(View view){
        mpMusic.stop();
        mpMusic = null;
    }
}

0 个答案:

没有答案