使用VOICE_CALL在Android5.0之后闪退bug源码解析

2024-04-21 19:38

本文主要是介绍使用VOICE_CALL在Android5.0之后闪退bug源码解析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

android4.4_r1版本AndroidRecord.java中源码如下

 public More ...AudioRecord(int audioSource, int sampleRateInHz, int channelConfig, int audioFormat,
209            int bufferSizeInBytes)
210    throws IllegalArgumentException {
211        mRecordingState = RECORDSTATE_STOPPED;
212
213        // remember which looper is associated with the AudioRecord instanciation
214        if ((mInitializationLooper = Looper.myLooper()) == null) {
215            mInitializationLooper = Looper.getMainLooper();
216        }
217
218        audioParamCheck(audioSource, sampleRateInHz, channelConfig, audioFormat);
219
220        audioBuffSizeCheck(bufferSizeInBytes);
221
222        // native initialization
223        int[] session = new int[1];
224        session[0] = 0;
225        //TODO: update native initialization when information about hardware init failure
226        //      due to capture device already open is available.
227        int initResult = native_setup( new WeakReference<AudioRecord>(this),
228                mRecordSource, mSampleRate, mChannelMask, mAudioFormat, mNativeBufferSizeInBytes,
229                session);
230        if (initResult != SUCCESS) {
231            loge("Error code "+initResult+" when initializing native AudioRecord object.");
232            return; // with mState == STATE_UNINITIALIZED
233        }
234
235        mSessionId = session[0];
236
237        mState = STATE_INITIALIZED;
238    }
239
240
241    // Convenience method for the constructor's parameter checks.
242    // This is where constructor IllegalArgumentException-s are thrown
243    // postconditions:
244    //    mRecordSource is valid
245    //    mChannelCount is valid
246    //    mChannelMask is valid
247    //    mAudioFormat is valid
248    //    mSampleRate is valid
249    private void More ...audioParamCheck(int audioSource, int sampleRateInHz,
250                                 int channelConfig, int audioFormat) {
251
252        //--------------
253        // audio source
254        if ( (audioSource < MediaRecorder.AudioSource.DEFAULT) ||
255             ((audioSource > MediaRecorder.getAudioSourceMax()) &&
256              (audioSource != MediaRecorder.AudioSource.HOTWORD)) )  {
257            throw new IllegalArgumentException("Invalid audio source.");
258        }
259        mRecordSource = audioSource;
260
261        //--------------
262        // sample rate
263        if ( (sampleRateInHz < 4000) || (sampleRateInHz > 48000) ) {
264            throw new IllegalArgumentException(sampleRateInHz
265                    + "Hz is not a supported sample rate.");
266        }
267        mSampleRate = sampleRateInHz;
268
269        //--------------
270        // channel config
271        switch (channelConfig) {
272        case AudioFormat.CHANNEL_IN_DEFAULT: // AudioFormat.CHANNEL_CONFIGURATION_DEFAULT
273        case AudioFormat.CHANNEL_IN_MONO:
274        case AudioFormat.CHANNEL_CONFIGURATION_MONO:
275            mChannelCount = 1;
276            mChannelMask = AudioFormat.CHANNEL_IN_MONO;
277            break;
278        case AudioFormat.CHANNEL_IN_STEREO:
279        case AudioFormat.CHANNEL_CONFIGURATION_STEREO:
280            mChannelCount = 2;
281            mChannelMask = AudioFormat.CHANNEL_IN_STEREO;
282            break;
283        case (AudioFormat.CHANNEL_IN_FRONT | AudioFormat.CHANNEL_IN_BACK):
284            mChannelCount = 2;
285            mChannelMask = channelConfig;
286            break;
287        default:
288            throw new IllegalArgumentException("Unsupported channel configuration.");
289        }
290
291        //--------------
292        // audio format
293        switch (audioFormat) {
294        case AudioFormat.ENCODING_DEFAULT:
295            mAudioFormat = AudioFormat.ENCODING_PCM_16BIT;
296            break;
297        case AudioFormat.ENCODING_PCM_16BIT:
298        case AudioFormat.ENCODING_PCM_8BIT:
299            mAudioFormat = audioFormat;
300            break;
301        default:
302            throw new IllegalArgumentException("Unsupported sample encoding."
303                    + " Should be ENCODING_PCM_8BIT or ENCODING_PCM_16BIT.");
304        }
305    }
306
307
308    // Convenience method for the contructor's audio buffer size check.
309    // preconditions:
310    //    mChannelCount is valid
311    //    mAudioFormat is AudioFormat.ENCODING_PCM_8BIT OR AudioFormat.ENCODING_PCM_16BIT
312    // postcondition:
313    //    mNativeBufferSizeInBytes is valid (multiple of frame size, positive)
314    private void More ...audioBuffSizeCheck(int audioBufferSize) {
315        // NB: this section is only valid with PCM data.
316        // To update when supporting compressed formats
317        int frameSizeInBytes = mChannelCount
318            * (mAudioFormat == AudioFormat.ENCODING_PCM_8BIT ? 1 : 2);
319        if ((audioBufferSize % frameSizeInBytes != 0) || (audioBufferSize < 1)) {
320            throw new IllegalArgumentException("Invalid audio buffer size.");
321        }
322
323        mNativeBufferSizeInBytes = audioBufferSize;
324    }

可以看到其中对audioSource的校验部分并没有做区分,所以理论上可以使用所有音频源

Android5.0.0_r1版本时,代码更新如下

222
223    public More ...AudioRecord(int audioSource, int sampleRateInHz, int channelConfig, int audioFormat,
224            int bufferSizeInBytes)
225    throws IllegalArgumentException {
226        this((new AudioAttributes.Builder())
227                    .setInternalCapturePreset(audioSource)
228                    .build(),
229                (new AudioFormat.Builder())
230                    .setChannelMask(getChannelMaskFromLegacyConfig(channelConfig,
231                                        true/*allow legacy configurations*/))
232                    .setEncoding(audioFormat)
233                    .setSampleRate(sampleRateInHz)
234                    .build(),
235                bufferSizeInBytes,
236                AudioManager.AUDIO_SESSION_ID_GENERATE);
237    }

并且增加了如下系统级初始化方法

Parameters:
attributes a non-null AudioAttributes instance. Use AudioAttributes.Builder.setCapturePreset(int) for configuring the capture preset for this instance.
format a non-null AudioFormat instance describing the format of the data that will be recorded through this AudioRecord. See AudioFormat.Builder for configuring the audio format parameters such as encoding, channel mask and sample rate.
bufferSizeInBytes the total size (in bytes) of the buffer where audio data is written to during the recording. New audio data can be read from this buffer in smaller chunks than this size. See getMinBufferSize(int,int,int) to determine the minimum required buffer size for the successful creation of an AudioRecord instance. Using values smaller than getMinBufferSize() will result in an initialization failure.
sessionId ID of audio session the AudioRecord must be attached to, or AudioManager.AUDIO_SESSION_ID_GENERATE if the session isn't known at construction time. See also AudioManager.generateAudioSessionId() to obtain a session ID before construction.
Throws:
java.lang.IllegalArgumentException
Hide:
CANDIDATE FOR PUBLIC API Class constructor with AudioAttributes and AudioFormat.
259
260    public More ...AudioRecord(AudioAttributes attributes, AudioFormat format, int bufferSizeInBytes,
261            int sessionId) throws IllegalArgumentException {
262        mRecordingState = RECORDSTATE_STOPPED;
263
264        if (attributes == null) {
265            throw new IllegalArgumentException("Illegal null AudioAttributes");
266        }
267        if (format == null) {
268            throw new IllegalArgumentException("Illegal null AudioFormat");
269        }
270
271        // remember which looper is associated with the AudioRecord instanciation
272        if ((mInitializationLooper = Looper.myLooper()) == null) {
273            mInitializationLooper = Looper.getMainLooper();
274        }
275
276        mAudioAttributes = attributes;
277
278        // is this AudioRecord using REMOTE_SUBMIX at full volume?
279        if (mAudioAttributes.getCapturePreset() == MediaRecorder.AudioSource.REMOTE_SUBMIX) {
280            final Iterator<String> tagsIter = mAudioAttributes.getTags().iterator();
281            while (tagsIter.hasNext()) {
282                if (tagsIter.next().equalsIgnoreCase(SUBMIX_FIXED_VOLUME)) {
283                    mIsSubmixFullVolume = true;
284                    Log.v(TAG, "Will record from REMOTE_SUBMIX at full fixed volume");
285                    break;
286                }
287            }
288        }
289
290        int rate = 0;
291        if ((format.getPropertySetMask()
292                & AudioFormat.AUDIO_FORMAT_HAS_PROPERTY_SAMPLE_RATE) != 0)
293        {
294            rate = format.getSampleRate();
295        } else {
296            rate = AudioSystem.getPrimaryOutputSamplingRate();
297            if (rate <= 0) {
298                rate = 44100;
299            }
300        }
301
302        int encoding = AudioFormat.ENCODING_DEFAULT;
303        if ((format.getPropertySetMask() & AudioFormat.AUDIO_FORMAT_HAS_PROPERTY_ENCODING) != 0)
304        {
305            encoding = format.getEncoding();
306        }
307
308        audioParamCheck(attributes.getCapturePreset(), rate, encoding);
309
310        mChannelCount = AudioFormat.channelCountFromInChannelMask(format.getChannelMask());
311        mChannelMask = getChannelMaskFromLegacyConfig(format.getChannelMask(), false);
312
313        audioBuffSizeCheck(bufferSizeInBytes);
314
315        int[] session = new int[1];
316        session[0] = sessionId;
317        //TODO: update native initialization when information about hardware init failure
318        //      due to capture device already open is available.
319        int initResult = native_setup( new WeakReference<AudioRecord>(this),
320                mAudioAttributes, mSampleRate, mChannelMask, mAudioFormat, mNativeBufferSizeInBytes,
321                session);
322        if (initResult != SUCCESS) {
323            loge("Error code "+initResult+" when initializing native AudioRecord object.");
324            return; // with mState == STATE_UNINITIALIZED
325        }
326
327        mSessionId = session[0];
328
329        mState = STATE_INITIALIZED;
330    }

跟踪对音频源的处理入口可以查到AudioAttributes.java中

Parameters:
preset
Returns:
the same Builder instance.
Hide:
Same as setCapturePreset(int) but authorizes the use of HOTWORD and REMOTE_SUBMIX.
525
526        public Builder More ...setInternalCapturePreset(int preset) {
527            if ((preset == MediaRecorder.AudioSource.HOTWORD)
528                    || (preset == MediaRecorder.AudioSource.REMOTE_SUBMIX)) {
529                mSource = preset;
530            } else {
531                setCapturePreset(preset);
532            }
533            return this;
534        }
535    };
536
537    @Override
538    public int More ...describeContents() {
539        return 0;
540    }

以及

Parameters:
preset one of MediaRecorder.AudioSource.DEFAULT, MediaRecorder.AudioSource.MIC, MediaRecorder.AudioSource.CAMCORDER, MediaRecorder.AudioSource.VOICE_RECOGNITION or MediaRecorder.AudioSource.VOICE_COMMUNICATION.
Returns:
the same Builder instance.
Hide:
Sets the capture preset. Use this audio attributes configuration method when building an AudioRecord instance with AudioRecord.(android.media.AudioAttributes,android.media.AudioFormat,int).
503
504        public Builder More ...setCapturePreset(int preset) {
505            switch (preset) {
506                case MediaRecorder.AudioSource.DEFAULT:
507                case MediaRecorder.AudioSource.MIC:
508                case MediaRecorder.AudioSource.CAMCORDER:
509                case MediaRecorder.AudioSource.VOICE_RECOGNITION:
510                case MediaRecorder.AudioSource.VOICE_COMMUNICATION:
511                    mSource = preset;
512                    break;
513                default:
514                    Log.e(TAG, "Invalid capture preset " + preset + " for AudioAttributes");
515            }
516            return this;
517        }

可以发现VOICE_CALL音频源已经不能使用,所以抛出Invalid capture preset异常

从代码中并不能发现为何MIC这个音频源为何在高版本无法录到通话对方的声音

这篇关于使用VOICE_CALL在Android5.0之后闪退bug源码解析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

网页解析 lxml 库--实战

lxml库使用流程 lxml 是 Python 的第三方解析库,完全使用 Python 语言编写,它对 XPath表达式提供了良好的支 持,因此能够了高效地解析 HTML/XML 文档。本节讲解如何通过 lxml 库解析 HTML 文档。 pip install lxml lxm| 库提供了一个 etree 模块,该模块专门用来解析 HTML/XML 文档,下面来介绍一下 lxml 库

中文分词jieba库的使用与实景应用(一)

知识星球:https://articles.zsxq.com/id_fxvgc803qmr2.html 目录 一.定义: 精确模式(默认模式): 全模式: 搜索引擎模式: paddle 模式(基于深度学习的分词模式): 二 自定义词典 三.文本解析   调整词出现的频率 四. 关键词提取 A. 基于TF-IDF算法的关键词提取 B. 基于TextRank算法的关键词提取

使用SecondaryNameNode恢复NameNode的数据

1)需求: NameNode进程挂了并且存储的数据也丢失了,如何恢复NameNode 此种方式恢复的数据可能存在小部分数据的丢失。 2)故障模拟 (1)kill -9 NameNode进程 [lytfly@hadoop102 current]$ kill -9 19886 (2)删除NameNode存储的数据(/opt/module/hadoop-3.1.4/data/tmp/dfs/na

Hadoop数据压缩使用介绍

一、压缩原则 (1)运算密集型的Job,少用压缩 (2)IO密集型的Job,多用压缩 二、压缩算法比较 三、压缩位置选择 四、压缩参数配置 1)为了支持多种压缩/解压缩算法,Hadoop引入了编码/解码器 2)要在Hadoop中启用压缩,可以配置如下参数

Makefile简明使用教程

文章目录 规则makefile文件的基本语法:加在命令前的特殊符号:.PHONY伪目标: Makefilev1 直观写法v2 加上中间过程v3 伪目标v4 变量 make 选项-f-n-C Make 是一种流行的构建工具,常用于将源代码转换成可执行文件或者其他形式的输出文件(如库文件、文档等)。Make 可以自动化地执行编译、链接等一系列操作。 规则 makefile文件

使用opencv优化图片(画面变清晰)

文章目录 需求影响照片清晰度的因素 实现降噪测试代码 锐化空间锐化Unsharp Masking频率域锐化对比测试 对比度增强常用算法对比测试 需求 对图像进行优化,使其看起来更清晰,同时保持尺寸不变,通常涉及到图像处理技术如锐化、降噪、对比度增强等 影响照片清晰度的因素 影响照片清晰度的因素有很多,主要可以从以下几个方面来分析 1. 拍摄设备 相机传感器:相机传

JAVA智听未来一站式有声阅读平台听书系统小程序源码

智听未来,一站式有声阅读平台听书系统 🌟&nbsp;开篇:遇见未来,从“智听”开始 在这个快节奏的时代,你是否渴望在忙碌的间隙,找到一片属于自己的宁静角落?是否梦想着能随时随地,沉浸在知识的海洋,或是故事的奇幻世界里?今天,就让我带你一起探索“智听未来”——这一站式有声阅读平台听书系统,它正悄悄改变着我们的阅读方式,让未来触手可及! 📚&nbsp;第一站:海量资源,应有尽有 走进“智听

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

pdfmake生成pdf的使用

实际项目中有时会有根据填写的表单数据或者其他格式的数据,将数据自动填充到pdf文件中根据固定模板生成pdf文件的需求 文章目录 利用pdfmake生成pdf文件1.下载安装pdfmake第三方包2.封装生成pdf文件的共用配置3.生成pdf文件的文件模板内容4.调用方法生成pdf 利用pdfmake生成pdf文件 1.下载安装pdfmake第三方包 npm i pdfma

零基础学习Redis(10) -- zset类型命令使用

zset是有序集合,内部除了存储元素外,还会存储一个score,存储在zset中的元素会按照score的大小升序排列,不同元素的score可以重复,score相同的元素会按照元素的字典序排列。 1. zset常用命令 1.1 zadd  zadd key [NX | XX] [GT | LT]   [CH] [INCR] score member [score member ...]