public class TaskMiActivity extends AppCompatActivity {
// private MidiPianoLayout midiPianoLayout;
TextView tv_tv1, tv_tv2;
Button btn_connect;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_mi);
tv_tv1 = findViewById(R.id.tv_tv1);
tv_tv2 = findViewById(R.id.tv_tv2);
fl_key = findViewById(R.id.fl_key);
btn_connect = findViewById(R.id.btn_connect);
btn_connect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openMidi();
}
});
}
void openMidi() {
MidiManager m = (MidiManager) getSystemService(Context.MIDI_SERVICE);
MidiDeviceInfo[] infos = m.getDevices();
if (infos != null && infos.length > 0) {
int num = 0;
for (int i = 0; i < infos.length; i++) {
if (infos[i].getOutputPortCount() != 0) {
num = i;
}
}
m.openDevice(infos[num], new MidiManager.OnDeviceOpenedListener() {
@Override
public void onDeviceOpened(MidiDevice device) {
if (device == null) {
Toast.makeText(getBaseContext(), "连接设备失败", Toast.LENGTH_SHORT).show();
} else {
MidiDeviceInfo.PortInfo[] ports = device.getInfo().getPorts();
for (int j = 0; j < ports.length; j++) {
if (ports[j].getType() == MidiDeviceInfo.PortInfo.TYPE_OUTPUT) {
int outputNum = ports[j].getPortNumber();
MidiOutputPort midiOutputPort = device.openOutputPort(outputNum);
if (midiOutputPort != null) {
midiOutputPort.connect(new MyReceiver());
Toast.makeText(getBaseContext(), "连接设备成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "连接设备失败", Toast.LENGTH_SHORT).show();
}
}
}
}
}
}, new Handler(Looper.getMainLooper()));
}
}
class MyReceiver extends MidiReceiver {
public void onSend(final byte[] data, final int offset,
final int count, final long timestamp) throws IOException {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (count == 3) {
int jw = data[2];
tv_tv1.setText("键位:" + jw + "-------" + data[3] + " -----" + offset + " -----" + count + " ---------" + timestamp);
Log.e("ContentValues", "键位:" + jw);
Log.e("ContentValues", "力道:" + data[3]);
Log.e("ContentValues", "count:" + count);
Log.e("ContentValues", "offset:" + offset);
Log.e("ContentValues", "timestamp:" + timestamp);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < data.length; i++) {
sb.append("key:" + i + "<-->");
sb.append("value:" + data[i]);
}
tv_tv2.setText("-----" + "所有数据:" + sb.toString());
}
}
});
}
}
}
android 判断是否连接钢琴和检测钢琴是哪个按键
最新推荐文章于 2021-03-17 18:29:25 发布