使用AudioTrack生成频率

时间:2014-09-29 13:02:10

标签: android audiotrack

我找到了以下代码,它会产生' noise'。我希望能够产生一种音调。据我所知,有一种涉及SIN的公式可以产生音调。

此行生成噪音:rnd.nextBytes(noiseData);

我尝试手动为所有数组元素指定特定值,但之后没有声音。我发现了一个生成音调的代码,但它并没有流式传输。当我尝试将数据传递给我的代码时,会产生几秒钟的音调,然后应用程序崩溃。

任何建议如何从中产生音调?感谢

public class Internal extends Activity
{   
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);              
}

public void onPlayClicked(View v)
{
    start();    
}

public void onStopClicked(View v)
{
    stop();
}

boolean m_stop = false;
AudioTrack m_audioTrack;
Thread m_noiseThread;

Runnable m_noiseGenerator = new Runnable()
{       
    public void run()
    {
        Thread.currentThread().setPriority(Thread.MIN_PRIORITY);

        /* 8000 bytes per second, 1000 bytes = 125 ms */
        byte [] noiseData = new byte[1000];
        Random rnd = new Random();

        while(!m_stop)
        {           
            rnd.nextBytes(noiseData);   
            m_audioTrack.write(noiseData, 0, noiseData.length);                 
        }
    }
};

void start()
{
    m_stop = false;

    /* 8000 bytes per second*/
    m_audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 8000, AudioFormat.CHANNEL_OUT_MONO,
                                    AudioFormat.ENCODING_PCM_8BIT, 8000 /* 1 second buffer */,
                                    AudioTrack.MODE_STREAM);            

    m_audioTrack.play();        


    m_noiseThread = new Thread(m_noiseGenerator);
    m_noiseThread.start();
}

void stop()
{
    m_stop = true;          
    m_audioTrack.stop();
}   

}

这是生成音调的代码,但是当我将其输出提供给我的写入缓冲区时,它会播放一秒钟然后应用程序崩溃..即使我改变了音频格式.ENCODING_PCM_8BIT' to' AudioFormat.ENCODING_PCM_16BIT'

private final int duration = 1; // 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];
    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);

    }
}

1 个答案:

答案 0 :(得分:0)

确保您的noiseData缓冲区大小大于或等于最小缓冲区大小,AudioTrack将使用getMinBufferSize返回。

http://developer.android.com/reference/android/media/AudioTrack.html#getMinBufferSize(int, int, int)