6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SkyWayでAndroidで音声の出力先を切り替える

Last updated at Posted at 2018-03-23

skywayを使っていて、Androidでつまづいたのですが、GalaxyS5・Android6.0でとりあえず動いたのでメモ


enum class AudioOutput{
    Speaker,
    Call
}

fun setAudioOutput(type:AudioOutput?){
    val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as? AudioManager
    val mediaPlayer = MediaPlayer()

    // MODE_IN_COMMUNICATION: In communication audio mode. An audio/video chat or VoIP call is established.
    audioManager?.mode = AudioManager.MODE_IN_COMMUNICATION

    type?.let{
        // Adjust output for Speakerphone.
        audioManager?.isSpeakerphoneOn = when(it){
            AudioOutput.Call -> false
            AudioOutput.Speaker -> true
        }
    } ?: run{
        if(this.isHeadsetOn()){
            audioManager?.isSpeakerphoneOn = false
        }else{
            audioManager?.isSpeakerphoneOn = true
        }
    }

    mediaPlayer.setAudioStreamType(AudioManager.MODE_IN_COMMUNICATION)
}

fun isHeadsetOn(): Boolean {
    val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        return audioManager.isWiredHeadsetOn() || audioManager.isBluetoothA2dpOn()
    } else {
        val devices = audioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS)
        for (i in devices.indices) {
            val device = devices[i]
            if (device.type === AudioDeviceInfo.TYPE_WIRED_HEADPHONES
                    || device.type === AudioDeviceInfo.TYPE_BLUETOOTH_A2DP
                    || device.type === AudioDeviceInfo.TYPE_BLUETOOTH_SCO) {
                return true
            }
        }
    }
    return false
}

6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?