이 예제는 시작하면 비프음(삐-) 소리가 나므로 주의하길 바란다.
public class MainActivity extends Activity {
PlayAudioTask task = new PlayAudioTask();
class PlayAudioTask extends AsyncTask<Void, Integer, Void> {
final static String TAG = "PlayAudioTask";
int streamType = AudioManager.STREAM_MUSIC;
int sampleRateInHz = 44100;
//int sampleRateInHz = 11025;
//int sampleRateInHz = 22050;
int channelConfig = CHANNEL_OUT_MONO;
int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
int mode = AudioTrack.MODE_STATIC;
// 몇초간 플레이 할것인지 정의함
// 1초에는 short bytes * 44100이 필요함
// 1초를 그렇게 많이 쪼갠다는 뜻인가?
int seconds = 2;
short[] samples = new short[sampleRateInHz * seconds];
// 1초간 4000번 상한과 하한을 진동함
int freqOfTone = 4000;
int bufferSizeInBytes = sampleRateInHz * seconds * 2;
@Override
protected Void doInBackground(Void... params) {
// init audio
//int streamType, int sampleRateInHz, int channelConfig, int audioFormat, int bufferSizeInBytes, int mode
final AudioTrack track = new AudioTrack(streamType, sampleRateInHz, channelConfig, audioFormat, bufferSizeInBytes, mode);
double angle = 0;
double increment = (2 * Math.PI * freqOfTone / sampleRateInHz); // angular increment
for (int i = 0; i < samples.length; i++) {
// 사인파(Sine wave)
samples[i] = (short) (Math.sin(angle) * Short.MAX_VALUE);
// Log.d(TAG, "sample i=" + i + " value=" + samples[i]);
// 파일 내용 저장하자.
angle += increment;
}
track.write(samples, 0, samples.length);
track.play();
// TODO Auto-generated method stub
return null;
}
}
다운로드
No comments:
Post a Comment