본문 바로가기
Android

AudioTrack을 이용한 짧은 파일 재생방법

by CodeDiver 2013. 10. 30.

출처: http://darksilber.tistory.com/61

소스파일: 

ExAudioPlay_SRC.zip





/**

 * 짧은 데이터 재생 (byte 배열을 입력)

 */

private void PlayShortAudioData(byte[] byteData) {


// Set and push to audio track..

int intSize = android.media.AudioTrack.getMinBufferSize(RECORDER_SAMPLERATE,

                                                                                AudioFormat.CHANNEL_CONFIGURATION_MONO,  

                                                                                AudioFormat.ENCODING_PCM_16BIT);


AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, RECORDER_SAMPLERATE, 

AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, 

intSize, 

AudioTrack.MODE_STREAM);


if (at != null) {

at.play();

// Write the byte array to the track

at.write(byteData, 0, byteData.length);

at.stop();

at.release();

}



// sdcard 파일경로 입력

private void PlayShortAudioFileViaAudioTrack(String filePath) throws IOException {

// We keep temporarily filePath globally as we have only two sample sounds now..

if (filePath == null)

return;


// Reading the file..

byte[] byteData = null;

File file = null;

file = new File(filePath); // for ex. path= "/sdcard/samplesound.pcm" or "/sdcard/samplesound.wav"

byteData = new byte[(int) file.length()];

FileInputStream in = null;


try {

in = new FileInputStream(file);

in.read(byteData);

in.close();


} catch (FileNotFoundException e) {

e.printStackTrace();

}

// Set and push to audio track..

int intSize = android.media.AudioTrack.getMinBufferSize(48000, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT);

AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, 48000, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, intSize, AudioTrack.MODE_STREAM);


if (at != null) {

at.play();

// Write the byte array to the track

at.write(byteData, 0, byteData.length);

at.stop();

at.release();

else {

Log.d("TCAudio", "audio track is not initialised ");

}

}


'Android' 카테고리의 다른 글

금융계산기 - 2013  (0) 2013.10.31
Assets file 읽기  (0) 2013.10.30
AudioRecord 를 이용한 녹음하는 소스  (0) 2013.10.28
Android NDK JNI - 정리 잘됨  (0) 2013.10.28
[Android] 오디오 녹음하는 3가지 방법  (2) 2013.10.25