基于Linphone android sdk开发Android软话机

2023-12-21 15:44

本文主要是介绍基于Linphone android sdk开发Android软话机,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

 

1.Linphone简介

1.1 简介

LinPhone是一个遵循GPL协议的开源网络电话或者IP语音电话(VOIP)系统,其主要如下。使用linphone,开发者可以在互联网上随意的通信,包括语音、视频、即时文本消息。linphone使用SIP协议,是一个标准的开源网络电话系统,能将linphone与任何基于SIP的VoIP运营商连接起来,包括我们自己开发的免费的基于SIP的Audio/Video服务器。

LinPhone是一款自由软件(或者开源软件),你可以随意的下载和在LinPhone的基础上二次开发。LinPhone是可用于Linux, Windows, MacOSX 桌面电脑以及Android, iPhone, Blackberry移动设备。

学习LinPhone的源码,开源从以下几个部分着手: Java层框架实现的SIP三层协议架构: 传输层,事务层,语法编解码层; linphone动态库C源码实现的SIP功能: 注册,请求,请求超时,邀请会话,挂断电话,邀请视频,收发短信... linphone动态库C源码实现的音视频编解码功能; Android平台上的音视频捕获,播放功能;

1.2 基本使用

如果是Android系统用户,可以从谷歌应用商店安装或者从这个链接下载Linphone 。安装完成后,点击左上角的菜单按钮,选择进入助手界面。在助手界面,可以设定SIP账户或者Linphone账号,如下图:

2.基于linphone android sdk开发linphone

引入sdk依赖 

dependencies {
    //linphone
    debugImplementation "org.linphone:linphone-sdk-android-debug:5.0.0"
    releaseImplementation "org.linphone:linphone-sdk-android:5.0.0"

为了方便调用,我们需要对Linphone进行简单的封装。首先,按照官方文档的介绍,创建一个CoreManager类,此类是sdk里面的管理类,用来控制来电铃声和启动CoreService,无特殊需求不需调用。需要注意的是,启动来电铃声需要导入media包,否则不会有来电铃声,如下

implementation 'androidx.media:media:1.2.0'

基本代码开发: 

package com.matt.linphonelibrary.coreimport android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.telephony.PhoneStateListener
import android.telephony.TelephonyManager
import android.util.Log
import android.view.TextureView
import com.matt.linphonelibrary.R
import com.matt.linphonelibrary.callback.PhoneCallback
import com.matt.linphonelibrary.callback.RegistrationCallback
import com.matt.linphonelibrary.utils.AudioRouteUtils
import com.matt.linphonelibrary.utils.LinphoneUtils
import com.matt.linphonelibrary.utils.VideoZoomHelper
import org.linphone.core.*
import java.io.File
import java.util.*class LinphoneManager private constructor(private val context: Context) {private val TAG = javaClass.simpleNameprivate var core: Coreprivate var corePreferences: CorePreferencesprivate var coreIsStart = falsevar registrationCallback: RegistrationCallback? = nullvar phoneCallback: PhoneCallback? = nullinit {//日志收集Factory.instance().setLogCollectionPath(context.filesDir.absolutePath)Factory.instance().enableLogCollection(LogCollectionState.Enabled)corePreferences = CorePreferences(context)corePreferences.copyAssetsFromPackage()val config = Factory.instance().createConfigWithFactory(corePreferences.configPath,corePreferences.factoryConfigPath)corePreferences.config = configval appName = context.getString(R.string.app_name)Factory.instance().setDebugMode(corePreferences.debugLogs, appName)core = Factory.instance().createCoreWithConfig(config, context)}private var previousCallState = Call.State.Idleprivate val coreListener = object : CoreListenerStub() {override fun onGlobalStateChanged(core: Core, state: GlobalState?, message: String) {if (state === GlobalState.On) {}}//登录状态回调override fun onRegistrationStateChanged(core: Core,cfg: ProxyConfig,state: RegistrationState,message: String) {when (state) {RegistrationState.None -> registrationCallback?.registrationNone()RegistrationState.Progress -> registrationCallback?.registrationProgress()RegistrationState.Ok -> registrationCallback?.registrationOk()RegistrationState.Cleared -> registrationCallback?.registrationCleared()RegistrationState.Failed -> registrationCallback?.registrationFailed()}}//电话状态回调override fun onCallStateChanged(core: Core,call: Call,state: Call.State,message: String) {Log.i(TAG, "[Context] Call state changed [$state]")when (state) {Call.State.IncomingReceived, Call.State.IncomingEarlyMedia -> {if (gsmCallActive) {Log.w(TAG,"[Context] Refusing the call with reason busy because a GSM call is active")call.decline(Reason.Busy)return}phoneCallback?.incomingCall(call)gsmCallActive = true//自动接听if (corePreferences.autoAnswerEnabled) {val autoAnswerDelay = corePreferences.autoAnswerDelayif (autoAnswerDelay == 0) {Log.w(TAG, "[Context] Auto answering call immediately")answerCall(call)} else {Log.i(TAG,"[Context] Scheduling auto answering in $autoAnswerDelay milliseconds")val mainThreadHandler = Handler(Looper.getMainLooper())mainThreadHandler.postDelayed({Log.w(TAG, "[Context] Auto answering call")answerCall(call)}, autoAnswerDelay.toLong())}}}Call.State.OutgoingInit -> {phoneCallback?.outgoingInit(call)gsmCallActive = true}Call.State.OutgoingProgress -> {if (core.callsNb == 1 && corePreferences.routeAudioToBluetoothIfAvailable) {AudioRouteUtils.routeAudioToBluetooth(core, call)}}Call.State.Connected -> phoneCallback?.callConnected(call)Call.State.StreamsRunning -> {// Do not automatically route audio to bluetooth after first callif (core.callsNb == 1) {// Only try to route bluetooth / headphone / headset when the call is in StreamsRunning for the first timeif (previousCallState == Call.State.Connected) {Log.i(TAG,"[Context] First call going into StreamsRunning state for the first time, trying to route audio to headset or bluetooth if available")if (AudioRouteUtils.isHeadsetAudioRouteAvailable(core)) {AudioRouteUtils.routeAudioToHeadset(core, call)} else if (corePreferences.routeAudioToBluetoothIfAvailable && AudioRouteUtils.isBluetoothAudioRouteAvailable(core)) {AudioRouteUtils.routeAudioToBluetooth(core, call)}}}if (corePreferences.routeAudioToSpeakerWhenVideoIsEnabled && call.currentParams.videoEnabled()) {// Do not turn speaker on when video is enabled if headset or bluetooth is usedif (!AudioRouteUtils.isHeadsetAudioRouteAvailable(core) &&!AudioRouteUtils.isBluetoothAudioRouteCurrentlyUsed(core, call)) {Log.i(TAG,"[Context] Video enabled and no wired headset not bluetooth in use, routing audio to speaker")AudioRouteUtils.routeAudioToSpeaker(core, call)}}}Call.State.End, Call.State.Released, Call.State.Error -> {if (core.callsNb == 0) {when (state) {Call.State.End -> phoneCallback?.callEnd(call)Call.State.Released -> phoneCallback?.callReleased(call)Call.State.Error -> {val id = when (call.errorInfo.reason) {Reason.Busy -> R.string.call_error_user_busyReason.IOError -> R.string.call_error_io_errorReason.NotAcceptable -> R.string.call_error_incompatible_media_paramsReason.NotFound -> R.string.call_error_user_not_foundReason.Forbidden -> R.string.call_error_forbiddenelse -> R.string.call_error_unknown}phoneCallback?.error(context.getString(id))}}gsmCallActive = false}}}previousCallState = state}}/*** 启动linphone*/fun start() {if (!coreIsStart) {coreIsStart = trueLog.i(TAG, "[Context] Starting")core.addListener(coreListener)core.start()initLinphone()val telephonyManager =context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManagerLog.i(TAG, "[Context] Registering phone state listener")telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE)}}/*** 停止linphone*/fun stop() {coreIsStart = falseval telephonyManager =context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManagerLog.i(TAG, "[Context] Unregistering phone state listener")telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE)core.removeListener(coreListener)core.stop()}/*** 注册到服务器** @param username     账号名* @param password      密码* @param domain     IP地址:端口号*/fun createProxyConfig(username: String,password: String,domain: String,type: TransportType? = TransportType.Udp) {core.clearProxyConfig()val accountCreator = core.createAccountCreator(corePreferences.xmlRpcServerUrl)accountCreator.language = Locale.getDefault().languageaccountCreator.reset()accountCreator.username = usernameaccountCreator.password = passwordaccountCreator.domain = domainaccountCreator.displayName = usernameaccountCreator.transport = typeaccountCreator.createProxyConfig()}/*** 取消注册*/fun removeInvalidProxyConfig() {core.clearProxyConfig()}/*** 拨打电话* @param to String* @param isVideoCall Boolean*/fun startCall(to: String, isVideoCall: Boolean) {try {val addressToCall = core.interpretUrl(to)addressToCall?.displayName = toval params = core.createCallParams(null)//启用通话录音
//            params?.recordFile = LinphoneUtils.getRecordingFilePathForAddress(context, addressToCall!!)//启动低宽带模式if (LinphoneUtils.checkIfNetworkHasLowBandwidth(context)) {Log.w(TAG, "[Context] Enabling low bandwidth mode!")params?.enableLowBandwidth(true)}if (isVideoCall) {params?.enableVideo(true)core.enableVideoCapture(true)core.enableVideoDisplay(true)} else {params?.enableVideo(false)}if (params != null) {core.inviteAddressWithParams(addressToCall!!, params)} else {core.inviteAddress(addressToCall!!)}} catch (e: Exception) {e.printStackTrace()}}/*** 接听来电**/fun answerCall(call: Call) {Log.i(TAG, "[Context] Answering call $call")val params = core.createCallParams(call)//启用通话录音
//        params?.recordFile = LinphoneUtils.getRecordingFilePathForAddress(context, call.remoteAddress)if (LinphoneUtils.checkIfNetworkHasLowBandwidth(context)) {Log.w(TAG, "[Context] Enabling low bandwidth mode!")params?.enableLowBandwidth(true)}params?.enableVideo(isVideoCall(call))call.acceptWithParams(params)}/*** 谢绝电话* @param call Call*/fun declineCall(call: Call) {val voiceMailUri = corePreferences.voiceMailUriif (voiceMailUri != null && corePreferences.redirectDeclinedCallToVoiceMail) {val voiceMailAddress = core.interpretUrl(voiceMailUri)if (voiceMailAddress != null) {Log.i(TAG, "[Context] Redirecting call $call to voice mail URI: $voiceMailUri")call.redirectTo(voiceMailAddress)}} else {Log.i(TAG, "[Context] Declining call $call")call.decline(Reason.Declined)}}/*** 挂断电话*/fun terminateCall(call: Call) {Log.i(TAG, "[Context] Terminating call $call")call.terminate()}fun micEnabled() = core.micEnabled()fun speakerEnabled() = core.outputAudioDevice?.type == AudioDevice.Type.Speaker/*** 启动麦克风* @param micEnabled Boolean*/fun enableMic(micEnabled: Boolean) {core.enableMic(micEnabled)}/*** 扬声器或听筒* @param SpeakerEnabled Boolean*/fun enableSpeaker(SpeakerEnabled: Boolean) {if (SpeakerEnabled) {AudioRouteUtils.routeAudioToEarpiece(core)} else {AudioRouteUtils.routeAudioToSpeaker(core)}}/*** 是否是视频电话* @return Boolean*/fun isVideoCall(call: Call): Boolean {val remoteParams = call.remoteParamsreturn remoteParams != null && remoteParams.videoEnabled()}/*** 设置视频界面* @param videoRendering TextureView 对方界面* @param videoPreview CaptureTextureView 自己界面*/fun setVideoWindowId(videoRendering: TextureView, videoPreview: TextureView) {core.nativeVideoWindowId = videoRenderingcore.nativePreviewWindowId = videoPreview}/*** 设置视频电话可缩放* @param context Context* @param videoRendering TextureView*/fun setVideoZoom(context: Context, videoRendering: TextureView) {VideoZoomHelper(context, videoRendering, core)}fun switchCamera() {val currentDevice = core.videoDeviceLog.i(TAG, "[Context] Current camera device is $currentDevice")for (camera in core.videoDevicesList) {if (camera != currentDevice && camera != "StaticImage: Static picture") {Log.i(TAG, "[Context] New camera device will be $camera")core.videoDevice = camerabreak}}//        val conference = core.conference
//        if (conference == null || !conference.isIn) {
//            val call = core.currentCall
//            if (call == null) {
//                Log.w(TAG, "[Context] Switching camera while not in call")
//                return
//            }
//            call.update(null)
//        }}//初始化一些操作private fun initLinphone() {configureCore()initUserCertificates()}private fun configureCore() {// 来电铃声core.isNativeRingingEnabled = false// 来电振动core.isVibrationOnIncomingCallEnabled = truecore.enableEchoCancellation(true) //回声消除core.enableAdaptiveRateControl(true) //自适应码率控制}private var gsmCallActive = falseprivate val phoneStateListener = object : PhoneStateListener() {override fun onCallStateChanged(state: Int, phoneNumber: String?) {gsmCallActive = when (state) {TelephonyManager.CALL_STATE_OFFHOOK -> {Log.i(TAG, "[Context] Phone state is off hook")true}TelephonyManager.CALL_STATE_RINGING -> {Log.i(TAG, "[Context] Phone state is ringing")true}TelephonyManager.CALL_STATE_IDLE -> {Log.i(TAG, "[Context] Phone state is idle")false}else -> {Log.i(TAG, "[Context] Phone state is unexpected: $state")false}}}}//设置存放用户x509证书的目录路径private fun initUserCertificates() {val userCertsPath = corePreferences!!.userCertificatesPathval f = File(userCertsPath)if (!f.exists()) {if (!f.mkdir()) {Log.e(TAG, "[Context] $userCertsPath can't be created.")}}core.userCertificatesPath = userCertsPath}companion object {// For Singleton instantiation@SuppressLint("StaticFieldLeak")@Volatileprivate var instance: LinphoneManager? = nullfun getInstance(context: Context) =instance ?: synchronized(this) {instance ?: LinphoneManager(context).also { instance = it }}}}

这篇关于基于Linphone android sdk开发Android软话机的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/520561

相关文章

这15个Vue指令,让你的项目开发爽到爆

1. V-Hotkey 仓库地址: github.com/Dafrok/v-ho… Demo: 戳这里 https://dafrok.github.io/v-hotkey 安装: npm install --save v-hotkey 这个指令可以给组件绑定一个或多个快捷键。你想要通过按下 Escape 键后隐藏某个组件,按住 Control 和回车键再显示它吗?小菜一碟: <template

Hadoop企业开发案例调优场景

需求 (1)需求:从1G数据中,统计每个单词出现次数。服务器3台,每台配置4G内存,4核CPU,4线程。 (2)需求分析: 1G / 128m = 8个MapTask;1个ReduceTask;1个mrAppMaster 平均每个节点运行10个 / 3台 ≈ 3个任务(4    3    3) HDFS参数调优 (1)修改:hadoop-env.sh export HDFS_NAMENOD

嵌入式QT开发:构建高效智能的嵌入式系统

摘要: 本文深入探讨了嵌入式 QT 相关的各个方面。从 QT 框架的基础架构和核心概念出发,详细阐述了其在嵌入式环境中的优势与特点。文中分析了嵌入式 QT 的开发环境搭建过程,包括交叉编译工具链的配置等关键步骤。进一步探讨了嵌入式 QT 的界面设计与开发,涵盖了从基本控件的使用到复杂界面布局的构建。同时也深入研究了信号与槽机制在嵌入式系统中的应用,以及嵌入式 QT 与硬件设备的交互,包括输入输出设

OpenHarmony鸿蒙开发( Beta5.0)无感配网详解

1、简介 无感配网是指在设备联网过程中无需输入热点相关账号信息,即可快速实现设备配网,是一种兼顾高效性、可靠性和安全性的配网方式。 2、配网原理 2.1 通信原理 手机和智能设备之间的信息传递,利用特有的NAN协议实现。利用手机和智能设备之间的WiFi 感知订阅、发布能力,实现了数字管家应用和设备之间的发现。在完成设备间的认证和响应后,即可发送相关配网数据。同时还支持与常规Sof

活用c4d官方开发文档查询代码

当你问AI助手比如豆包,如何用python禁止掉xpresso标签时候,它会提示到 这时候要用到两个东西。https://developers.maxon.net/论坛搜索和开发文档 比如这里我就在官方找到正确的id描述 然后我就把参数标签换过来

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo

Android平台播放RTSP流的几种方案探究(VLC VS ExoPlayer VS SmartPlayer)

技术背景 好多开发者需要遴选Android平台RTSP直播播放器的时候,不知道如何选的好,本文针对常用的方案,做个大概的说明: 1. 使用VLC for Android VLC Media Player(VLC多媒体播放器),最初命名为VideoLAN客户端,是VideoLAN品牌产品,是VideoLAN计划的多媒体播放器。它支持众多音频与视频解码器及文件格式,并支持DVD影音光盘,VCD影

Linux_kernel驱动开发11

一、改回nfs方式挂载根文件系统         在产品将要上线之前,需要制作不同类型格式的根文件系统         在产品研发阶段,我们还是需要使用nfs的方式挂载根文件系统         优点:可以直接在上位机中修改文件系统内容,延长EMMC的寿命         【1】重启上位机nfs服务         sudo service nfs-kernel-server resta

【区块链 + 人才服务】区块链集成开发平台 | FISCO BCOS应用案例

随着区块链技术的快速发展,越来越多的企业开始将其应用于实际业务中。然而,区块链技术的专业性使得其集成开发成为一项挑战。针对此,广东中创智慧科技有限公司基于国产开源联盟链 FISCO BCOS 推出了区块链集成开发平台。该平台基于区块链技术,提供一套全面的区块链开发工具和开发环境,支持开发者快速开发和部署区块链应用。此外,该平台还可以提供一套全面的区块链开发教程和文档,帮助开发者快速上手区块链开发。

Vue3项目开发——新闻发布管理系统(六)

文章目录 八、首页设计开发1、页面设计2、登录访问拦截实现3、用户基本信息显示①封装用户基本信息获取接口②用户基本信息存储③用户基本信息调用④用户基本信息动态渲染 4、退出功能实现①注册点击事件②添加退出功能③数据清理 5、代码下载 八、首页设计开发 登录成功后,系统就进入了首页。接下来,也就进行首页的开发了。 1、页面设计 系统页面主要分为三部分,左侧为系统的菜单栏,右侧