4package org.qtproject.qt.android.multimedia;
6import java.util.ArrayList;
7import java.util.Arrays;
8import java.util.Comparator;
9import java.util.HashMap;
11import java.util.concurrent.atomic.AtomicInteger;
12import android.content.Context;
13import android.media.AudioDeviceCallback;
14import android.media.AudioDeviceInfo;
15import android.media.AudioFormat;
16import android.media.AudioManager;
17import android.media.AudioRecord;
18import android.media.AudioTrack;
19import android.media.MediaRecorder;
20import android.os.Build;
21import android.os.Handler;
22import android.os.Looper;
23import android.util.Log;
24import android.util.Range;
26import org.qtproject.qt.android.UsedFromNativeCode;
28class QtAudioDeviceManager
30 private static final String TAG =
"QtAudioDeviceManager";
32 static private AudioManager m_audioManager =
null;
33 static private final AudioDevicesReceiver m_audioDevicesReceiver =
new AudioDevicesReceiver();
34 static private Handler handler =
new Handler(Looper.getMainLooper());
35 static private AudioRecord m_recorder =
null;
36 static private AudioTrack m_streamPlayer =
null;
37 static private Thread m_streamingThread =
null;
38 static private boolean m_isStreaming =
false;
39 static private boolean m_useSpeaker =
false;
40 static private final int m_sampleRate = 8000;
41 static private final int m_channels = AudioFormat.CHANNEL_CONFIGURATION_MONO;
42 static private final int m_audioFormat = AudioFormat.ENCODING_PCM_16BIT;
43 static private final int m_bufferSize = AudioRecord.getMinBufferSize(m_sampleRate, m_channels, m_audioFormat);
44 static private int m_currentOutputId = -1;
45 static private AtomicInteger m_scoCounter =
new AtomicInteger();
46 static private AtomicInteger m_communicationDeviceCounter =
new AtomicInteger();
47 static private AtomicInteger m_speakerphoneCounter =
new AtomicInteger();
48 static private int m_currentCommunicationDeviceId = -1;
50 static native
void onAudioInputDevicesUpdated();
51 static native
void onAudioOutputDevicesUpdated();
53 static private void updateDeviceList() {
54 if (m_currentOutputId != -1)
55 prepareAudioOutput(m_currentOutputId);
56 onAudioInputDevicesUpdated();
57 onAudioOutputDevicesUpdated();
60 private static class AudioDevicesReceiver
extends AudioDeviceCallback {
73 static void registerAudioHeadsetStateReceiver()
75 m_audioManager.registerAudioDeviceCallback(m_audioDevicesReceiver, handler);
78 static void unregisterAudioHeadsetStateReceiver()
80 m_audioManager.unregisterAudioDeviceCallback(m_audioDevicesReceiver);
85 m_audioManager = (AudioManager)
context.getSystemService(
Context.AUDIO_SERVICE);
90 return getAudioDevices(AudioManager.GET_DEVICES_OUTPUTS);
95 return getAudioDevices(AudioManager.GET_DEVICES_INPUTS);
101 final AudioDeviceInfo[] audioDevices = m_audioManager.getDevices(AudioManager.GET_DEVICES_INPUTS);
104 if (deviceInfo.getId() ==
id)
112 static int getDefaultSampleRate()
114 String sampleRate = m_audioManager.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE);
115 return Integer.parseInt(sampleRate);
121 switch (deviceInfo.getType()) {
131 static boolean prepareAudioInput(
int id)
134 m_audioManager.getDevices(AudioManager.GET_DEVICES_INPUTS);
136 if (deviceInfo.getId() ==
id) {
137 switch (deviceInfo.getType())
144 return prepareAudioDevice(deviceInfo, AudioManager.MODE_NORMAL);
153 private static void setInputMuted(
boolean mute)
156 m_audioManager.setMicrophoneMute(mute);
159 private static boolean isMicrophoneMute()
161 return m_audioManager.isMicrophoneMute();
164 private static String audioDeviceTypeToString(
int type)
175 return "Built in earpiece";
177 return "Built in microphone";
179 return "Built in speaker";
193 return "Line analog";
195 return "Line digital";
199 return "USB accessory";
201 return "Wired headphones";
203 return "Wired headset";
207 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
212 return "Unknown-Type";
216 private static final HashMap<Integer, Integer> priorityMap =
new HashMap<Integer, Integer>() {{
223 private static final int DEFAULT_PRIORITY = 4;
226 Comparator<AudioDeviceInfo> deviceTypeComparator =
new Comparator<AudioDeviceInfo>() {
229 return getPriority(device1) - getPriority(device2);
233 return priorityMap.getOrDefault(
device.getType(), DEFAULT_PRIORITY);
237 Arrays.sort(
devices, deviceTypeComparator);
242 ArrayList<AudioDeviceInfo> filteredDevices =
new ArrayList<>();
244 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
245 boolean builtInMicAdded =
false;
246 boolean bluetoothDeviceAdded =
false;
248 sortAudioDevices(audioDevices);
257 if (builtInMicAdded) {
266 builtInMicAdded =
true;
267 }
else if (isBluetoothDevice(deviceInfo)) {
268 if (bluetoothDeviceAdded) {
274 bluetoothDeviceAdded =
true;
277 filteredDevices.add(deviceInfo);
281 return filteredDevices.toArray(
new AudioDeviceInfo[filteredDevices.size()]);
284 final private static int [] bluetoothTypes = {
286 AudioDeviceInfo.TYPE_BLUETOOTH_SCO
288 final private static int [] wiredTypes = {
290 AudioDeviceInfo.TYPE_WIRED_HEADPHONES
297 .flatMapToInt(Arrays::stream)
303 AudioManager.MODE_IN_COMMUNICATION : AudioManager.MODE_NORMAL;
308 return getCorrectModeIfContainsAnyOfType(audioDevices, bluetoothTypes);
313 return getCorrectModeIfContainsAnyOfType(audioDevices, wiredTypes);
318 return getCorrectModeIfContainsAnyOfType(audioDevices, bluetoothTypes, wiredTypes);
321 private static boolean prepareAudioOutput(
int id)
324 m_audioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS);
326 if (deviceInfo.getId() ==
id) {
327 switch (deviceInfo.getType())
331 return prepareAudioDevice(deviceInfo, getModeForBluetooth(audioDevices));
333 return prepareAudioDevice(deviceInfo, getModeForSpeaker(audioDevices));
336 return prepareAudioDevice(deviceInfo, getModeForWired(audioDevices));
341 Log.w(TAG,
"Built in Earpiece may not work when "
342 +
"Wired Headphones are connected");
343 return prepareAudioDevice(deviceInfo, AudioManager.MODE_IN_CALL);
347 return prepareAudioDevice(deviceInfo, AudioManager.MODE_NORMAL);
364 if (isBluetoothDevice(
device)) {
368 boolean isSameType = communicationDevice.getType() ==
device.getType();
369 boolean isSameAddress = communicationDevice.getAddress().equals(
device.getAddress());
370 if (isSameType && isSameAddress)
371 return communicationDevice;
374 Log.w(TAG,
"No matching bluetooth output device found for " +
device);
381 if (m_currentCommunicationDeviceId == -1 ||
device ==
null) {
385 return m_currentCommunicationDeviceId ==
device.getId();
389 static void releaseAudioDevice(
int id) {
393 releaseAudioDevice(
device);
401 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
403 AudioDeviceInfo communicationDevice = getValidCommunicationDevice(deviceInfo);
404 if (!deviceIsCurrentCommunicationDevice(communicationDevice))
407 if (m_communicationDeviceCounter.decrementAndGet() == 0) {
408 m_audioManager.clearCommunicationDevice();
409 m_currentCommunicationDeviceId = -1;
411 }
else if (isBluetoothDevice(deviceInfo) && m_audioManager.isBluetoothScoOn()
412 && m_scoCounter.decrementAndGet() == 0) {
413 m_audioManager.stopBluetoothSco();
414 m_audioManager.setBluetoothScoOn(
false);
415 }
else if (deviceInfo.getType() ==
AudioDeviceInfo.TYPE_BUILTIN_SPEAKER
416 && m_speakerphoneCounter.decrementAndGet() == 0) {
417 m_audioManager.setSpeakerphoneOn(
false);
423 if (deviceInfo ==
null)
426 m_audioManager.setMode(
mode);
428 boolean isSink = deviceInfo.isSink();
430 m_currentOutputId = deviceInfo.getId();
432 boolean isBluetoothDevice = isBluetoothDevice(deviceInfo);
433 boolean isBluetoothSource = isBluetoothDevice && !isSink;
434 boolean isCommunicationMode = (
mode == AudioManager.MODE_IN_CALL
435 ||
mode == AudioManager.MODE_IN_COMMUNICATION);
437 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
438 if (!isBluetoothSource && !isCommunicationMode)
442 AudioDeviceInfo communicationDevice = getValidCommunicationDevice(deviceInfo);
443 if (communicationDevice ==
null) {
444 Log.w(TAG,
"No suitable communication device to set to enable communication via "
445 + deviceInfo.getId());
449 if (deviceIsCurrentCommunicationDevice(communicationDevice)) {
450 m_communicationDeviceCounter.incrementAndGet();
452 }
else if (m_audioManager.setCommunicationDevice(communicationDevice)) {
458 m_currentCommunicationDeviceId = communicationDevice.getId();
459 m_communicationDeviceCounter.set(1);
466 boolean isSpeakerphoneDevice = deviceInfo.getType() ==
AudioDeviceInfo.TYPE_BUILTIN_SPEAKER;
468 if (isBluetoothSource && m_scoCounter.getAndIncrement() == 0) {
469 m_audioManager.startBluetoothSco();
470 m_audioManager.setBluetoothScoOn(
true);
471 }
else if (isSpeakerphoneDevice
472 && m_speakerphoneCounter.getAndIncrement() == 0) {
475 m_audioManager.setSpeakerphoneOn(
true);
481 private static void streamSound()
483 byte data[] =
new byte[m_bufferSize];
484 while (m_isStreaming) {
485 m_recorder.read(
data, 0, m_bufferSize);
486 m_streamPlayer.play();
487 m_streamPlayer.write(
data, 0, m_bufferSize);
488 m_streamPlayer.stop();
492 private static void startSoundStreaming(
int inputId,
int outputId)
495 stopSoundStreaming();
497 m_recorder =
new AudioRecord(MediaRecorder.AudioSource.DEFAULT, m_sampleRate, m_channels,
498 m_audioFormat, m_bufferSize);
499 m_streamPlayer =
new AudioTrack(AudioManager.STREAM_MUSIC, m_sampleRate, m_channels,
500 m_audioFormat, m_bufferSize, AudioTrack.MODE_STREAM);
504 if (deviceInfo.getId() == outputId) {
505 m_streamPlayer.setPreferredDevice(deviceInfo);
506 }
else if (deviceInfo.getId() == inputId) {
507 m_recorder.setPreferredDevice(deviceInfo);
511 m_recorder.startRecording();
512 m_isStreaming =
true;
514 m_streamingThread =
new Thread(
new Runnable() {
521 m_streamingThread.start();
524 private static void stopSoundStreaming()
529 m_isStreaming =
false;
531 m_streamingThread.join();
532 m_streamingThread =
null;
533 }
catch (InterruptedException e) {
537 m_recorder.release();
538 m_streamPlayer.release();
539 m_streamPlayer =
null;
void AudioDeviceInfo()
[Audio callback capture setup peak meter]
IOBluetoothDevice * device
static const QString context()
QTCONCURRENT_RUN_NODISCARD auto run(QThreadPool *pool, Function &&f, Args &&...args)
GLsizei GLenum GLenum * types
GLint GLsizei GLsizei GLenum GLenum GLsizei void * data
[0]
static int compare(quint64 a, quint64 b)
static QInputDevice::DeviceType deviceType(const UINT cursorType)
manager put(request, myData, this, [this](QRestReply &reply) { if(reply.isSuccess()) })
[5]