C#에 해당하는 글 7

유니티 Android native 사운드 적용

C#/Unity|2019. 9. 14. 13:18

유니티에서 안드로이드 빌드시 사운드 재생이 Dealy 되는 경우가 있는데

이럴경우 안드로이드 native로 접근해서 사운드를 재생시켜줘야한다.

이미 관련된 Plugin이 있어서 유니티에서 사용하기 쉽게 클래스를 작성해보았다.


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using E7.Native;

/// E7 Native Audio Asset Required
/// http://exceed7.com/native-audio
public class NativeSoundSystem : MonoBehaviour {
    private static T _instance;
    public static T instance {
        get {
            if (_instance == null) {
                var insArray = FindObjectsOfType<T>();
                if (insArray.Length > 1) throw new Exception($"[{typeof(T).Name}] is not single.");
                if (insArray.Length == 0) {
                    var obj = new GameObject(typeof(T).Name);
                    _instance = obj.AddComponent<T>();
                } else if (insArray.Length == 1) {
                    _instance = insArray[0];
                }
            }
            return _instance;
        }
    }

    [Range(0f, 1f)]
    public float baseVolume = 1f;
    [SerializeField]
    public List<AudioClip> clips = new List<AudioClip>();

    private Dictionary<AudioClip, NativeAudioPointer> pointers = new Dictionary<AudioClip, NativeAudioPointer>();

    private NativeAudioController nativeAudioController;


    private void Awake() {
        Initialize();
    }


    public static void PlayOnce(AudioClip clip, float volume = 1f) {
        if(instance.NotRealDevice()) {
            Debug.Log($"Editor Play ({clip.name})");
            return;
        }
        if(!instance.pointers.ContainsKey(clip)) {
            instance.pointers[clip] = NativeAudio.Load(clip);
        }
        var option = new NativeAudio.PlayOptions();
        option.volume = instance.baseVolume * volume;
        instance.nativeAudioController = instance.pointers[clip].Play(option);
    }
    public static void PlayOnce(string clipName, float volume = 1f) {
        var clip = instance.clips.Find(x => x.name == clipName);
        PlayOnce(clip, volume);
    }

    private void Initialize() {
#if UNITY_EDITOR
        //You should have a fallback to normal AudioSource playing in your game so you can also hear sounds while developing.
        Debug.Log("Please try this in a real device!");
#else
#if UNITY_ANDROID
        var audioInfo = NativeAudio.GetDeviceAudioInformation();
        Debug.Log("Android audio information : " + audioInfo);
#endif
        NativeAudio.Initialize(new NativeAudio.InitializationOptions { androidAudioTrackCount = 3 });
#endif
    }

    private bool NotRealDevice() {
#if UNITY_EDITOR
        //You should have a fallback to normal AudioSource playing in your game so you can also hear sounds while developing.
        return true;
#else
        return false;
#endif
    }
}

-http://exceed7.com/native-audio

'C# > Unity' 카테고리의 다른 글

유용한 Unity & C# 관련 링크  (0) 2020.01.19
유니티 이동 컴포넌트 (Mover)  (0) 2019.09.14
유니티 클릭 컴포넌트 (Clickable)  (0) 2019.09.14

댓글()