我非常简单,可以枚举设备上的所有麦克风耳机
public class MainActivity
extends AppCompatActivity
{
private static String TAG = MainActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AudioManager audioManager =
(AudioManager) getSystemService(Context.AUDIO_SERVICE);
List<MicrophoneInfo> mics = null;
try
{
mics = audioManager.getMicrophones();
}
catch ( IOException e )
{
e.printStackTrace();
}
Log.d(TAG,"mics.size() = "+ mics.size());
for(MicrophoneInfo mic : mics)
{
}
}
}
但是当我在任何设备上运行应用程序时,都会得到
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.micsrc, PID: 8721
java.lang.NoSuchMethodError: No virtual method getMicrophones()Ljava/util/List;
in class Landroid/media/AudioManager; or its super classes (declaration
of 'android.media.AudioManager' appears in /system/framework/framework.jar)
at com.example.micsrc.MainActivity.onCreate(MainActivity.java:27)
at android.app.Activity.performCreate(Activity.java:6285)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2408)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2541)
at android.app.ActivityThread.access$900(ActivityThread.java:169)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1382)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5554)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:746)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:636)
答案 0 :(得分:3)
您需要处理向后兼容:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
List<MicrophoneInfo> mics = am.getMicrophones();
...
} else {
AudioDeviceInfo[] deviceInfo = am.getDevices(AudioManager.GET_DEVICES_INPUTS);
...
}
“耳机”连接器不是麦克风-但使用双工耳机时,它仍可能连接了麦克风...即使可能无法直接检测到该麦克风。 BT耳机甚至扬声器都可能带有麦克风,需要从A2DP接收器中查询。