2012-01-02 148 views
10

我正在開發一個Android應用程序。我想要生成頻率範圍在1KHz到20KHz之間的聲音。無論如何,在特定頻率下產生聲音。如何生成特定的聲音頻率?

+1

您描述的範圍不是超聲波。即它仍然可以被聽到。 – Sjoerd 2012-01-02 08:04:21

+1

只是挑剔:超聲波_starts_在20KHz。你想要的範圍內的頻率是聲學的。 – 2012-01-02 08:04:59

+0

@alextsc,如果它在BlackBerry或Java-ME中,那麼也歡迎回答。 – Android 2012-01-02 08:05:26

回答

14

我從另一個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 <[email protected]> 
    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(); 
    } 
} 
+0

heh。我只是在這裏找到了同樣的東西(http://marblemice.blogspot.com/2010/04/generate-and-play-tone-in-android.html)。假設代碼在該鏈接處更新以修復錯誤。 – 2012-01-02 08:12:54

+0

是的,但根據評論它仍然有一些......無論哪種方式,它是一個偉大的基地。 – Reid 2012-01-02 08:15:33

+1

這個代碼有問題,因爲即使你設置了sampleRate = 44100,它也不能播放超過17000Hz的任何東西。這些相同的算法在Flash中工作,例如我使用的手機可以播放這些頻率,當它們來自文件。有誰知道如何解決這一問題? – PSIXO 2013-09-09 13:07:06