Playing an arbitrary tone with Android

后端 未结 10 2209
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 10:38

Is there any way to make Android emit a sound of arbitrary frequency (meaning, I don\'t want to have pre-recorded sound files)?

I\'ve looked around and ToneGenerator

10条回答
  •  没有蜡笔的小新
    2020-11-22 11:02

        float synth_frequency = 440;
        int minSize = AudioTrack.getMinBufferSize(SAMPLE_RATE,
    AudioFormat.CHANNEL_OUT_MONO,
    AudioFormat.ENCODING_PCM_16BIT);
    AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
    SAMPLE_RATE,
    AudioFormat.CHANNEL_OUT_MONO,
    AudioFormat.ENCODING_PCM_16BIT,
    minSize,
    AudioTrack.MODE_STREAM);
    audioTrack.play();
    short[] buffer = new short[minSize];
    float angle = 0;
    while (true) 
    {
        if (play)
        {
            for (int i = 0; i < buffer.length; i++)
            {
                float angular_frequency =
                (float)(2*Math.PI) * synth_frequency / SAMPLE_RATE;
                buffer[i] = (short)(Short.MAX_VALUE * ((float) Math.sin(angle)));
                angle += angular_frequency;
        }
            audioTrack.write(buffer, 0, buffer.length);
        } 
    

    // You can add arbitrary value in synth_frequency to get change sound for example you can add random variable to get sound

提交回复
热议问题