如何在 Android 上生成复杂的声音?
Posted
技术标签:
【中文标题】如何在 Android 上生成复杂的声音?【英文标题】:How to generate complex sound on Android? 【发布时间】:2013-07-31 08:47:46 【问题描述】:我需要在 android 上实时生成具有少量频率(叠加)的复杂声音。我如何使用 Android SDK(首选)或 NDK 来做到这一点?
似乎使用 ToneGenerator 不够灵活。 使用生成的声音数据录制 AudioTrack 并播放它似乎是正确的方向,但我需要实时它,并且录制和播放似乎不是实时的。
【问题讨论】:
【参考方案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;
【讨论】:
以上是关于如何在 Android 上生成复杂的声音?的主要内容,如果未能解决你的问题,请参考以下文章