Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

はじめに

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした