7

如何在 Android 中轻松生成合成和弦声音?我希望能够使用 8 位动态生成游戏音乐。尝试使用AudioTrack,但还没有获得好的声音效果。

有什么例子吗?

我尝试了以下代码但没有成功:

public class BitLoose {
    private final int duration = 1; // seconds
    private final int sampleRate = 4200;
    private final int numSamples = duration * sampleRate;
    private final double sample[] = new double[numSamples];

    final AudioTrack audioTrack;

    public BitLoose() {
        audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
                sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO,
                AudioFormat.ENCODING_PCM_8BIT, numSamples,
                AudioTrack.MODE_STREAM);
        audioTrack.play();
    }

    public void addTone(final int freqOfTone) {
        // 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.
        final byte generatedSnd[] = new byte[numSamples];

        int idx = 0;
        for (final double dVal : sample) {
            // scale to maximum amplitude
            final short val = (short) ((((dVal * 255))) % 255);
            // in 16 bit wav PCM, first byte is the low order byte
            generatedSnd[idx++] = (byte) (val);
        }
        audioTrack.write(generatedSnd, 0, sampleRate);
    }

    public void stop() {
        audioTrack.stop();
    }
4

2 回答 2

2

我认为声音不好是由于音频格式:AudioFormat.ENCODING_PCM_8BIT 使用无符号样本,因此必须将 1 和 -1 之间的正弦转换为 0-255 字节值,试试这个:

for (final double dVal : sample) {
    final short val = (short) ((dVal + 1) / 2 * 255) ;
    generatedSnd[idx++] = (byte) val;
}

也尝试将采样率更改为 11025,因为某些设备可能不支持 4200:

private final int sampleRate = 11025;
于 2011-03-20T08:07:03.883 回答
0

除了答案 1,您应该使用:
sample[i] = Math.sin(2 * Math.PI * i / ( (double) sampleRate / freqOfTone));
而不是
sample[i] = Math.sin(2 * Math.PI * i / (sampleRate / freqOfTone));

于 2012-09-02T10:07:36.460 回答