android 声音频率动画,android – 如何生成特定的声音频率?

这段代码展示了一个Java活动类,用于生成特定频率的音调并将其播放出来。通过计算正弦波数组来创建声音样本,然后将其转换为16位PCM格式,最后使用AudioTrack API播放声音。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我从另一个SO帖子中找到了这段代码.从我可以说它仍然是一个小马车但它应该做的伎俩.

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

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();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值