0

我需要在 Android 上实时生成具有很少频率(叠加)的复杂声音。我如何使用 Android SDK(首选)或 NDK 来做到这一点?

使用 ToneGenerator 似乎不够灵活。使用生成的声音数据录制 AudioTrack 并播放它似乎是正确的方向,但我需要实时它,并且录制和播放似乎不是实时的。

4

1 回答 1

1

Shawn Van Every 的“Pro Android Media”一书中的一个例子:

import android.app.Activity;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class AudioSynthesis extends Activity implements OnClickListener {
    Button startSound;
    Button endSound;

AudioSynthesisTask audioSynth;
boolean keepGoing = false;
float synth_frequency = 440; // 440 Hz, Middle A

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    startSound = (Button) this.findViewById(R.id.StartSound);
    startSound.setOnClickListener(this);
    endSound = (Button) this.findViewById(R.id.EndSound);
    endSound.setOnClickListener(this);
    endSound.setEnabled(false);
}

@Override
public void onPause() {
    super.onPause();
    keepGoing = false;
    endSound.setEnabled(false);
    startSound.setEnabled(true);
}

public void onClick(View v) {
    if (v == startSound) {
        keepGoing = true;
        audioSynth = new AudioSynthesisTask();
        audioSynth.execute();
        endSound.setEnabled(true);
        startSound.setEnabled(false);
    } else if (v == endSound) {
        keepGoing = false;
        endSound.setEnabled(false);
        startSound.setEnabled(true);
    }
}

private class AudioSynthesisTask extends AsyncTask<Void, Void, Void>
{
    @Override
    protected Void doInBackground(Void... params) {
        final int SAMPLE_RATE= 11025;
        int minSize = AudioTrack.getMinBufferSize(SAMPLE_RATE,
                AudioFormat.CHANNEL_CONFIGURATION_MONO,
                AudioFormat.ENCODING_PCM_16BIT);
        AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
            SAMPLE_RATE,
            AudioFormat.CHANNEL_CONFIGURATION_MONO,
            AudioFormat.ENCODING_PCM_16BIT,
            minSize,
            AudioTrack.MODE_STREAM);
    audioTrack.play();
    short[] buffer = new short[minSize];
    float angular_frequency =
       (float)(2*Math.PI) * synth_frequency / SAMPLE_RATE;
    float angle = 0;
    while (keepGoing) {
         for (int i = 0; i < buffer.length; i++)
         {
             buffer[i] = (short)(Short.MAX_VALUE * ((float) Math.sin(angle)));
             angle += angular_frequency;
         }
         audioTrack.write(buffer, 0, buffer.length);
    }
    return null;
}
} }
于 2013-08-22T10:15:21.353 回答