LoginSignup
11
9

More than 5 years have passed since last update.

【Unity】音にディレイをかける

Last updated at Posted at 2016-02-09

はじめに

UnityのOnAudioFilterReadを使う事で、スピーカーから出ている音にエフェクトをかけることができます.
この記事ではディレイエフェクトの作り方について解説したいと思います.

OnAudioFilterReadについて

通常の音の流れ
image

OnAudioFilterReadを使った場合
image

今回の記事ではOnAudioFilterReadの中で音を書き換える処理を書き、ディレイを実装していきます

ディレイを作る流れ

以下の流れでディレイエフェクトを作ります.
1. 遅延器・乗算器を作る
2. 遅延器・乗算器でループ回路を作る
3. 音の出力時に原音と混ぜる

図で表すと以下のようになります
image

1. ディレイエフェクトを作る

遅延器の音の出力を遅延器に入力させることでループを作っています.

DelayEffect.cs
using UnityEngine;
using System.Collections;

// ディレイエフェクト
class DelayEffect
{
  private float[] buffer = new float[48000];
  private int position = 0;
  private float g = .75f;
  private int delayTime = 18000;

  // 音の入力
  public void Input(float[] data, int channels)
  {
    int dst = this.position + delayTime;
    dst = dst % this.buffer.Length;
    for (int i = 0; i < data.Length; i++)
    {
      this.buffer[dst] += data[i];

      dst++;
      if (dst == buffer.Length) { dst = 0; }
    }
  }

  // 音の出力
  public void Output(float[] data, int channels)
  {
    int src = this.position;
    for (int i = 0; i < data.Length; i++)
    {
      data[i] += this.buffer[src] * g;
      this.buffer[src] = 0f;

      src++;
      if (src == buffer.Length) { src = 0; }
    }
    this.Input(data, channels);

    this.position = src;
  }
}

2. 音にディレイエフェクトをかける

SoundEffect.cs
using UnityEngine;
using System.Collections;

public class SoundEffect : MonoBehaviour
{
  DelayEffect delay = new DelayEffect();

  void OnAudioFilterRead(float[] data, int channels)
  {
    delay.Input(data, channels);
    delay.Output(data, channels);
  }
}

SoundEffect.csをAudioListnerコンポーネントがついているGameObjectにアタッチすればスピーカーから出る音にディレイがかかるようになります。

参考

Unity のオーディオの再生・エフェクト・解析周りについてまとめてみた
http://tips.hecomi.com/entry/2014/11/11/021147
OnAudioFilterRead - Unity - スクリプトリファレンス
http://docs.unity3d.com/ja/current/ScriptReference/MonoBehaviour.OnAudioFilterRead.html

11
9
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
11
9