Пример #1
0
 public void Dispose()
 {
     isInitialized = false;
     controllers.Keys.ToList().FindAll(it => !controllers[it].IsPreloaded).ForEach(Unload);
     controllers.Clear();
     NativeAudio.Dispose();
 }
Пример #2
0
    /// <summary>
    /// Play audio natively or normally based on if we have Native Audio support or not + did we check the checkbox or not.
    /// </summary>
    public void PlayAudio(bool comingFromCallback)
    {
#if NATIVE_AUDIO
        if (NativeAudio.OnSupportedPlatform() && mainLogic.NativeAudioChecked)
        {
            loadedNativeAudio.Play();
        }
        else
        {
            //If from callback on Android, we could not let it use main thread only things like `Stop` and `Play` of `AudioSource`. Or you will get :

            /*
             *  Unity   E  UnityException: Stop can only be called from the main thread.
             *          E  Constructors and field initializers will be executed from the loading thread when loading a scene.
             *          E  Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.
             */
#if UNITY_ANDROID
            if (!comingFromCallback)
#endif
            {
                selfSource.Stop();
                selfSource.Play();
            }
        }
#else
        selfSource.Stop();
        selfSource.Play();
#endif
    }
Пример #3
0
    public void Start()
    {
        if (NotRealDevice())
        {
            return;
        }
        Application.targetFrameRate = 60;
        Debug.Log("Unity output sample rate : " + AudioSettings.outputSampleRate);

        var dai = NativeAudio.GetDeviceAudioInformation();

        Debug.Log(dai.ToString());

#if UNITY_ANDROID
        var optimalBufferSize = dai.optimalBufferSize;
        bufferSizeSlider.value = optimalBufferSize;
        bufferSizeText.text    = optimalBufferSize.ToString();
#else
        bufferSizeSlider.value = 0;
        bufferSizeText.text    = "---";
#endif

        if (autoRepeat)
        {
            Initialize();
            LoadAudio1();
            StartCoroutine("RepeatedPlayRoutine");
        }
    }
Пример #4
0
    public void Awake()
    {
        director.Evaluate();
#if !UNITY_EDITOR
        loadedAudio = NativeAudio.Load(noteToPlay);
#endif
    }
Пример #5
0
 private void LoadAudio(AudioClip ac)
 {
     if (NotRealDevice())
     {
         return;
     }
     nativeAudioPointer = NativeAudio.Load(ac);
     Debug.Log("Loaded audio of length " + nativeAudioPointer.Length);
 }
Пример #6
0
    public 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
        NativeAudio.Initialize();
#endif
    }
Пример #7
0
 public void Awake()
 {
     normalColor = image.color;
     mainLogic   = GameObject.FindObjectOfType <MainLogic>();
     if (NativeAudio.OnSupportedPlatform())
     {
         loadedNativeAudio = NativeAudio.Load(selfSource.clip);
     }
 }
Пример #8
0
    public void LoadAudioSA()
    {
        if (NotRealDevice())
        {
            return;
        }

        //Loading via ScriptableAssets will have to ask Java to read out the file, then send that audio byte array to C.
        UnloadIfLoaded();
        nativeAudioPointer = NativeAudio.Load("NativeAudioDemoSA.wav");
        Debug.Log("Loaded audio of length " + nativeAudioPointer.Length + " from ScriptableAssets");
    }
Пример #9
0
    private void LoadAudio(AudioClip ac)
    {
        if (NotRealDevice())
        {
            return;
        }

        //Loading via AudioClip will pull out and send the audio byte array to C side directly.
        UnloadIfLoaded();
        nativeAudioPointer = NativeAudio.Load(ac);
        Debug.Log("Loaded audio of length " + nativeAudioPointer.Length);
    }
Пример #10
0
    private void LoadAudio(string name)
    {
#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
        nativeAudioPointer = NativeAudio.Load(name);
        if (nativeAudioPointer == null)
        {
            Debug.LogError("You have either Load-ed a nonexistent audio file or allocated over the Android's AudioTrack hard limit. Check your StreamingAssets folder for the correct name, or call nativeAudioPointer.Unload() to free up the quota.");
        }
#endif
    }
Пример #11
0
    IEnumerator DoInitializing()
    {
        Debug.Log("Initialize Native Audio");
        NativeAudio.Initialize();
        yield return(new WaitForSeconds(1.0f));

        initialized = true;
        Debug.Log("native audio initialized : " + initialized);
        if (initialized)
        {
            StartCoroutine(LoadSounds());
        }
    }
Пример #12
0
    public void NextHitSound()
    {
        HitSoundIndex++;
        if (HitSoundIndex == HitSounds.Length)
        {
            HitSoundIndex = 0;
        }

        UpdateHitSound(HitSounds[HitSoundIndex]);
#if (UNITY_IOS || UNITY_ANDROID) && !UNITY_EDITOR
        var pointer = NativeAudio.Load("Hits/" + HitSounds[HitSoundIndex].Name + ".wav");
        pointer.Play();
#endif
    }
Пример #13
0
     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
     }
Пример #14
0
    public 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 at initialization : " + audioInfo);
#endif
        NativeAudio.Initialize(new NativeAudio.InitializationOptions {
            androidAudioTrackCount   = 2,
            androidMinimumBufferSize = Mathf.RoundToInt(bufferSizeSlider.value)
        });
#endif
    }
Пример #15
0
        public static void PlayOnce(AudioClip clip, float volume = 1f)
        {
            if (instance.NotRealDevice())
            {
                SoundSystem.PlayOnce(clip);
                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 void Start()
    {
        // var pl = PlayerLoop.GetDefaultPlayerLoop();
        // foreach(var subsystem in pl.subSystemList)
        // {
        //  if(subsystem.GetType() == typeof(Initialization))
        //  {
        //         var npl = new PlayerLoopSystem[1];
        //      npl.updateDelegate = TimeCaptureUpdate;
        //      subsystem.subSystemList = subsystem.subSystemList.Concat(npl);
        //  }
        // }
#if !UNITY_EDITOR
        NativeAudio.Initialize();
        pointer = NativeAudio.Load("NativeAudioDemo1.wav");
#endif
    }
Пример #17
0
    public void PrevHitSound()
    {
        HitSoundIndex--;
        if (HitSoundIndex < 0)
        {
            HitSoundIndex = HitSounds.Length - 1;
        }

        UpdateHitSound(HitSounds[HitSoundIndex]);

#if (UNITY_IOS || UNITY_ANDROID) && !UNITY_EDITOR
        var pointer = NativeAudio.Load("Hits/" + HitSounds[HitSoundIndex].Name + ".wav");
        if (pointer != null)
        {
            pointer.Play();
        }
#endif
    }
Пример #18
0
        public NativeAudioCase(string fileName, AudioController.AudioType type)
        {
            audioName = fileName;
            audioType = type;

#if UNITY_EDITOR
            AudioController.LoadAudioClipFromStreamingAssets(fileName, OnClipLoaded);
#elif UNITY_ANDROID
            float currentVolume = type == AudioController.AudioType.Sound ? AudioController.GetSoundVolume() : AudioController.GetMusicVolume();
            //var adjustment = new NativeAudio.PlayAdjustment { volume = currentVolume, pan = 1f };
            //playOptions = new NativeAudio.PlayOptions { playAdjustment = adjustment };
            //Debug.Log("Created native audio case for:" + fileName + "  volume: " + currentVolume);

            audioEnabled = currentVolume == 0 ? false : true;

            nativeAudioPointer = NativeAudio.Load(fileName);
#endif
        }
Пример #19
0
    public void Initialize()
    {
        if (isInitialized)
        {
            return;
        }
        isInitialized = true;
        SetUseNativeAudio(Context.Player.Settings.UseNativeAudio);
        if (useNativeAudio)
        {
            NativeAudio.Initialize(new NativeAudio.InitializationOptions
            {
                androidAudioTrackCount = 2
            });
            Debug.Log("Native Audio initialized");
        }

        preloadedAudioClips.ForEach(it => Load(it.name, it, isPreloaded: true));
    }
Пример #20
0
    IEnumerator LoadSounds()
    {
        audioPointers.Clear();

        int soundsCount = audioNames.Length;
        int soundNum    = 0;

        Debug.Log("LOAD " + soundsCount + " SOUNDS:");

        while (soundNum < soundsCount)
        {
            Debug.Log("LOADING SOUND " + audioNames[soundNum] + "  " + Time.time);
            NativeAudioPointer nativeAudioPointer = NativeAudio.Load(audioNames[soundNum]);
            audioPointers.Add(nativeAudioPointer);
            if (nativeAudioPointer == null)
            {
                Debug.Log("ERROR: " + audioNames[soundNum] + " NOT LOADED ");
            }
            yield return(new WaitForSeconds(1.0f));

            if (nativeAudioPointer != null)
            {
                Debug.Log("PREPARE SOUND " + audioNames[soundNum] + "  " + Time.time);
                nativeAudioPointer.Prepare();
            }
            else
            {
                Debug.Log("CAN'T PREPARE NULL SOUND " + audioNames[soundNum] + "  " + Time.time);
            }
            yield return(new WaitForSeconds(1.0f));

            soundNum += 1;
        }

        Debug.Log("LOADING DONE " + +Time.time);
        yield return(null);
    }
Пример #21
0
        protected virtual IEnumerator Start()
        {
            // Load level
            if (CytoidApplication.CurrentLevel != null)
            {
                Level = CytoidApplication.CurrentLevel;
            }
            else
            {
                Level = JsonConvert.DeserializeObject <Level>(
                    File.ReadAllText(Application.persistentDataPath + "/player/level.json"));
                Level.BasePath = Application.persistentDataPath + "/player/";
                CytoidApplication.CurrentChartType = Level.charts[0].type;

                var www = new WWW("file://" + Level.BasePath + Level.background.path);
                yield return(www);

                yield return(null); // Wait an extra frame

                www.LoadImageIntoTexture(CytoidApplication.BackgroundTexture);

                var backgroundSprite =
                    Sprite.Create(CytoidApplication.BackgroundTexture,
                                  new Rect(0, 0, CytoidApplication.BackgroundTexture.width,
                                           CytoidApplication.BackgroundTexture.height),
                                  new Vector2(0, 0));
                var background = GameObject.FindGameObjectWithTag("Background");
                if (background != null)
                {
                    background.GetComponent <Image>().sprite = backgroundSprite;

                    // Fill the screen by adapting to the aspect ratio
                    background.GetComponent <AspectRatioFitter>().aspectRatio =
                        (float)CytoidApplication.BackgroundTexture.width / CytoidApplication.BackgroundTexture.height;
                    yield return(null); // Wait an extra frame
                }

                www.Dispose();
                Resources.UnloadUnusedAssets();

                CytoidApplication.CurrentLevel = Level;
            }

            // System settings
            CytoidApplication.SetAutoRotation(false);
            if (Application.platform == RuntimePlatform.Android && !Level.IsInternal)
            {
                print("Using Android Native Audio");
                GameOptions.Instance.UseAndroidNativeAudio = true;
            }

            // Load chart
            print("Loading chart");

            if (CytoidApplication.CurrentChartType == null)
            {
                CytoidApplication.CurrentChartType = Level.charts[0].type;
            }

            var chartSection = Level.charts.Find(it => it.type == CytoidApplication.CurrentChartType);

            string chartText;

            if (Application.platform == RuntimePlatform.Android && Level.IsInternal)
            {
                var chartWww = new WWW(Level.BasePath + chartSection.path);
                yield return(chartWww);

                chartText = Encoding.UTF8.GetString(chartWww.bytes);
            }
            else
            {
                chartText = File.ReadAllText(Level.BasePath + chartSection.path, Encoding.UTF8);
            }

            Chart = new Chart(
                chartText,
                0.8f + (5 - (int)PlayerPrefs.GetFloat("horizontal margin", 3) - 1) * 0.025f,
                (5.5f + (5 - (int)PlayerPrefs.GetFloat("vertical margin", 3)) * 0.5f) / 9.0f
                );

            // Load audio
            print("Loading audio");

            var audioPath = Level.BasePath + Level.GetMusicPath(CytoidApplication.CurrentChartType);

            if (GameOptions.Instance.UseAndroidNativeAudio)
            {
                NativeAudioId = ANAMusic.load(audioPath, true);
                Length        = ANAMusic.getDuration(NativeAudioId);
            }
            else
            {
                var www = new WWW(
                    (Level.IsInternal && Application.platform == RuntimePlatform.Android ? "" : "file://") +
                    audioPath);
                yield return(www);

                AudioSource.clip = www.GetAudioClip();
                Length           = AudioSource.clip.length;

                www.Dispose();
            }

            // Game options
            var options = GameOptions.Instance;

            options.HitboxMultiplier       = PlayerPrefsExt.GetBool("larger_hitboxes") ? 1.5555f : 1.3333f;
            options.ShowEarlyLateIndicator = PlayerPrefsExt.GetBool("early_late_indicator");
            options.ChartOffset            = PlayerPrefs.GetFloat("main offset", 0);
            options.ChartOffset           += ZPlayerPrefs.GetFloat(PreferenceKeys.ChartRelativeOffset(Level.id), 0);

            if (Application.platform != RuntimePlatform.Android && Headset.Detect())
            {
                options.ChartOffset += ZPlayerPrefs.GetFloat("headset offset");
            }

            if (CytoidApplication.CurrentHitSound.Name != "None")
            {
#if (UNITY_IOS || UNITY_ANDROID) && !UNITY_EDITOR
                options.HitSound = NativeAudio.Load("Hits/" + CytoidApplication.CurrentHitSound.Name + ".wav");
#endif
            }

            Play.Init(Chart);

            print("Chart checksum: " + Chart.Checksum);
            // Rank data
            if (Play.IsRanked)
            {
                RankedPlayData                            = new RankedPlayData();
                RankedPlayData.user                       = OnlinePlayer.Name;
                RankedPlayData.password                   = OnlinePlayer.Password;
                RankedPlayData.start                      = TimeExt.Millis();
                RankedPlayData.id                         = Level.id;
                RankedPlayData.type                       = CytoidApplication.CurrentChartType;
                RankedPlayData.mods                       = string.Join(",", Array.ConvertAll(Play.Mods.ToArray(), mod => mod.ToString()));
                RankedPlayData.version                    = Level.version;
                RankedPlayData.chart_checksum             = Chart.Checksum;
                RankedPlayData.device.width               = Screen.width;
                RankedPlayData.device.height              = Screen.height;
                RankedPlayData.device.dpi                 = (int)Screen.dpi;
                RankedPlayData.device.model               = SystemInfo.deviceModel;
                CytoidApplication.CurrentRankedPlayData   = RankedPlayData;
                CytoidApplication.CurrentUnrankedPlayData = null;
            }
            else
            {
                UnrankedPlayData                          = new UnrankedPlayData();
                UnrankedPlayData.user                     = OnlinePlayer.Authenticated ? OnlinePlayer.Name : "local";
                UnrankedPlayData.password                 = OnlinePlayer.Authenticated ? OnlinePlayer.Password : "";
                UnrankedPlayData.id                       = Level.id;
                UnrankedPlayData.type                     = CytoidApplication.CurrentChartType;
                UnrankedPlayData.version                  = Level.version;
                UnrankedPlayData.chart_checksum           = Chart.Checksum;
                CytoidApplication.CurrentRankedPlayData   = null;
                CytoidApplication.CurrentUnrankedPlayData = UnrankedPlayData;
            }

            // Touch handlers
            if (!Mod.Auto.IsEnabled())
            {
                LeanTouch.OnFingerDown += OnFingerDown;
                LeanTouch.OnFingerSet  += OnFingerSet;
                LeanTouch.OnFingerUp   += OnFingerUp;
            }

            yield return(new WaitForSeconds(0.2f));

            View.OnStart();

            IsLoaded = true;

            EventKit.Broadcast("game loaded");

            // Wait for Storyboard
            while (!StoryboardController.Instance.Loaded)
            {
                yield return(null);
            }

            yield return(new WaitForSeconds(0.3f));

            StartGame();
        }
Пример #22
0
 private static void Init()
 {
     //This is so that it comes before all Pad's `Awake` which attempts to load the audio.
     NativeAudio.Initialize();
 }
Пример #23
0
 public void DisposeNativeAudio()
 {
     NativeAudio.Dispose();
 }
Пример #24
0
    public IEnumerator PerformanceTest()
    {
        running = true;
        sw      = new Stopwatch();
        pr      = new PerformanceResult();
        audioSource.clip.UnloadAudioData();
        UnityEngine.Debug.Log("Performance test : AudioSource..");
        UnityEngine.Debug.Log("Performance test : AudioSource loading..");

        sw.Start();
        audioSource.clip.LoadAudioData();
        sw.Stop();
        pr.asLoad = sw.ElapsedTicks;
        sw.Reset();

        yield return(new WaitForSeconds(0.5f));

        UnityEngine.Debug.Log("Performance test : AudioSource playing..");

        for (int i = 0; i < framesOfPlay; i++)
        {
            UnityEngine.Debug.Log("Performance test : AudioSource frame " + i);
            sw.Start();
            audioSource.Play();
            yield return(null);

            sw.Stop();
            pr.asTicks.Add(sw.ElapsedTicks);
            sw.Reset();
        }

        yield return(new WaitForSeconds(0.5f));

        if (!Application.isEditor)
        {
            UnityEngine.Debug.Log("Performance test : NativeAudio initializing..");

            sw.Start();
            //This force the "crash prevention mechanism" to activates. If it crashes then... it is a bug.
            NativeAudio.Initialize(new NativeAudio.InitializationOptions {
                androidAudioTrackCount = 3
            });
            sw.Stop();
            pr.naInitialize = sw.ElapsedTicks;
            sw.Reset();

            yield return(new WaitForSeconds(0.5f));

            UnityEngine.Debug.Log("Performance test : NativeAudio silently analyzing..");

            NativeAudioAnalyzer analyzer = NativeAudio.SilentAnalyze();
            yield return(new WaitUntil(() => analyzer.Analyzed));

            pr.silenceAnalysis = analyzer.AnalysisResult.averageFps;

            UnityEngine.Debug.Log("Performance test : NativeAudio loading..");

            sw.Start();
            loaded = NativeAudio.Load("NativeAudioDemo1.wav");
            yield return(null);

            sw.Stop();
            pr.naLoad = sw.ElapsedTicks;
            sw.Reset();

            yield return(new WaitForSeconds(0.5f));

            UnityEngine.Debug.Log("Performance test : NativeAudio playing..");

            for (int i = 0; i < framesOfPlay; i++)
            {
                UnityEngine.Debug.Log("Performance test : NativeAudio frame " + i);
                sw.Start();
                loaded.Play();
                yield return(null);

                sw.Stop();
                pr.naTicks.Add(sw.ElapsedTicks);
                sw.Reset();
            }

            yield return(new WaitForSeconds(0.5f));
        }

        UnityEngine.Debug.Log("Performance test : Ending..");

        resultText.text = pr.AnalysisText;

        running = false;
    }
Пример #25
0
 public void SetUseNativeAudio(bool useNativeAudio)
 {
     this.useNativeAudio = NativeAudio.OnSupportedPlatform() && useNativeAudio;
 }