[TIL] Unity - AudioSource (2)

MINO·2024년 6월 7일
0
post-thumbnail

2024-06-07


AudioSource 스크립팅

하나의 AudioSource 에 여러 Clip 들을 재생시키기 위해
AudioSource 와 함께 사용되는 여러 메서드를 살펴보았다.

private AudioSource audioSource;

private void Start()
{
	audioSource = GetComponent<AudioSource>();
}

변수

clip

오디오 소스에서 재생할 오디오 클립을 설정

public AudioClip hornSound;

audioSource.clip = hornSound; 

isPlaying

현재 오디오 소스에 클립이 재생 중이라면 true, 그렇지 않다면 false 를 반환

if(!audioSource.isPlaying)
	audioSource.Play();

loop

오디오 소스의 루프 상태를 설정

audioSource.loop = true; // 현재 clip 을 반복 재생
audioSource.loop = false; // 한 번 재생하고 끝

등의 방식으로 사용된다.


Public 함수

Play() / Pause() / UnPause() / Stop()

현재 오디오 클립을 재생 / 일시 정지 / 다시 재생 / 재생 중지

audioSource.Play();
audioSource.Pause();
audioSource.UnPause();
audioSource.Stop();

PlayOneShot(AudioClip clip1, float volume)

특정 클립을 한 번만 재생 , 볼륨 조절 가능

audioSource.PlayOneShot(clip1 , 0.5f); // 클립1을 0.5 볼륨으로 한 번만 재생

PlayScheduled(double time)

Plays the clip at a specific time on the absolute time-line that AudioSettings.dspTime reads from.
(AudioSettings.dspTime이 읽는 절대 타임라인의 특정 시간에 클립을 재생)


DSP Time (Digital Signaling Processing)

디지털 신호 관련된 처리 시간

  • 초 단위로 지정
  • 오디오 시스템에서 처리된 실제 오디오 샘플 수에 기반하여 반환되는 double 형의 시간
  • Time.time 으로 얻은 시간보다 훨씬 더 정확
  • AudioSettings.dspTime 을 통해 double 값을 얻음
private double delayTime = 5.0;
void Start()
{
	audioSource = GetComponent<AudioSource>();
    double curDspTime = AudioSettings.dspTime;
    
    audioSource.PlayScheduled(curDspTime + delayTime); // 5초 뒤에 audioSource 재생
}

활용

clip1 의 재생이 끝난 뒤, clip2를 재생하고 싶을 때

private AudioSource as1;
private AudioSource as2;

void Start()
{
	double curDspTime = AudioSettings.dspTime;
	double as1Duration = (double)audioSource1.clip.samples / audioSource1.clip.frequency;
    
    as1.PlayScheduled(curDspTime);
    as2.PlayShceduled(curDspTime + as1Duration);

TIL 마무리

실제 활용한 코드는 PlayOneShot, Stop, loop , clip 정도이다.

  1. Vehicle 생성 시, hornSound - loop 재생
  2. Ray 를 통해 Player 를 감지, SkidMarkSound - loop 재생
  3. 충돌 감지, CarCrashSound 재생 -> ExplosionSound 재생

구현 과정에서, CarCrashSound 와 ExplosionSound 의 타이밍을 어떻게 맞춰야할 지 모르겠어서 AudioSource 와 관련된 스크립트를 찾아보게 되었다.

결국 사용되진 않았지만, 다음에 AudioSource 를 사용할 일이 있을 때
더욱 잘 활용할 수 있을 것 같다.

profile
안녕하세요 게임 개발하는 MINO 입니다.

0개의 댓글