Примеры кода

Пример 1: Основы Audio System

Базовое управление аудио и настройка звуковой системы Unity:

using UnityEngine;

public class SpatialAudio : MonoBehaviour
{
    [Header("Аудио Клипы")]
    public AudioClip backgroundMusic;
    public AudioClip buttonClickSound;
    public AudioClip explosionSound;
    
    [Header("Аудио Источники")]
    public AudioSource musicSource;
    public AudioSource sfxSource;
    
    [Header("Настройки Громкости")]
    [Range(0f, 1f)]
    public float masterVolume = 1f;
    [Range(0f, 1f)]
    public float musicVolume = 0.7f;
    [Range(0f, 1f)]
    public float sfxVolume = 1f;
    
    void Start()
    {
        SetupAudioSources();
        PlayBackgroundMusic();
        Debug.Log("Audio Manager инициализирован");
    }
    
    void SetupAudioSources()
    {
        if (musicSource == null)
        {
            musicSource = gameObject.AddComponent<AudioSource>();
        }
        
        musicSource.loop = true;
        musicSource.playOnAwake = false;
        musicSource.volume = musicVolume;
        
        if (sfxSource == null)
        {
            sfxSource = gameObject.AddComponent<AudioSource>();
        }
        
        sfxSource.loop = false;
        sfxSource.playOnAwake = false;
        sfxSource.volume = sfxVolume;
        
        Debug.Log("Аудио источники настроены");
    }
    
    public void PlayBackgroundMusic()
    {
        if (backgroundMusic != null && musicSource != null)
        {
            musicSource.clip = backgroundMusic;
            musicSource.Play();
            Debug.Log("Фоновая музыка запущена");
        }
    }
    
    public void PlaySoundEffect(AudioClip clip)
    {
        if (clip != null && sfxSource != null)
        {
            sfxSource.PlayOneShot(clip);
            Debug.Log("Звуковой эффект воспроизведен: " + clip.name);
        }
    }
    
    public void SetMasterVolume(float volume)
    {
        masterVolume = Mathf.Clamp01(volume);
        AudioListener.volume = masterVolume;
        Debug.Log("Общая громкость: " + masterVolume);
    }
    
    public void SetMusicVolume(float volume)
    {
        musicVolume = Mathf.Clamp01(volume);
        if (musicSource != null)
        {
            musicSource.volume = musicVolume;
        }
        Debug.Log("Громкость музыки: " + musicVolume);
    }
}

Управление AudioSource

Детальная работа с компонентом AudioSource и его параметрами.

using UnityEngine;

public class AudioSourceController : MonoBehaviour
{
    [Header("AudioSource Компоненты")]
    public AudioSource primarySource;
    
    [Header("Аудио Клипы")]
    public AudioClip[] musicTracks;
    
    [Header("Параметры Воспроизведения")]
    [Range(0f, 3f)]
    public float pitch = 1f;
    [Range(0f, 1f)]
    public float volume = 1f;
    [Range(-1f, 1f)]
    public float stereoPan = 0f;
    
    private int currentTrackIndex = 0;
    private bool isPlaying = false;
    
    void Start()
    {
        if (primarySource == null)
            primarySource = GetComponent<AudioSource>();
            
        Debug.Log("AudioSource Controller инициализирован");
    }
    
    void Update()
    {
        UpdateAudioParameters();
        CheckPlaybackStatus();
        HandleInput();
    }
    
    void UpdateAudioParameters()
    {
        if (primarySource != null)
        {
            primarySource.pitch = pitch;
            primarySource.volume = volume;
            primarySource.panStereo = stereoPan;
        }
    }
    
    void CheckPlaybackStatus()
    {
        if (primarySource != null && isPlaying && !primarySource.isPlaying)
        {
            Debug.Log("Воспроизведение завершено");
            isPlaying = false;
            
            if (musicTracks.Length > 0)
            {
                PlayNextTrack();
            }
        }
    }
    
    void HandleInput()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            TogglePlayback();
        }
        
        if (Input.GetKeyDown(KeyCode.N))
        {
            PlayNextTrack();
        }
        
        if (Input.GetKeyDown(KeyCode.P))
        {
            PlayPreviousTrack();
        }
    }
    
    public void TogglePlayback()
    {
        if (primarySource == null) return;
        
        if (primarySource.isPlaying)
        {
            primarySource.Pause();
            Debug.Log("Воспроизведение приостановлено");
        }
        else
        {
            primarySource.UnPause();
            isPlaying = true;
            Debug.Log("Воспроизведение возобновлено");
        }
    }
    
    public void PlayNextTrack()
    {
        if (musicTracks.Length > 0)
        {
            currentTrackIndex = (currentTrackIndex + 1) % musicTracks.Length;
            PlayCurrentTrack();
            Debug.Log($"Следующий трек: {currentTrackIndex + 1}/{musicTracks.Length}");
        }
    }
    
    public void PlayPreviousTrack()
    {
        if (musicTracks.Length > 0)
        {
            currentTrackIndex = (currentTrackIndex - 1 + musicTracks.Length) % musicTracks.Length;
            PlayCurrentTrack();
            Debug.Log($"Предыдущий трек: {currentTrackIndex + 1}/{musicTracks.Length}");
        }
    }
    
    public void PlayCurrentTrack()
    {
        if (musicTracks.Length > 0 && primarySource != null)
        {
            AudioClip currentClip = musicTracks[currentTrackIndex];
            primarySource.clip = currentClip;
            primarySource.Play();
            isPlaying = true;
            Debug.Log("Воспроизводится: " + currentClip.name);
        }
    }
}

Audio Mixer и группы

Использование Audio Mixer для профессионального управления звуком.

using UnityEngine;
using UnityEngine.Audio;

public class AudioMixerController : MonoBehaviour
{
    [Header("Audio Mixer")]
    public AudioMixer mainMixer;
    
    [Header("Параметры Mixer")]
    [Range(-80f, 20f)]
    public float masterVolume = 0f;
    [Range(-80f, 20f)]
    public float musicVolume = 0f;
    [Range(-80f, 20f)]
    public float sfxVolume = 0f;
    
    void Start()
    {
        SetupMixer();
        Debug.Log("Audio Mixer Controller инициализирован");
    }
    
    void SetupMixer()
    {
        if (mainMixer != null)
        {
            SetMasterVolume(masterVolume);
            SetMusicVolume(musicVolume);
            SetSFXVolume(sfxVolume);
            
            Debug.Log("AudioSource настроен");
        }
    }
    
    public void SetMasterVolume(float volume)
    {
        masterVolume = volume;
        if (mainMixer != null)
        {
            mainMixer.SetFloat("MasterVolume", volume);
            Debug.Log("Master Volume: " + volume + " dB");
        }
    }
    
    public void SetMusicVolume(float volume)
    {
        musicVolume = volume;
        if (mainMixer != null)
        {
            mainMixer.SetFloat("MusicVolume", volume);
            Debug.Log("Music Volume: " + volume + " dB");
        }
    }
    
    public void SetSFXVolume(float volume)
    {
        sfxVolume = volume;
        if (mainMixer != null)
        {
            mainMixer.SetFloat("SFXVolume", volume);
            Debug.Log("SFX Volume: " + volume + " dB");
        }
    }
    
    public void SetLowPassFilter(float frequency)
    {
        if (mainMixer != null)
        {
            mainMixer.SetFloat("LowPassFreq", frequency);
            Debug.Log("Low Pass Filter: " + frequency + " Hz");
        }
    }
    
    public void SetReverb(float level)
    {
        if (mainMixer != null)
        {
            mainMixer.SetFloat("ReverbLevel", level);
            Debug.Log("Reverb Level: " + level);
        }
    }
    
    public void CreateSnapshot(string snapshotName)
    {
        if (mainMixer != null)
        {
            AudioMixerSnapshot snapshot = mainMixer.FindSnapshot(snapshotName);
            if (snapshot != null)
            {
                snapshot.TransitionTo(1f);
                Debug.Log("Переход к снимку: " + snapshotName);
            }
        }
    }
    
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Alpha1))
        {
            CreateSnapshot("Normal");
        }
        
        if (Input.GetKeyDown(KeyCode.Alpha2))
        {
            CreateSnapshot("Underwater");
        }
        
        if (Input.GetKeyDown(KeyCode.Alpha3))
        {
            CreateSnapshot("Cave");
        }
    }
}

3D Пространственный звук

Настройка пространственного звука и 3D аудио эффектов.

using UnityEngine;

public class SpatialAudioController : MonoBehaviour
{
    [Header("3D Audio Settings")]
    public AudioSource spatialSource;
    
    [Header("Spatial Parameters")]
    [Range(0f, 1f)]
    public float spatialBlend = 1f;
    [Range(0f, 5f)]
    public float dopplerLevel = 1f;
    [Range(0f, 360f)]
    public float spread = 0f;
    
    [Header("Distance Settings")]
    public float minDistance = 1f;
    public float maxDistance = 500f;
    public AudioRolloffMode rolloffMode = AudioRolloffMode.Logarithmic;
    
    void Start()
    {
        SetupSpatialAudio();
        Debug.Log("Spatial Audio Controller инициализирован");
    }
    
    void SetupSpatialAudio()
    {
        if (spatialSource == null)
            spatialSource = GetComponent<AudioSource>();
            
        if (spatialSource != null)
        {
            spatialSource.spatialBlend = spatialBlend;
            spatialSource.dopplerLevel = dopplerLevel;
            spatialSource.spread = spread;
            spatialSource.rolloffMode = rolloffMode;
            spatialSource.minDistance = minDistance;
            spatialSource.maxDistance = maxDistance;
            
            Debug.Log("3D звук настроен");
        }
    }
    
    void Update()
    {
        UpdateSpatialParameters();
        HandleInput();
    }
    
    void UpdateSpatialParameters()
    {
        if (spatialSource != null)
        {
            spatialSource.spatialBlend = spatialBlend;
            spatialSource.dopplerLevel = dopplerLevel;
            spatialSource.spread = spread;
            spatialSource.minDistance = minDistance;
            spatialSource.maxDistance = maxDistance;
            spatialSource.rolloffMode = rolloffMode;
        }
    }
    
    void HandleInput()
    {
        if (Input.GetKeyDown(KeyCode.Plus))
        {
            IncreaseDistance();
        }
        
        if (Input.GetKeyDown(KeyCode.Minus))
        {
            DecreaseDistance();
        }
        
        if (Input.GetKeyDown(KeyCode.D))
        {
            ToggleDoppler();
        }
    }
    
    public void IncreaseDistance()
    {
        maxDistance = Mathf.Min(maxDistance + 50f, 1000f);
        Debug.Log("Максимальная дистанция: " + maxDistance);
    }
    
    public void DecreaseDistance()
    {
        maxDistance = Mathf.Max(maxDistance - 50f, minDistance + 1f);
        Debug.Log("Максимальная дистанция: " + maxDistance);
    }
    
    public void ToggleDoppler()
    {
        dopplerLevel = dopplerLevel > 0 ? 0f : 1f;
        Debug.Log("Эффект Доплера: " + (dopplerLevel > 0 ? "включен" : "выключен"));
    }
    
    public void SetSpatialBlend(float blend)
    {
        spatialBlend = Mathf.Clamp01(blend);
        Debug.Log("Пространственное смешивание: " + spatialBlend);
    }
}

Продвинутые аудио техники

Продвинутые методы работы с аудио и динамическое управление звуком.

using UnityEngine;
using System.Collections;

public class AdvancedAudio : MonoBehaviour
{
    [Header("Dynamic Music")]
    public AudioSource[] musicLayers;
    public float crossfadeDuration = 2f;
    
    [Header("Audio Effects")]
    public AudioLowPassFilter lowPassFilter;
    public AudioHighPassFilter highPassFilter;
    public AudioReverbFilter reverbFilter;
    
    [Header("Performance")]
    public int maxAudioSources = 32;
    
    private int currentMusicLayer = 0;
    private bool isCrossfading = false;
    
    void Start()
    {
        SetupAdvancedAudio();
        Debug.Log("Advanced Audio Controller инициализирован");
    }
    
    void SetupAdvancedAudio()
    {
        // Настройка слоев музыки
        for (int i = 0; i < musicLayers.Length; i++)
        {
            if (musicLayers[i] != null)
            {
                musicLayers[i].volume = (i == 0) ? 1f : 0f;
                musicLayers[i].Play();
            }
        }
        
        // Настройка фильтров
        if (lowPassFilter == null)
            lowPassFilter = gameObject.AddComponent<AudioLowPassFilter>();
            
        if (highPassFilter == null)
            highPassFilter = gameObject.AddComponent<AudioHighPassFilter>();
            
        if (reverbFilter == null)
            reverbFilter = gameObject.AddComponent<AudioReverbFilter>();
    }
    
    public void CrossfadeToLayer(int layerIndex)
    {
        if (layerIndex >= 0 && layerIndex < musicLayers.Length && !isCrossfading)
        {
            StartCoroutine(CrossfadeCoroutine(layerIndex));
        }
    }
    
    IEnumerator CrossfadeCoroutine(int targetLayer)
    {
        isCrossfading = true;
        int previousLayer = currentMusicLayer;
        currentMusicLayer = targetLayer;
        
        float elapsedTime = 0f;
        
        while (elapsedTime < crossfadeDuration)
        {
            elapsedTime += Time.deltaTime;
            float t = elapsedTime / crossfadeDuration;
            
            if (musicLayers[previousLayer] != null)
                musicLayers[previousLayer].volume = Mathf.Lerp(1f, 0f, t);
                
            if (musicLayers[targetLayer] != null)
                musicLayers[targetLayer].volume = Mathf.Lerp(0f, 1f, t);
            
            yield return null;
        }
        
        if (musicLayers[previousLayer] != null)
            musicLayers[previousLayer].volume = 0f;
            
        if (musicLayers[targetLayer] != null)
            musicLayers[targetLayer].volume = 1f;
        
        isCrossfading = false;
        Debug.Log($"Переключение на слой {targetLayer} завершено");
    }
    
    public void ApplyLowPassFilter(float frequency)
    {
        if (lowPassFilter != null)
        {
            lowPassFilter.cutoffFrequency = Mathf.Clamp(frequency, 10f, 22000f);
            Debug.Log("Low Pass Filter: " + frequency + " Hz");
        }
    }
    
    public void ApplyHighPassFilter(float frequency)
    {
        if (highPassFilter != null)
        {
            highPassFilter.cutoffFrequency = Mathf.Clamp(frequency, 10f, 22000f);
            Debug.Log("High Pass Filter: " + frequency + " Hz");
        }
    }
    
    public void ApplyReverb(AudioReverbPreset preset)
    {
        if (reverbFilter != null)
        {
            reverbFilter.reverbPreset = preset;
            Debug.Log("Reverb Preset: " + preset);
        }
    }
    
    public void PlaySoundWithDelay(AudioClip clip, float delay)
    {
        StartCoroutine(PlayDelayedSound(clip, delay));
    }
    
    IEnumerator PlayDelayedSound(AudioClip clip, float delay)
    {
        yield return new WaitForSeconds(delay);
        
        AudioSource tempSource = gameObject.AddComponent<AudioSource>();
        tempSource.clip = clip;
        tempSource.Play();
        
        yield return new WaitForSeconds(clip.length);
        Destroy(tempSource);
        
        Debug.Log("Отложенный звук воспроизведен: " + clip.name);
    }
    
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Alpha1))
        {
            CrossfadeToLayer(0);
        }
        
        if (Input.GetKeyDown(KeyCode.Alpha2))
        {
            CrossfadeToLayer(1);
        }
        
        if (Input.GetKeyDown(KeyCode.Alpha3))
        {
            CrossfadeToLayer(2);
        }
        
        if (Input.GetKeyDown(KeyCode.L))
        {
            ApplyLowPassFilter(1000f);
        }
        
        if (Input.GetKeyDown(KeyCode.H))
        {
            ApplyHighPassFilter(1000f);
        }
        
        if (Input.GetKeyDown(KeyCode.R))
        {
            ApplyReverb(AudioReverbPreset.Cave);
        }
    }
}