当前位置: 首页 > 知识库问答 >
问题:

检查麦克风是否被其他应用程序使用?

叶经略
2023-03-14

当我启动音频/屏幕录像机并打开我的录音机应用程序并启动用于录制音频的服务时,我遇到错误该应用程序崩溃。
我不知道为什么我会面临这个问题。

来自logcat的错误跟踪

E/AndroidRuntime: FATAL EXCEPTION: main
        Process: com.example.babluboro.urecorder, PID: 10632
        java.lang.RuntimeException: Unable to start service com.example.babluboro.urecorder.RecordingService@dee6d7d with Intent { cmp=com.example.babluboro.urecorder/.RecordingService }: java.lang.IllegalStateException
            at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4145)
            at android.app.ActivityThread.access$2400(ActivityThread.java:229)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1924)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:7325)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
         Caused by: java.lang.IllegalStateException
            at android.media.MediaRecorder._start(Native Method)
            at android.media.MediaRecorder.start(MediaRecorder.java:943)
            at com.example.babluboro.urecorder.RecordingService.startRecording(RecordingService.java:126)
            at com.example.babluboro.urecorder.RecordingService.onStartCommand(RecordingService.java:97)
            at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4128)

录制服务.java

public class RecordingService extends Service {

    private String mFileName = null;
    private String mFilePath = null;

    private static final String LOG_TAG = "RecordingService";

    private MediaRecorder mRecorder = null;
    private DBHelper mDatabase;

    private long mStartingTimeMillis = 0;
    private long mElapsedMillis = 0;

    private static final String PREF_RECORDING_KEY = "prefs_recording_channel";
    private String channelType;


    @Override
    public void onCreate() {
        super.onCreate();
        mDatabase = new DBHelper(getApplicationContext());
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        channelType = sharedPreferences.getString(PREF_RECORDING_KEY, "0");
    }

    class MyServiceBinder extends Binder{

        public RecordingService getService(){
            return RecordingService.this;
        }
    }

    private IBinder mBinder = new MyServiceBinder();

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Intent notificationIntent = new Intent(this, RecordingActivity.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        notificationIntent.setAction(Intent.ACTION_MAIN);
        notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,
                0, notificationIntent, 0);

        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("URecorder")
                .setContentText("recording...")
                .setSmallIcon(R.drawable.microphone_icon)
                .setContentIntent(pendingIntent)
                .build();

        startForeground(1, notification);
        startRecording();

        return START_STICKY;
    }


    public void startRecording() {
        setFileNameAndPath();
        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mRecorder.setOutputFile(mFilePath);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);

        if(channelType == "Mono") {
            mRecorder.setAudioChannels(AudioFormat.CHANNEL_IN_MONO);
        }

        if(channelType == "Stereo"){
            mRecorder.setAudioChannels(AudioFormat.CHANNEL_IN_MONO);
        }

        if (MySharedPreferences.getPrefHighQuality(this)) {
            mRecorder.setAudioSamplingRate(44100);
            mRecorder.setAudioEncodingBitRate(96000);
        }

        try {
            mRecorder.prepare();
            mRecorder.start();
            mStartingTimeMillis = System.currentTimeMillis();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void setFileNameAndPath(){

        int count = 0;
        File f;

        do{
            count++;

            mFileName = "URecorder " + (mDatabase.getCount() + count)  + ".m4a";
            mFilePath = Environment.getExternalStorageDirectory().getAbsolutePath();
            mFilePath += "/URecorder/" + mFileName;

            f = new File(mFilePath);

        }while (f.exists() && !f.isDirectory());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (mRecorder != null) {
            Toast.makeText(this, "Recording Canceled", Toast.LENGTH_SHORT).show();
            mRecorder.stop();
            mRecorder.release();
            File file = new File(mFilePath);
            file.delete();
            mRecorder = null;
        }
    }


    public void stopRecording() {
        mRecorder.stop();
        mElapsedMillis = (System.currentTimeMillis() - mStartingTimeMillis);
        mRecorder.release();
        mRecorder = null;
        Toast.makeText(this,"Recording Saved ", Toast.LENGTH_SHORT).show();

        try {
            mDatabase.addRecording(mFileName, mFilePath, mElapsedMillis);

        } catch (Exception e){
            Log.e(LOG_TAG, "exception", e);
        }
    }
}

录音活动

    toolbar_main = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar_main);

        setSupportActionBar(toolbar_main);

        folderBtn = (ImageView) findViewById(R.id.folder_button);

        waveHeader = (MultiWaveHeader) findViewById(R.id.waveHeader);
        circleSpinner = (ImageView) findViewById(R.id.circleSpinner);
        pulsator = (PulsatorLayout) findViewById(R.id.pulsator);
        recordBtn = (ImageButton) findViewById(R.id.recordBtn);
        chronometer_id = (Chronometer) findViewById(R.id.chronometer_id);

        folderBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(RecordingActivity.this, AllRecordsActivity.class);
                startActivity(intent);
                chronometer_id.setBase(SystemClock.elapsedRealtime());

            }
        });

        recordBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onRecord(uStartRecording);
                uStartRecording = !uStartRecording;
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.settings_popup, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.settings:

                Intent intent = new Intent(RecordingActivity.this, SettingsActivity.class);
                startActivity(intent);
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }


    private void onRecord(boolean start) {

        serviceIntent = new Intent(this, RecordingService.class);
        recordBtn.setImageResource(R.drawable.save_icon);

        if (start) {

            bindService();
            folderBtn.setVisibility(View.GONE);
            pulsator.setCount(2);
            pulsator.start();

            File folder = new File(Environment.getExternalStorageDirectory() + "/URecorder");
            if (!folder.exists()) {
                folder.mkdir();
            }

            startService(serviceIntent);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

            rotation = AnimationUtils.loadAnimation(this, R.anim.rotate);
            rotation.setFillAfter(true);
            circleSpinner.startAnimation(rotation);

            chronometer_id.setBase(SystemClock.elapsedRealtime());
            chronometer_id.start();

        } else {
            folderBtn.setVisibility(View.VISIBLE);
            recordingService.stopRecording();
            unbindService(serviceConnection);
            isServiceBound = false;
            stopService(serviceIntent);
            recordBtn.setImageResource(R.drawable.microphone_icon);
            timeWhenPaused = chronometer_id.getBase() - SystemClock.elapsedRealtime();
            circleSpinner.clearAnimation();
            pulsator.stop();
            chronometer_id.stop();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            getPermissionToRecordAudio();
        }
    }

    public void getPermissionToRecordAudio() {

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){

            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)
                    || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                    || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage("Record, Read & Write External Storage permissions are required to do the task.");
                builder.setTitle("Please grant those permissions");
                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        ActivityCompat.requestPermissions(
                                RecordingActivity.this,
                                new String[]{
                                        Manifest.permission.RECORD_AUDIO,
                                        Manifest.permission.READ_EXTERNAL_STORAGE,
                                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                                },
                                RECORD_AUDIO_REQUEST_CODE
                        );
                    }
                });
                builder.setNeutralButton("Cancel",null);
                AlertDialog dialog = builder.create();
                dialog.show();

            }else{

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                    requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO,
                                    Manifest.permission.READ_EXTERNAL_STORAGE,
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                    RECORD_AUDIO_REQUEST_CODE);
                }
            }
        }
    }

    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        if (requestCode == RECORD_AUDIO_REQUEST_CODE) {
            if (grantResults.length == 3 &&
                    grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED
                    && grantResults[2] == PackageManager.PERMISSION_GRANTED){

                Toast.makeText(this, "Permissions granted.", Toast.LENGTH_SHORT).show();
            }
        } else {

            Toast.makeText(this,"Permissions denied.",Toast.LENGTH_SHORT).show();

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if(isServiceBound != false) {
            unbindService(serviceConnection);
            isServiceBound = false;
            stopService(serviceIntent);
        }
    }

    private void bindService(){

        if(serviceConnection == null){
            serviceConnection = new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                    RecordingService.MyServiceBinder myServiceBinder=(RecordingService.MyServiceBinder)iBinder;
                    recordingService = myServiceBinder.getService();
                    isServiceBound = true;
                }

                @Override
                public void onServiceDisconnected(ComponentName componentName) {
                    isServiceBound=false;
                }
            };
        }

        bindService(serviceIntent ,serviceConnection, Context.BIND_AUTO_CREATE);

    }
}

这就是我尝试在应用程序中开始录制时发生的情况
链接如下。

显示我的应用程序崩溃

共有2个答案

闻人和泽
2023-03-14

这是怎么做的

AudioManager am = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);

if(am.getMode()==AudioManager.MODE_IN_COMMUNICATION){
   //Mic is in use
}

MODE_NORMAL -> You good to go. Mic not in use
MODE_RINGTONE -> Incoming call. The phone is ringing
MODE_IN_CALL -> A phone call is in progress
MODE_IN_COMMUNICATION -> The Mic is being used by another application
袁鸿达
2023-03-14

我认为您没有使用麦克风的权限。请尝试将其添加到清单文件中。

这是许可:

<uses-permission android:name="android.permission.RECORD_AUDIO" />

将其放在应用程序块之外,如下所示:

...
    </application>

    <uses-permission android:name="android.permission.RECORD_AUDIO" /> 
</manifest>

然后,您可以使用此代码来检查麦克风是否在使用中:

private boolean validateMicAvailability(){
    Boolean available = true;
    AudioRecord recorder =
            new AudioRecord(MediaRecorder.AudioSource.MIC, 44100,
                    AudioFormat.CHANNEL_IN_MONO,
                    AudioFormat.ENCODING_DEFAULT, 44100);
    try{
        if(recorder.getRecordingState() != AudioRecord.RECORDSTATE_STOPPED ){
            available = false;

        }

        recorder.startRecording();
        if(recorder.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING){
            recorder.stop();
            available = false;

        }
        recorder.stop();
    } finally{
        recorder.release();
        recorder = null;
    }

    return available;
}
 类似资料:
  • 问题内容: 随着iOS 7的引入,应用程序在想要录制音频时必须请求访问麦克风。 如何检查应用程序是否可以访问麦克风? 在iOS 8 SDK中,我可以使用枚举,但是如何在iOS 7中进行检查? 信息: 我不想请求权限,我只想检查应用程序是否可以访问麦克风。(例如位置访问权限): 问题答案: 在这种情况下,无法获取..的当前状态。他们已将枚举指定为AVAudioSessionRecordPermiss

  • 问题内容: 我正在研究android voip应用程序。我想确定是否还有其他应用程序正在使用麦克风。因此,我想防止在使用时从其他应用程序访问麦克风。 请任何人有想法,这将对我非常有帮助。 谢谢, 问题答案: 终于知道我们可以按以下方式检查麦克风的可用性:

  • 使用光环板制作一个音量检测计,通过光环板的麦克风检测音量大小,并通过可视化的形式呈现出来,音量越大,LED灯环亮起的灯就越多。 1. 从事件类积木拖取一个 当按钮被按下时 积木。 2. 从控制类积木拖取一个 重复执行 积木。 3. 从灯光类积木拖取一个 显示LED环形图()% 积木,再添加一个传感器类积木 麦克风 响度。 4. 试着拍下桌子,看光环板LED环形图的变化吧! 下载代码

  • 简短版本: 我试图检测我的麦克风何时被像不和谐这样的程序捕获,最好是在Python中,但是我不知道如何做到这一点。有什么建议吗? 长版本: 我试图编写一个程序,每当我的麦克风被使用时,它就会打开“开机”灯。通常情况下,这要么是为了不和谐,要么是为了抽搐。这也是视窗系统已经监控的东西(视窗10),因为它在通知托盘中显示一个麦克风图标,并告诉你哪些程序正在使用你的麦克风。基本上,每当图标通知打开时,我

  • 大家好,我正在使用Peer Js创建一个WebRtc,就像一个视频通话一样,我只想创建一个按钮,当用户点击它时,关掉麦克风,这段代码在script.Js中: 这是Html代码: 所以我创建了这个按钮: 那么我如何制作一个能够禁用麦克风的脚本呢?

  • 问题内容: 我将如何使用pyaudio来检测现场麦克风的突然敲击声? 问题答案: 我这样做的一种方式: 一次读取一块样本,比如说值得0.05秒 计算块的RMS幅度(各个样本的平方的平均值的平方根) 如果块的RMS幅度大于阈值,则为“嘈杂的块”,否则为“安静的块” 突然的敲击将是一个安静的区域,然后是少量的噪音区域,然后是一个安静的区域 如果您从不安静,则门槛太低 如果您从不听到嘈杂的声音,则您的门