Android:如何生成频率?
Android中是否有一种很好的方法来生成并播放频率(例如1000hz、245hz)?看看Android.media 您也可以尝试以下代码Android:如何生成频率?,android,audio,android-audiomanager,Android,Audio,Android Audiomanager,Android中是否有一种很好的方法来生成并播放频率(例如1000hz、245hz)?看看Android.media 您也可以尝试以下代码 public class PlaySound extends Activity { // originally from http://marblemice.blogspot.com/2010/04/generate-and-play-tone-in-android.html // and modified by Steve Pomeroy
public class PlaySound extends Activity {
// originally from http://marblemice.blogspot.com/2010/04/generate-and-play-tone-in-android.html
// and modified by Steve Pomeroy <steve@staticfree.info>
private final int duration = 3; // seconds
private final int sampleRate = 8000;
private final int numSamples = duration * sampleRate;
private final double sample[] = new double[numSamples];
private final double freqOfTone = 440; // hz
private final byte generatedSnd[] = new byte[2 * numSamples];
Handler handler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
protected void onResume() {
super.onResume();
// Use a new tread as this can take a while
final Thread thread = new Thread(new Runnable() {
public void run() {
genTone();
handler.post(new Runnable() {
public void run() {
playSound();
}
});
}
});
thread.start();
}
void genTone(){
// fill out the array
for (int i = 0; i < numSamples; ++i) {
sample[i] = Math.sin(2 * Math.PI * i / (sampleRate/freqOfTone));
}
// convert to 16 bit pcm sound array
// assumes the sample buffer is normalised.
int idx = 0;
for (final double dVal : sample) {
// scale to maximum amplitude
final short val = (short) ((dVal * 32767));
// in 16 bit wav PCM, first byte is the low order byte
generatedSnd[idx++] = (byte) (val & 0x00ff);
generatedSnd[idx++] = (byte) ((val & 0xff00) >>> 8);
}
}
void playSound(){
final AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT, numSamples,
AudioTrack.MODE_STATIC);
audioTrack.write(generatedSnd, 0, generatedSnd.length);
audioTrack.play();
}
}
public class PlaySound扩展活动{
//源于http://marblemice.blogspot.com/2010/04/generate-and-play-tone-in-android.html
//由史蒂夫·波默罗伊修改
私有最终整数持续时间=3;//秒
私人最终int采样器=8000;
私有最终整数样本=持续时间*采样器;
私人最终双样本[]=新双样本[numSamples];
专用最终双频通=440;//hz
生成的私有最终字节SND[]=新字节[2*个样本];
Handler=newhandler();
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@凌驾
受保护的void onResume(){
super.onResume();
//使用新胎面,因为这可能需要一段时间
最终线程线程=新线程(新可运行(){
公开募捐{
庚酮();
handler.post(新的Runnable(){
公开募捐{
播放声音();
}
});
}
});
thread.start();
}
void genTone(){
//填写数组
对于(int i=0;i>>8);
}
}
void playSound(){
最终音轨音轨=新音轨(AudioManager.STREAM_MUSIC,
采样器,AudioFormat.CHANNEL\u配置\u单声道,
AudioFormat.ENCODING_PCM_16位,数字样本,
音频跟踪模式(静态);
audioTrack.write(generatedSnd,0,generatedSnd.length);
音轨播放();
}
}