1

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

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

我正在运行 4.4.4 的三星 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;
    }
}
4

0 回答 0