안드로이드 스튜디오에서 PCM데이터로 소리생성하기

조회수 3055회
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;


public class MainActivity extends Activity {
private final int duration = 10; // 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.activity_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.
    /**
     * The samples are created in floating points with an amplitude range from 0.0 to 1.0.
     * Multiply by 32767 would convert it into the 16-bit fixed point range.
     * The AudioTrack expects the buffer to be little endian format. Hence the next
     * two line just converts the byte order from big endian into little endia
     */
    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_OUT_MONO,
            AudioFormat.ENCODING_PCM_16BIT, generatedSnd.length,
            AudioTrack.MODE_STATIC);
    audioTrack.write(generatedSnd, 0, generatedSnd.length);
    audioTrack.play();
}
}

위의 코드는 PCM데이터가 아닌 임의의 데이터를 입력하여 소리를 생성한 코드입니다. 그런데 PCM데이터를 받아서 소리를 생성하려면,

  1. PCM데이터는 어떠한 형태로 입력받나요?
  2. 코드는 어떻게 바꾸어야할까요?
  • (•́ ✖ •̀)
    알 수 없는 사용자
  • 지금하는 방식과 동일하게 해서 (generatedSnd 생성) PCM 데이터를 일정 size만큼 받아서 동일하게 audioTrack.write 로 넣어주면 되지 않을까요,, PCM 데이터를 네트워크를 통해 받거나 파일로부터 일정 size 만큼 읽는 부분이 추가적으로 필요하겠네요 알 수 없는 사용자 2017.9.14 15:15

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)