public boolean initOnThisThread(boolean isRightChannel, int sampleRate) { this.sampleRate = sampleRate; if (portDevices.size() == 0) { Log.w(TAG, "No devices found"); return false; } UsbAudioDevice device; // Right devices has the higher port if (portDevices.size() == 2) { Iterator<IntObjectCursor<UsbAudioDevice>> c = portDevices.iterator(); UsbAudioDevice first = c.next().value; UsbAudioDevice second = c.next().value; int port; if (isRightChannel) { port = Math.max(first.getPort(), second.getPort()); } else { port = Math.min(first.getPort(), second.getPort()); } device = portDevices.get(port); } else { Iterator<IntObjectCursor<UsbAudioDevice>> c = portDevices.iterator(); device = c.next().value; } port = device.getPort(); portReceivers.put(port, this); device = portDevices.get(port); this.nativeSampleRate = device.getDescriptor().sampleRate; byteBuffer = ByteBuffer.allocateDirect(this.nativeSampleRate); // 1s tmpShortBuffer = new short[byteBuffer.capacity() / 2]; if (sampleRate != nativeSampleRate && sampleRate != (nativeSampleRate / 2)) { Log.e(TAG, "Sample rate != nativeSampleRate or nativeSampleRate / 2"); return false; } return device.beginReadAudio(); }
public static void initUsbAudioDevices() { if (isInitted) return; UsbDevice[] rawUsbDevices = UsbAudioDriver.getAttachedAudioDevices(); ArrayList<UsbAudioDevice> audioDevices = new ArrayList<>(); for (UsbDevice rawUsbDevice : rawUsbDevices) { Log.d(TAG, rawUsbDevice.getDeviceName()); UsbAudioDeviceDescriptor deviceDescriptor = KnownDevices.findByVenderProduct(rawUsbDevice.getVendorId(), rawUsbDevice.getProductId()); if (deviceDescriptor == null) { Log.d(TAG, "Found unknown device " + rawUsbDevice.getDeviceName()); } final UsbAudioDevice audioDevice = new UsbAudioDevice( deviceDescriptor, rawUsbDevice.getDeviceName(), (device, data, length) -> { writeToPort(data, length, device.getPort()); }); portDevices.put(audioDevice.getPort(), audioDevice); } isInitted = true; }
@Override public void stop() { device.close(); }