java - Android 6.0(棉花糖): How to play midi notes?

标签 java android audio midi android-6.0-marshmallow

我正在创建一个生成现场乐器声音的应用程序,并且我计划使用 Android Marshmallow(版本 6.0)中的新 Midi API。我在这里阅读了包概述文档 http://developer.android.com/reference/android/media/midi/package-summary.html我知道如何生成 Midi 音符,但我仍然不确定:在生成这些音符的 Midi 数据后,我该如何实际演奏这些音符?

我需要合成器程序来播放 Midi 音符吗?如果是这样,我必须自己制作还是由 Android 或第三方提供?

我是 Midi 的新手,所以请尽可能描述您的回答。

到目前为止我尝试了什么: 我创建了一个 Midi 管理器对象并打开了一个输入端口

MidiManager m = (MidiManager)context.getSystemService(Context.MIDI_SERVICE); 
MidiInputPort inputPort = device.openInputPort(index);

然后,我向端口发送了一条测试 noteOn midi 消息

byte[] buffer = new byte[32];
int numBytes = 0;
int channel = 3; // MIDI channels 1-16 are encoded as 0-15.
buffer[numBytes++] = (byte)(0x90 + (channel - 1)); // note on
buffer[numBytes++] = (byte)60; // pitch is middle C
buffer[numBytes++] = (byte)127; // max velocity
int offset = 0;
// post is non-blocking
inputPort.send(buffer, offset, numBytes);

我还设置了一个类来接收 midi 音符消息

class MyReceiver extends MidiReceiver {
    public void onSend(byte[] data, int offset,
            int count, long timestamp) throws IOException {
        // parse MIDI or whatever
    }
}
MidiOutputPort outputPort = device.openOutputPort(index);
outputPort.connect(new MyReceiver());

现在,这是我最困惑的地方。我的应用程序的用例是成为用于制作音乐的一体化作曲和播放工具。换句话说,我的应用程序需要包含或使用虚拟 MIDI 设备(例如另一个应用程序的 MIDI 合成器的 Intent )。除非有人已经制作了这样的合成器,否则我必须在我的应用程序生命周期内自己创建一个。我如何实际将接收到的 midi noteOn() 转换为从我的扬声器发出的声音?我特别困惑,因为还必须有一种方法来以编程方式确定音符听起来像是来自哪种乐器:这也在合成器中完成吗?

Android Marshmallow 中的 Midi 支持是相当新的,所以我无法在线找到任何教程或示例合成器应用程序。感谢任何见解。

最佳答案

我还没有找到任何“官方”方法来从 Java 代码控制内部合成器。

可能最简单的选择是使用 Android midi driver for the Sonivox synthesizer .

获取as an AAR package (解压缩 *.zip)并将 *.aar 文件存储在您工作区的某个位置。路径并不重要,它不需要位于您自己的应用程序的文件夹结构中,但项目中的“libs”文件夹可能是一个合乎逻辑的位置。

在 Android Studio 中打开您的 Android 项目:

File -> New -> New Module -> Import .JAR/.AAR Package -> Next -> Find and select the "MidiDriver-all-release.aar" and change the subproject name if you want. -> Finish

等待 Gradle 发挥它的魔力,然后转到“应用程序”模块的设置(您自己的应用程序项目的设置)到“依赖项”选项卡并添加(带有绿色“+”符号)MIDI 驱动程序作为模块依赖。现在您可以访问 MIDI 驱动程序了:

import org.billthefarmer.mididriver.MidiDriver;
   ...
MidiDriver midiDriver = new MidiDriver();

无需担心 NDK 和 C++,您可以使用这些 Java 方法:

// Not really necessary. Receives a callback when/if start() has succeeded.
midiDriver.setOnMidiStartListener(listener);
// Starts the driver.
midiDriver.start();
// Receives the driver's config info.
midiDriver.config();
// Stops the driver.
midiDriver.stop();
// Just calls write().
midiDriver.queueEvent(event);
// Sends a MIDI event to the synthesizer.
midiDriver.write(event);

播放和停止音符的非常基本的“概念证明”可能是这样的:

package com.example.miditest;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;

import org.billthefarmer.mididriver.MidiDriver;

public class MainActivity extends AppCompatActivity implements MidiDriver.OnMidiStartListener,
        View.OnTouchListener {

    private MidiDriver midiDriver;
    private byte[] event;
    private int[] config;
    private Button buttonPlayNote;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        buttonPlayNote = (Button)findViewById(R.id.buttonPlayNote);
        buttonPlayNote.setOnTouchListener(this);

        // Instantiate the driver.
        midiDriver = new MidiDriver();
        // Set the listener.
        midiDriver.setOnMidiStartListener(this);
    }

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

        // Get the configuration.
        config = midiDriver.config();

        // Print out the details.
        Log.d(this.getClass().getName(), "maxVoices: " + config[0]);
        Log.d(this.getClass().getName(), "numChannels: " + config[1]);
        Log.d(this.getClass().getName(), "sampleRate: " + config[2]);
        Log.d(this.getClass().getName(), "mixBufferSize: " + config[3]);
    }

    @Override
    protected void onPause() {
        super.onPause();
        midiDriver.stop();
    }

    @Override
    public void onMidiStart() {
        Log.d(this.getClass().getName(), "onMidiStart()");
    }

    private void playNote() {

        // Construct a note ON message for the middle C at maximum velocity on channel 1:
        event = new byte[3];
        event[0] = (byte) (0x90 | 0x00);  // 0x90 = note On, 0x00 = channel 1
        event[1] = (byte) 0x3C;  // 0x3C = middle C
        event[2] = (byte) 0x7F;  // 0x7F = the maximum velocity (127)

        // Internally this just calls write() and can be considered obsoleted:
        //midiDriver.queueEvent(event);

        // Send the MIDI event to the synthesizer.
        midiDriver.write(event);

    }

    private void stopNote() {

        // Construct a note OFF message for the middle C at minimum velocity on channel 1:
        event = new byte[3];
        event[0] = (byte) (0x80 | 0x00);  // 0x80 = note Off, 0x00 = channel 1
        event[1] = (byte) 0x3C;  // 0x3C = middle C
        event[2] = (byte) 0x00;  // 0x00 = the minimum velocity (0)

        // Send the MIDI event to the synthesizer.
        midiDriver.write(event);

    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        Log.d(this.getClass().getName(), "Motion event: " + event);

        if (v.getId() == R.id.buttonPlayNote) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                Log.d(this.getClass().getName(), "MotionEvent.ACTION_DOWN");
                playNote();
            }
            if (event.getAction() == MotionEvent.ACTION_UP) {
                Log.d(this.getClass().getName(), "MotionEvent.ACTION_UP");
                stopNote();
            }
        }

        return false;
    }
}

布局文件只有一个按钮,按下时播放预定义的音符,松开时停止:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.miditest.MainActivity"
    android:orientation="vertical">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Play a note"
        android:id="@+id/buttonPlayNote" />
</LinearLayout>

其实就是这么简单。上面的代码很可能是触摸钢琴应用程序的起点,该应用程序具有 128 种可选乐器、非常不错的延迟和许多应用程序所缺乏的适当的“音符关闭”功能。

至于选择乐器:您只需将 MIDI“程序更改”消息发送到您打算演奏的 channel ,以从通用 MIDI 音色集中的 128 种声音中选择一种。但这与 MIDI 的细节有关,与库的使用无关。

同样,您可能希望抽象出 MIDI 的低级细节,以便您可以轻松地在特定 channel 上使用特定乐器以特定速度在特定时间播放特定音符,为此您可能会发现一些迄今为止所有开源 Java 和 MIDI 相关应用程序和库的线索。

顺便说一下,这种方法不需要 Android 6.0。而此刻only 4.6 % of devices visiting the Play Store run Android 6.x因此您的应用不会有太多受众。

当然,如果您想使用 android.media.midi 包,您可以使用该库来实现 android.media.midi.MidiReceiver 来接收MIDI 事件并在内部合成器上播放它们。谷歌已经有一些 demo code that plays notes with square and saw waves .只需将其替换为内部合成器即可。

其他一些选项可能是检查移植的状态FluidSynth到安卓。我想可能会有一些可用的东西。

编辑:其他可能有趣的库:

关于java - Android 6.0(棉花糖): How to play midi notes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36193250/

相关文章:

java - 需要帮助优化涉及数百万条记录的非常慢的 DB2 SQL 查询

android - 自定义工具栏设置不正确

android - Android下Phonegap中的SoundCloud Stream

java - 如何将主题设置为另一个 Activity 的主要 Activity ?

java - 有没有办法获取给定日期字符串或 LocalDate 的模式

Android:如何在 android 4.2 上折叠状态栏?

android - androidstudio HTTPCore version.properties中的重复文件异常

javascript - 如何在 javascript 中的音频 blob 上设置编解码器、采样率和比特率?

javascript - 声音波形是如何存储然后显示在 SoundCloud 上的?

java - 如何从 vector 内的数组中读取?