gpt4 book ai didi

android - 使用 Android 播放任意音调

转载 作者:IT老高 更新时间:2023-10-28 13:08:43 26 4
gpt4 key购买 nike

有什么方法可以让 Android 发出任意频率的声音(意思是,我不想有预先录制的声音文件)?

我环顾四周,发现 ToneGenerator是我能找到的唯一一个更接近的东西,但它似乎只能输出标准的 DTMF 音调。

有什么想法吗?

最佳答案

我最初发现 this example code在博客上,但它有一些错误,产生了一些可怕的声音。我已经修复了错误并在此处发布了生成的代码。似乎对我很有效!

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_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT, generatedSnd.length,
AudioTrack.MODE_STATIC);
audioTrack.write(generatedSnd, 0, generatedSnd.length);
audioTrack.play();
}
}

关于android - 使用 Android 播放任意音调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2413426/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com