2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Unityの音声関連のコンポーネント

Last updated at Posted at 2024-02-05

Unityの音声関連のコンポーネント

AudioSource

プレイヤーの声や、足音、BGMなど、音を鳴らすためのコンポーネント。シーン内に複数存在することができる。

たとえば、あるキャラクターが3種類のセリフを持っている場合に、話しかけるたびにランダムで1つのセリフを再生するようにするには、3つのAudioClipを話しかけるたびにランダムで選択し、それを再生するようにするといった使い方をする。

using UnityEngine;
public AudioSource audioSource;
public AudioClip[] audioClipCache;
audioSource.clip = audioClipCache[0]; // 1つ目のセリフを再生
audioSource.Play();

AudioClipにはOutputというプロパティがあり、AudioMixerGroupを指定することができる。これにより、BGMや効果音などを別々のグループに分けて音量を調整することができる。

AudioListener

プレイヤーの耳の役割をするコンポーネントで、シーン内に1つだけ存在する。たいていの場合、カメラにアタッチされている。

AudioSourceが3Dサウンドの場合、AudioListenerからの距離に応じて音量が変わる。

特にスクリプトから操作することはなく、コンポーネントとして存在するだけでよい。

AudioMixer

AudioMixerは、AudioSourceの出力をグループ化して、それぞれのグループに対して音量やエフェクトを調整するためのコンポーネント。

たとえば、BGMSEという2つのグループがあったとき、次のようにするとBGMの音量だけを聞こえなくすることができる。

AudioMixerのパラメーターを操作するには、AudioMixer.SetFloatを使う。単位はデシベルなのSliderコンポーネントと連動させる場合は、Mathf.Log10を使うとよい。

using UnityEngine.Audio;
public AudioMixer audioMixer;
public void SetBGMVolume(float volume)
{
    volume = Mathf.Clamp01(volume);
    float decibel = 20f * Mathf.Log10(volume);
    decibel = Mathf.Clamp(decibel, -80f, 0f);
    audioMixer.SetFloat("BGM", decibel);
}
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?