2017-02-11 57 views
2

如何在Android 5中播放旋律,比如說440Hz,480Hz,500Hz,440Hz? 其他系統都有。像「聲音(440)」。 或者我必須用AudioTrack來合成它嗎?如何在android中播放旋律?

+0

你可以添加與您試圖代碼一些更多的信息? – Stefan

+1

是的你應該用'AudioTrack'完成它:http://stackoverflow.com/questions/9106276/android-how-to-generate-a-frequency – zed

回答

1

是的,您必須使用AudioTrack將其合成,正如@zed指出的那樣。

下面是一些一段代碼,應該可以幫助您

final static double scale = 1; 
final static int duration = 50; // Seconds 
final static int sampleRate = 22050; // Hz (maximum frequency is 7902.13Hz (B8)) 
final static int numSamples = duration * sampleRate; 
final static double samples[] = new double[numSamples]; 
final static short buffer[] = new short[numSamples]; 


double note = scale * frequency; 
for (int i = 0; i < numSamples; ++i) 
{ 
     samples[i] = Math.sin(2 * Math.PI * i/(sampleRate/note)); // Sine wave 
     buffer[i] = (short) (samples[i] * Short.MAX_VALUE); // Higher amplitude increases volume 
} 

audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,sampleRate,AudioFormat.CHANNEL_OUT_MONO, 
       AudioFormat.ENCODING_PCM_16BIT, buffer.length,AudioTrack.MODE_STATIC); 
audioTrack.write(buffer, 0, buffer.length);