基于SRS服务器实现Android-Web端视频通话(3):Android端向SRS服务器推送WebRTC流
基于SRS服务器实现Android-Web端视频通话(1):SRS服务器启用HTTPS
基于SRS服务器实现Android-Web端视频通话(2):Android端从SRS服务器拉取WebRTC流
基于SRS服务器实现Android-Web端视频通话(3):Android端向SRS服务器推送WebRTC流
实现效果
引库
implementation 'org.webrtc:google-webrtc:1.0.32006'
其他版本,详见
推流流程
createPeerConnectionFactory -> createPeerConnection(addTransceiver) -> createOffer -> setLocalDescription(OFFER) -> get remote sdp(network requset) -> setRemoteDescription(ANSWER)
代码实现
初始化
//加载并初始化 WebRTC,在创建 PeerConnectionFactory 之前必须至少调用一次
PeerConnectionFactory.initialize(
PeerConnectionFactory.InitializationOptions
.builder(applicationContext).createInitializationOptions()
)
private val eglBaseContext = EglBase.create().eglBaseContext
createPeerConnectionFactory
private val peerConnectionFactory: PeerConnectionFactory = createPeerConnectionFactory()
private fun createPeerConnectionFactory(): PeerConnectionFactory {
//先做默认配置,后面可能会遇到坑
val options = PeerConnectionFactory.Options()
val encoderFactory = DefaultVideoEncoderFactory(eglBaseContext, true, true)
val decoderFactory = DefaultVideoDecoderFactory(eglBaseContext)
return PeerConnectionFactory.builder()
.setOptions(options)
.setVideoEncoderFactory(encoderFactory)
.setVideoDecoderFactory(decoderFactory)
.createPeerConnectionFactory()
}
createPeerConnection(addTransceiver)
private fun initPeerConnection() {
val createAudioSource = peerConnectionFactory.createAudioSource(createAudioConstraints())
val audioTrack =
peerConnectionFactory.createAudioTrack("local_audio_track", createAudioSource)
cameraVideoCapturer = createVideoCapture(this)
cameraVideoCapturer?.let {
capture ->
val videoSource = peerConnectionFactory.createVideoSource(capture.isScreencast)
videoTrack =
peerConnectionFactory.createVideoTrack("local_video_track", videoSource).apply {
//显示到本地画面上
addSink(mBinding.svr)
}
surfaceTextureHelper =
SurfaceTextureHelper.create("surface_texture_thread", eglBaseContext)
capture.initialize(surfaceTextureHelper, this, videoSource.capturerObserver)
//开始捕帧,宽、高、帧率。
capture.startCapture(640, 480, 20)
}
val rtcConfig = PeerConnection.RTCConfiguration(emptyList())
/*
<p>For users who wish to send multiple audio/video streams and need to stay interoperable with legacy WebRTC implementations, specify PLAN_B.
<p>For users who wish to send multiple audio/video streams and/or wish to use the new RtpTransceiver API, specify UNIFIED_PLAN.
*/
//使用PeerConnection.SdpSemantics.UNIFIED_PLAN
rtcConfig.sdpSemantics = PeerConnection.SdpSemantics.UNIFIED_PLAN
peerConnection = peerConnectionFactory.createPeerConnection(
rtcConfig,
PeerConnectionObserver