2014-09-29 84 views
0

我发现下面的代码会产生“噪音”。我希望能够产生一种音调。据我了解,有一些涉及SIN的公式可以产生声调。使用AudioTrack生成频率

该行生成噪声: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(); 
} 

}

这是产生一个音的代码,但是当我养活其输出到我写缓冲区,它扮演了一秒钟,然后应用程序崩溃..即使我改“ AudioFormat.ENCODING_PCM_8BIT”到‘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); 

    } 
} 

回答