2014-01-19 56 views

回答

0

這可能會幫助您:

public class GenerateAndPlaySound extends Activity { 
    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, generatedSnd.length, 
       AudioTrack.MODE_STATIC); 
     audioTrack.write(generatedSnd, 0, generatedSnd.length); 
     audioTrack.play(); 
    } 
} 
+0

不是一個直接的答案,但它是一個可行的解決方案。 –

+1

@ kagali-san我瞭解到您正在尋求將'ToneGenerator'的輸出寫入.wav文件的技術。此代碼僅創建一個440Hz的正弦波並通過audioTrack進行播放。所以,沒有'ToneGenerator',沒有wav保存。嗯 –

+0

這不回答原來的問題。這段代碼產生了音調,但它需要幾秒鐘的時間來完成,而且我需要的時間太長。 –

0

ToneGenerator指定生成的音頻數據寫入的輸出流類型。無法直接訪問生成的音頻數據。

當然,你可以記錄播放的音調,例如,通過內部麥克風。但這可能不是你想要的。

使用適當的audioSource,sampleRateInHz,channelConfig,audioFormat和streamType設置時,您還可以在某些設備上使用AudioRecord以數字方式將它們錄製。

關於AudioTrack,由於您必須使用write()方法,因此您必須能夠直接訪問音頻數據。