예제 #1
0
    // Three types:
    // Transform based (3D Sound)
    // Point or Vector3 Based (3D Sound)
    // None (Directly to the main audio source (2D sound)


    /// <summary>
    /// Plays directly at the cameras audioSource
    /// </summary>
    /// <param name="sample"></param>
    public static AudioSourceContainer Play(AudioSample sample)
    {
        // There should only be one audioListener (Usually main camera)
        Transform audioListenerTransform = GameObject.FindObjectOfType <AudioListener>().transform;

        return(Play(sample, audioListenerTransform));
    }
예제 #2
0
        private static FileSample GetSampleBase(IStorageFile file)
        {
            // TODO: We could move this to the environment service to actually attempt to load the file
            string ext = Path.GetExtension(file.Name);

            if (String.IsNullOrWhiteSpace(ext))
            {
                return(null);
            }

            FileSample baseSample = null;

            if (AudioExtensions.Contains(ext))
            {
                baseSample = new AudioSample();
            }

            if (baseSample != null)
            {
                baseSample = baseSample with
                {
                    SourceUrl = file.Path,
                    Name      = Path.GetFileNameWithoutExtension(file.Name)
                };
            }

            return(baseSample);
        }
    }
예제 #3
0
    private void SetSettingsFromSample(AudioSample sample)
    {
        if (AudioSource == null)
        {
            throw new Exception("AudioSourceContainer: No AudioSource set");
        }

        Layer = sample.Layer;
        AudioLayerSettings layerS = layerSettings;

        VolumeModifier = sample.Settings.Volume;

        AudioSource.mute     = layerS.Mute;
        AudioSource.loop     = sample.Settings.Loop;
        AudioSource.priority = sample.Settings.Priority;
        AudioSource.pitch    = sample.Settings.Pitch;

        AudioSource.bypassEffects         = sample.Settings.BypassEffects;
        AudioSource.bypassListenerEffects = sample.Settings.BypassListenerEffects;
        AudioSource.bypassReverbZones     = sample.Settings.BypassReverbZones;

        AudioSource.dopplerLevel = sample.Settings.DopplerLevel;
        AudioSource.panLevel     = sample.Settings.PanLevel;
        AudioSource.spread       = sample.Settings.Spread;
        AudioSource.maxDistance  = sample.Settings.MaxDistance;

        AudioSource.pan = sample.Settings.Pan2D;

        AudioSource.clip = sample.Clip;
    }
예제 #4
0
        private void Stream(WaveStream stream, CancellationToken cancellationToken)
        {
            var buffer          = new byte[stream.WaveFormat.AverageBytesPerSecond];
            var streamTimeStart = stream.CurrentTime;
            var realTimeStart   = DateTime.UtcNow;

            while (!cancellationToken.IsCancellationRequested)
            {
                var bytesRead = stream.Read(buffer, 0, buffer.Length);

                if (bytesRead == 0)
                {
                    // if we have reached the end, reset stream to start
                    stream.CurrentTime = TimeSpan.Zero;
                    streamTimeStart    = stream.CurrentTime;
                    realTimeStart      = DateTime.UtcNow;
                    continue;
                }

                var time        = realTimeStart + stream.CurrentTime;
                var audioSample = new AudioSample
                {
                    Timestamp = time.ToString("o"),
                    Data      = ByteString.CopyFrom(buffer)
                };
                OnAudioSampleCreated(audioSample);

                var streamTimePassed = stream.CurrentTime - streamTimeStart;
                var realTimePassed   = DateTime.UtcNow - realTimeStart;
                var timeDifference   = Math.Max(0, (streamTimePassed - realTimePassed).TotalMilliseconds);
                Thread.Sleep((int)timeDifference);
            }
        }
예제 #5
0
        private void load(AudioManager audio)
        {
            welcome = audio.Sample.Get(@"welcome");

            bgm         = audio.Track.Get(@"circles");
            bgm.Looping = true;
        }
예제 #6
0
        private void EnsureBufferSize()
        {
            // TODO throw out buffered data if the buffer is too large.
            // The way it is now, the buffer gets bigger but never shrinks back down.

            lock (_bufferLock)
            {
                if (_buffer.Length < _delaySamples)
                {
                    AudioSample[] oldBuffer = _buffer;
                    AudioSample[] newBuffer = new AudioSample[_delaySamples];

                    if (oldBuffer.Any(s => s.L != 0 || s.R != 0))
                    {
                        // segment 1: from the nextInputIndex to the end of the current buffer (which is always shorter than the current buffer)
                        int segment1Length = oldBuffer.Length - _nextInputIndex;
                        Array.Copy(oldBuffer, _nextInputIndex, newBuffer, _nextInputIndex, segment1Length);

                        // segment 2: take from the beginning of the old buffer and put as much as will fit at the end of the new buffer
                        int segment2Length = newBuffer.Length - oldBuffer.Length;
                        Array.Copy(oldBuffer, 0, newBuffer, oldBuffer.Length, segment2Length);

                        // segment 3: put the remainder of the old buffer at the beginning of the new buffer
                        int segment3Length = newBuffer.Length - (segment1Length + segment2Length);
                        Array.Copy(oldBuffer, segment2Length, newBuffer, 0, segment3Length);

                        // this leaves a block of zeros in the array elements representing the oldest samples, which weren't collected prior to the resize.
                    }

                    _buffer = newBuffer;
                }
            }
        }
예제 #7
0
파일: Audio.cs 프로젝트: henon/manic_digger
 AudioSample GetSample(string filename)
 {
     if (!audio.cache.ContainsKey(filename))
     {
         Stream stream = audio.d_GetFile.GetFile(filename);
         if (stream.ReadByte() == 'R'
             && stream.ReadByte() == 'I'
             && stream.ReadByte() == 'F'
             && stream.ReadByte() == 'F')
         {
             stream.Position = 0;
             int channels, bits_per_sample, sample_rate;
             byte[] sound_data = LoadWave(stream, out channels, out bits_per_sample, out sample_rate);
             AudioSample sample = new AudioSample()
             {
                 Pcm = sound_data,
                 BitsPerSample = bits_per_sample,
                 Channels = channels,
                 Rate = sample_rate,
             };
             audio.cache[filename] = sample;
         }
         else
         {
             stream.Position = 0;
             AudioSample sample = new OggDecoder().OggToWav(stream);
             audio.cache[filename] = sample;
         }
     }
     return audio.cache[filename];
 }
    private void SetSettingsFromSample(AudioSample sample)
    {
        if (AudioSource == null)
            throw new Exception("AudioSourceContainer: No AudioSource set");

        Layer = sample.Layer;
        AudioLayerSettings layerS = layerSettings;

        VolumeModifier              = sample.Settings.Volume;

        AudioSource.mute            = layerS.Mute;
        AudioSource.loop            = sample.Settings.Loop;
        AudioSource.priority        = sample.Settings.Priority;
        AudioSource.pitch           = sample.Settings.Pitch;

        AudioSource.bypassEffects   = sample.Settings.BypassEffects;
        AudioSource.bypassListenerEffects = sample.Settings.BypassListenerEffects;
        AudioSource.bypassReverbZones = sample.Settings.BypassReverbZones;

        AudioSource.dopplerLevel    = sample.Settings.DopplerLevel;
        AudioSource.panLevel        = sample.Settings.PanLevel;
        AudioSource.spread          = sample.Settings.Spread;
        AudioSource.maxDistance     = sample.Settings.MaxDistance;

        AudioSource.pan             = sample.Settings.Pan2D;

        AudioSource.clip            = sample.Clip;
    }
예제 #9
0
        private void loopbackCaptureController_OnCapture(AudioSample audioSample)
        {
            ValuesCache.LastSampleOnChannelLeft  = AudioProcessingHelper.CalculateSampleByMaxValue(audioSample.AudioChannelSamples[0].SampleFrames);
            ValuesCache.LastSampleOnChannelRight = AudioProcessingHelper.CalculateSampleByMaxValue(audioSample.AudioChannelSamples[1].SampleFrames);

            /*Complex[] fftBuffer = new Complex[audioSample.SampleFrames.Length];
             * for(var i =0; i< audioSample.SampleFrames.Length; i++)
             * {
             *  fftBuffer[i].X = (float)(audioSample.SampleFrames[i] * FastFourierTransform.HammingWindow(i, audioSample.SampleFrames.Length));
             *  fftBuffer[i].Y = i;
             * }
             *
             * FastFourierTransform.FFT(true, 10, fftBuffer);*/

            SampleAggregatorHelper sa = new SampleAggregatorHelper(audioSample.SampleProvider, (int)Math.Pow(2, 13));

            sa.PerformFFT     = true;
            sa.FftCalculated += new EventHandler <FftEventArgs>((object sender, FftEventArgs e) =>
            {
                //for (var i = 0; i < e.Result.Length; i++)
                // {
                // e.Result[i].X;
                //e.Result[i].Y;
                /// }
                ValuesCache.LastSampleOnFrequency1000Hz = e.Result[1024].Y;
            });
            float[] buff = new float[audioSample.SampleFrames.Length];
            sa.Process(audioSample.SampleFrames);
        }
예제 #10
0
        private void b_play_Click(object sender, EventArgs e)
        {
            if (lb_sample.SelectedItem == null)
            {
                return;
            }
            string key = lb_sample.SelectedItem.ToString();

            if (key == "None")
            {
                return;
            }
            if (lastPlaySample != null)
            {
                lastPlaySample.Stop();
                lastPlaySample = null;
            }

            int addr = AudioEngine.LoadBeatmapSample(key, false);

            //ignore slider and tick, just for preview
            //HitObject.ProcessSampleFile reset sample to proper loop config.
            if (addr != -1)
            {
                lastPlaySample = AudioEngine.PlaySample(addr, (int)nud_vol.Value);
            }
        }
예제 #11
0
        public async Task <IPreparedEffect> PrepareEffectAsync(EnvironmentElement element, string descriptor, PlaybackOptions options)
        {
            CreateAudioFileInputNodeResult nodeResult;

            AudioSample sample = await this.sync.GetElementByIdAsync <AudioSample> (descriptor).ConfigureAwait(false);

            StorageFile file = await GetFileAsync(sample).ConfigureAwait(false);

            AudioNodeEmitter emitter = null;            // GetEmitter (options);

            if (emitter != null)
            {
                nodeResult = await graph.CreateFileInputNodeAsync(file, emitter).ConfigureAwait(false);
            }
            else
            {
                nodeResult = await graph.CreateFileInputNodeAsync(file).ConfigureAwait(false);
            }

            var node     = nodeResult.FileInputNode;
            var prepared = new PreparedSource(node, emitter)
            {
                Duration = nodeResult.FileInputNode.Duration
            };

            /*
             * node.FileCompleted += (o, e) => {
             *      OnElementFinished (new PreparedElementEventArgs (prepared));
             * };*/

            return(prepared);
        }
예제 #12
0
        /// <summary>
        /// Enqueues next audio samples in the buffer
        /// </summary>
        /// <param name="buf">Buffer for the audio stream</param>
        public void EnqueueAudioSamples(byte[] buf)
        {
            AudioSample audioSample = new AudioSample(buf.AsBuffer());
            bool canDirectSubmit;

            lock (audioQueueLock)
            {
                if (audioQueue.Count == 0 && outstandingGetAudioSampleCount > 0)
                {
                    outstandingGetAudioSampleCount--;
                    canDirectSubmit = true;
                }
                else
                {
                    canDirectSubmit = false;
                    audioQueue.Enqueue(audioSample);
                }
            }

            if (canDirectSubmit)
            {
                Debug.WriteLine("Direct submitting LPCM sample");
                SubmitAudioSample(audioSample);
            }
            else
            {
                Debug.WriteLine("Queued LPCM sample");
                SendAudioSamples();
            }
        }
예제 #13
0
        private void load(AudioManager audio)
        {
            string hitType   = ((HitObject.Sample?.Type ?? SampleType.None) == SampleType.None ? SampleType.Normal : HitObject.Sample.Type).ToString().ToLower();
            string sampleSet = (HitObject.Sample?.Set ?? SampleSet.Normal).ToString().ToLower();

            sample = audio.Sample.Get($@"Gameplay/{sampleSet}-hit{hitType}");
        }
예제 #14
0
 public void CollectSamples(AudioSample sample)
 {
     if (this.recording != null && sample.Data != null)
     {
         float[] data = this.recording.ConvertToFloat(sample.Data);
         this.samples.AddRange(data);
     }
 }
예제 #15
0
 public bool audition_set(AudioSample currSample)
 {
     if (!bodyTransitionReady)
     {
         return(true);
     }
     return(auditionEnabled);
 }
예제 #16
0
파일: Intro.cs 프로젝트: yheno/osu
        private void load(AudioManager audio)
        {
            welcome = audio.Sample.Get(@"welcome");
            seeya = audio.Sample.Get(@"seeya");

            bgm = audio.Track.Get(@"circles");
            bgm.Looping = true;
        }
예제 #17
0
    public static AudioSourceContainer Play(AudioSample sample, Vector3 position)
    {
        AudioSourceContainer soundObject = RegisterAndCreateAudioSourceContainer(sample);

        soundObject.transform.position = position;

        return(Play(soundObject));
    }
예제 #18
0
파일: Button.cs 프로젝트: Kirishikun/osu
 private void load(AudioManager audio)
 {
     sampleClick = audio.Sample.Get($@"Menu/menu-{internalName}-click");
     if (sampleClick == null)
     {
         sampleClick = audio.Sample.Get(internalName.Contains(@"back") ? @"Menu/menuback" : @"Menu/menuhit");
     }
 }
예제 #19
0
 private void CreateSampleStorage(int dataSize)
 {
     samples = new AudioSample[(int)(MaxOffset / tickTime) + 1];
     for (int i = 0; i < samples.Length; i++)
     {
         samples[i]      = new AudioSample();
         samples[i].data = new float[dataSize];
     }
 }
예제 #20
0
파일: Intro.cs 프로젝트: Jonasrems/osu
        protected override void Load(BaseGame game)
        {
            base.Load(game);

            welcome = game.Audio.Sample.Get(@"welcome");

            bgm         = game.Audio.Track.Get(@"circles");
            bgm.Looping = true;
        }
예제 #21
0
 private void FinishSample(AudioSample a, bool callback)
 {
     if (callback)
     {
         a.SampleOver(this);     // let callers know a sample is over
     }
     a.FreeHandles();
     ad.Dispose(a.audiodata);        // tell the driver to clean up
 }
예제 #22
0
        /// <summary>
        /// </summary>
        public TestAudioScreen()
        {
            Song  = new AudioTrack(GameBase.Game.Resources.Get("Wobble.Tests.Resources/Tracks/virt - Send My Love To Mars.mp3"));
            Train = new AudioSample(GameBase.Game.Resources.Get("Wobble.Tests.Resources/SFX/train.wav"));

            Song?.Play();

            View = new TestAudioScreenView(this);
        }
예제 #23
0
        public override void Load()
        {
            base.Load();

            AudioSample welcome = Game.Audio.Sample.GetSample(@"welcome.mp3");

            welcome.Play();

            Add(new ButtonSystem());
        }
예제 #24
0
 private void PublishBuffer()
 {
     if (_waveBufferPos > 64000 * 1.5) //if less then 1.5 seconds, don't publish
     {
         _logger.LogInformation("Kinect published audio.");
         byte[] convertedWave = AudioSample.ConvertFormat32fTO16int(_waveBuffer, _waveBufferPos, 1);
         SampleReady?.Invoke(this, new AudioSample(DateTime.Now, convertedWave, convertedWave.Length, new AudioSample.FixedWaveFormat(16000)));
         _waveBufferPos = 0;
     }
 }
예제 #25
0
    private void AddClipToList(AudioLibrary AudioLib, AudioClip audioClip)
    {
        //data.foldSettings.Add(false);
        //data._3DSettings.Add(false);
        //data._2DSettings.Add(false);
        AudioSample sample = new AudioSample();

        sample.Clip = audioClip;
        AudioLib.Samples.Add(sample);
    }
예제 #26
0
        /// <summary>
        /// Creates a metronome with ticks that updates based on where you are in the active timing section.
        /// </summary>
        /// <param name="editor"></param>
        internal Metronome(Game game, Editor editor)
            : base(game)
        {
            this.editor = editor;

            s_metronomeHigh = new AudioSample(AudioEngine.LoadSample(@"metronomehigh", false, true, SkinSource.Osu));
            s_metronomeLow  = new AudioSample(AudioEngine.LoadSample(@"metronomelow", false, true, SkinSource.Osu));

            TapWindow = new pTapWindow(game, editor, new Vector2(200, 0));
        }
    public static GameObject CreateContainer(AudioSample sample)
    {
        GameObject soundObject = new GameObject();
        soundObject.name = "AudioSourceObject";
        AudioSourceContainer container = soundObject.AddComponent<AudioSourceContainer>();
        container.AudioSource = soundObject.AddComponent<AudioSource>();

        container.SetSettingsFromSample(sample);

        return soundObject;
    }
예제 #28
0
        public AudioSample GetSample(ulong requestId)
        {
            AudioSample sample = new AudioSample();

            if (Input != null)
            {
                sample = Input(requestId);
            }

            return(sample);
        }
예제 #29
0
 public bool IsWaiting(AudioSample s)    // is this at the top of my queue?
 {
     if (audioqueue.Count > 0)
     {
         return(Object.ReferenceEquals(audioqueue[0], s));
     }
     else
     {
         return(false);
     }
 }
예제 #30
0
        protected override AudioSample CalculateNextSample(ulong requestId)
        {
            AudioSample result = new AudioSample();

            if (IsActive)
            {
                _channels.Execute(channel => result += channel.GetSample(requestId));
                result *= _masterLevel.GetNextSample();
            }

            return(result);
        }
예제 #31
0
        /// <summary>
        /// Constructor
        /// </summary>
        public AudioForm(XmlNode node)
        {
            InitializeComponent();



            Sound = new AudioSample();
            Sound.Load(node);


            Build();
        }
예제 #32
0
파일: SkinStore.cs 프로젝트: jaydn/Quaver
        /// <summary>
        ///     Loads all sound effect elements.
        /// </summary>
        private void LoadSoundEffects()
        {
            var sfxFolder = $"{Dir}/SFX/";

            const string soundHit = "sound-hit";

            SoundHit = LoadSoundEffect($"{sfxFolder}/{soundHit}", soundHit, "Gameplay");

            const string soundHitClap = "sound-hitclap";

            SoundHitClap = LoadSoundEffect($"{sfxFolder}/{soundHitClap}", soundHitClap, "Gameplay");

            const string soundHitWhistle = "sound-hitwhistle";

            SoundHitWhistle = LoadSoundEffect($"{sfxFolder}/{soundHitWhistle}", soundHitWhistle, "Gameplay");

            const string soundHitFinish = "sound-hitfinish";

            SoundHitFinish = LoadSoundEffect($"{sfxFolder}/{soundHitFinish}", soundHitFinish, "Gameplay");

            const string soundComboBreak = "sound-combobreak";

            SoundComboBreak = LoadSoundEffect($"{sfxFolder}/{soundComboBreak}", soundComboBreak, "Gameplay");

            const string soundFailure = "sound-failure";

            SoundFailure = LoadSoundEffect($"{sfxFolder}/{soundFailure}", soundFailure, "Gameplay");

            const string soundRetry = "sound-retry";

            SoundRetry = LoadSoundEffect($"{sfxFolder}/{soundRetry}", soundRetry, "Gameplay");

            const string soundApplause = "sound-applause";

            SoundApplause = LoadSoundEffect($"{sfxFolder}/{soundApplause}", soundApplause, "Menu");

            const string soundScreenshot = "sound-screenshot";

            SoundScreenshot = LoadSoundEffect($"{sfxFolder}/{soundScreenshot}", soundScreenshot, "Menu");

            const string soundClick = "sound-click";

            SoundClick = LoadSoundEffect($"{sfxFolder}/{soundClick}", soundClick, "Menu");

            const string soundBack = "sound-back";

            SoundBack = LoadSoundEffect($"{sfxFolder}/{soundBack}", soundBack, "Menu");

            const string soundHover = "sound-hover";

            SoundHover = LoadSoundEffect($"{sfxFolder}/{soundHover}", soundHover, "Menu");
        }
예제 #33
0
        AudioSample IAudioSource.GetSample(ulong requestId)
        {
            AudioSample newSample = new AudioSample();

            if (_audioSource != null)
            {
                newSample = _audioSource(requestId);
            }

            newSample *= (float)Level * _masterLevel.GetNextSample();

            return(newSample);
        }
예제 #34
0
    private static AudioSourceContainer RegisterAndCreateAudioSourceContainer(AudioSample sample)
    {
        GameObject soundObject = AudioSourceContainer.CreateContainer(sample);

        AudioSourceContainer cont = soundObject.GetComponent <AudioSourceContainer>();
        AudioLayerSettings   audioLayerSettings = AudioLayerManager.GetAudioLayerSettings(sample.Layer);

        //Register
        Instance.AddAudioSource(cont);
        audioLayerSettings.ClipsPlaying++;

        return(cont);
    }
 void Start()
 {
     Sample = AudioManager.FindSampleFromCurrentLibrary(AudioSampleName);
     Radius = gameObject.GetComponent<CircleCollider2D>().radius;
     //Debug.Log(Radius);
 }
예제 #36
0
파일: ToolbarButton.cs 프로젝트: yheno/osu
 private void load(AudioManager audio)
 {
     sampleClick = audio.Sample.Get(@"Menu/menuclick");
 }
예제 #37
0
        private void UpdateUI(HeartBeatType t, TimeWindow w , TDESample[] tde, AudioSample[] a)
        {
            try
            {
                SetLabels(t);
                text1.Text = client.HeartBeatText(t);
                text2.Text = beat.ToString();

                text03.Text = tde[0].Value().ToString();
                text04.Text = tde[1].Value().ToString();
                text05.Text = tde[2].Value().ToString();
                text06.Text = a[1].Align().ToString();
                text07.Text = a[1].MaxAmplitude().ToString();
                text08.Text = a[1].Average().ToString();

                text13.Text = tde[3].Value().ToString();
                text14.Text = tde[4].Value().ToString();
                text15.Text = tde[5].Value().ToString();
                text16.Text = a[2].Align().ToString();
                text17.Text = a[2].MaxAmplitude().ToString();
                text18.Text = a[2].Average().ToString();

                text23.Text = tde[6].Value().ToString();
                text24.Text = tde[7].Value().ToString();
                text25.Text = tde[8].Value().ToString();
                text06.Text = a[3].Align().ToString();
                text07.Text = a[3].MaxAmplitude().ToString();
                text08.Text = a[3].Average().ToString();

                switch (t)
                {
                    case HeartBeatType.DATA:
                    case HeartBeatType.INVALID:
                    case HeartBeatType.SILENCE:
                        buffering = 0;
                        rebootPending = false;
                        break;
                    case HeartBeatType.BUFFERING:
                        buffering++;
                        break;
                    case HeartBeatType.DEVICE_ERROR:
                        rebootPending = true;
                        ResetEngine(10, "ERROR");
                        break;
                    case HeartBeatType.NODEVICE:
                        rebootPending = true;
                        break;
                }

                if (buffering == 30) { rebootPending = true; }
                else if (buffering >= 10 && buffering % 10 == 0) { ResetEngine(10, "RESET"); }
                
                if (t != HeartBeatType.BUFFERING) canvas.Children.Clear();
                if (t == HeartBeatType.DATA)
                {
                    SoundDirection(w.Samples(), 0.3, -1 * tde[0].Value(), 600, 200, 0, 200, new SolidColorBrush(Colors.Red), 4);
                    SoundDirection(w.Samples(), 0.3, -1 * tde[1].Value(), 600, 200, 0, 200, new SolidColorBrush(Colors.Green), 2);
                    SoundDirection(w.Samples(), 0.3, -1 * tde[2].Value(), 600, 200, 0, 200, new SolidColorBrush(Colors.Blue), 1);
                    samples++;       
                }
                text9.Text = samples.ToString();
            }
            catch (Exception ex)
            {
                Error("UpdateUI: " + ex.ToString() + " " + ex.Message + " " + ex.HResult);
            }
        }
예제 #38
0
 private void ThreadDelegate(HeartBeatType t, TimeWindow w , TDESample[] tde, AudioSample[] a)
 {
     try
     {
         var ign = Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
         {
             lock(accessLock)
             {
                 beat++;
                 if (w != null && tde != null && a != null)
                 {
                     var l = w.End();
                     if (t == HeartBeatType.BUFFERING)
                     {
                         l = w.Begin();
                         UpdateUI(t, w, tde, a);
                     }
                     UpdateUI(t, w, tde, a);
                     //client.AddMessage(t, cc0, asdf0, peak0, max0, max1, ave0, ave1, ave_all, beat, b - lastTimeStamp, l - b);
                     lastTimeStamp = l;
                 }
             }
         });
     }
     catch (Exception ex)            {
         Error("ThreadDelegate: " + ex.ToString() + " " + ex.Message + " " + ex.HResult);
     }        
 }
예제 #39
0
        private void SubmitAudioSample(AudioSample audioSample)
        {
            Stream sampleStream = WindowsRuntimeBufferExtensions.AsStream(audioSample.buffer);

            // Send out the next LPCM sample
            MediaStreamSample mediaStreamSamp = new MediaStreamSample(
                audioDesc,
                sampleStream,
                0,
                sampleStream.Length,
                (long)frameNumber, // FIXME?
                emptySampleDict);

            Debug.WriteLine("Submitting audio samples");
            ReportGetSampleCompleted(mediaStreamSamp);
        }
예제 #40
0
    public override void OnInspectorGUI()
    {
        serializedObject.Update();

        #region Get Data

        // Grab the object from the target in inspector
        AudioLibrary AudioLib = target as AudioLibrary;
        //AudioLibraryEditorData data = AudioLib.Data;
        int samplesCount = AudioLib.Samples.Count;

        #endregion

        #region First part of the editorGui Count & Add

        EditorGUILayout.BeginHorizontal();
        {
            EditorGUILayout.LabelField("Samples in library: " + samplesCount);
            if (GUILayout.Button("Add", addButtonStyle))
            {
                AddClipToList(AudioLib, null);
            }
        } EditorGUILayout.EndHorizontal();

        string folderPath;
        EditorGUILayout.BeginHorizontal();
        {
            // Check if there is already an dirpath in the editorPrefs
            folderPath = EditorPrefs.GetString(audioLibraryFolderPath, "");

            // If the button is pressed, find a new folder
            if (GUILayout.Button("Folder"))
                folderPath = EditorUtility.OpenFolderPanel("Select AudioFiles Folder", folderPath, "");

            // Show the directory in a user friendly manner
            string dir = "";
            if (folderPath != "")
                dir = FileUtility.AssetsRelativePath(folderPath);
            EditorGUILayout.LabelField("Dir: " + dir);

            // Save the changed string to the EditorPreference file
            if(GUI.changed)
                EditorPrefs.SetString(audioLibraryFolderPath, folderPath);

        } EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        {
            EditorGUILayout.LabelField("Add from directory: ");

            if (GUILayout.Button("AddFromDirectory"))
            {
                DirectoryInfo dir = new DirectoryInfo(folderPath);
                FileInfo[] allFiles = dir.GetFiles(); //FileUtility.GetResourcesDirectories();//data.folderPath);
                Debug.Log(allFiles.Length);
                //
                foreach (FileInfo f in allFiles)
                {
                    if (f.FullName.EndsWith(".wav") || f.FullName.EndsWith(".ogg"))
                    {
                        // Does not work
                        Debug.Log(f.FullName);

                        WWW www = new WWW(f.FullName);

                        AudioClip clip = www.GetAudioClip(true, false);
                        string[] split = f.FullName.Split('/');
                        clip.name = split[split.Length - 1];
                        if (AudioLib.Samples.Where(a => a.Clip == clip).Count() == 0)
                            AddClipToList(AudioLib, clip);
                        //clip
                    }
                }
                //Debug.Log(data.folderPath);
                //Debug.Log(FileUtility.AssetsRelativePath(data.folderPath));
            }
            //folderPath = EditorUtility.OpenFolderPanel("Select AudioFiles Folder", folderPath, "");

        } EditorGUILayout.EndHorizontal();

        if (GUILayout.Button("Clear"))
        {
            for (int i = samplesCount - 1; i >= 0; i--)
            {
                RemoveSample(AudioLib, i);
            }
            samplesCount = AudioLib.Samples.Count();
        }

        EditorGUILayout.Space();
        #endregion

        #region SampleLoop

        int removeAt = -1; // to store the index at where to delete at (must be bigger than 0)
        for (int i = 0; i < samplesCount; i++)
        {
            AudioSample sample = AudioLib.Samples[i];

            // Instantiate if null
            if (sample == null)
                sample = new AudioSample();

            #region Clip, Layer, Delete, Settingsfold

            bool fold;

            Rect hor = EditorGUILayout.BeginHorizontal();
            {
                Rect rect = new Rect(hor.xMin, hor.yMin, 15, hor.height);
                fold = SavedFoldout("", rect, i,"base");

                sample.Clip = EditorGUILayout.ObjectField("", sample.Clip, typeof(AudioClip), false, audioClipStyle) as AudioClip;
                sample.Layer = (AudioLayer)EditorGUILayout.EnumPopup("", sample.Layer, audioLayerStyle);

                // Delete button
                if (GUILayout.Button("X", delButtonStyle))
                    if (EditorUtility.DisplayDialog("Delete AudioSample", "Are you sure you want to delete this audioSample?", "ok", "cancel"))
                        removeAt = i;
            }
            EditorGUILayout.EndHorizontal();

            #endregion

            #region Settings

            if (fold)
            {
                EditorGUI.indentLevel++;
                sample.Name = EditorGUILayout.TextField("Name:", sample.Name, GUILayout.Width(250));
                //[RangeAttribute(0,1)]
                sample.Settings.Volume = EditorGUILayout.Slider("Volume: ",sample.Settings.Volume,0,1);
                EditorGUILayout.Space();

                sample.Settings.Loop = EditorGUILayout.Toggle("Loop: ", sample.Settings.Loop);
                //[RangeAttribute(0,255)]
                sample.Settings.Priority = EditorGUILayout.IntSlider("Priority: ",sample.Settings.Priority,0,255);
                //[RangeAttribute(-3, 3)]
                sample.Settings.Pitch = EditorGUILayout.Slider("Pitch: ",sample.Settings.Pitch,-3,3);

                EditorGUILayout.Space();
                sample.Settings.BypassEffects = EditorGUILayout.Toggle("BypassEffects:",sample.Settings.BypassEffects);
                sample.Settings.BypassListenerEffects = EditorGUILayout.Toggle("BypassListenerFX:",sample.Settings.BypassListenerEffects);
                sample.Settings.BypassReverbZones = EditorGUILayout.Toggle("BypassReverbZones:",sample.Settings.BypassReverbZones);

                // 3D Sound Settings
                if (SavedFoldout("3D Settings",i,"3D"))
                {
                    EditorGUI.indentLevel++;
                    //[RangeAttribute(0, 5)]
                    sample.Settings.DopplerLevel = EditorGUILayout.Slider("DopplerLevel:",sample.Settings.DopplerLevel, 0, 5);
                    //[RangeAttribute(0, 1)]
                    sample.Settings.PanLevel = EditorGUILayout.Slider("PanLevel:",sample.Settings.PanLevel, 0, 1);
                    //[RangeAttribute(0, 360)]
                    sample.Settings.Spread = EditorGUILayout.Slider("Spread: ",sample.Settings.Spread,0,360);
                    sample.Settings.MaxDistance = EditorGUILayout.FloatField("MaxDistance",sample.Settings.MaxDistance);
                    EditorGUI.indentLevel--;
                }

                 // 2D Sound Settings
                //data._2DSettings[i] = EditorGUILayout.Foldout(data._2DSettings[i], "2D Settings");
                if (SavedFoldout("2D Settings",i,"2D"))
                {
                    EditorGUI.indentLevel++;
                    //[RangeAttribute(-1, 1)]
                    sample.Settings.Pan2D = EditorGUILayout.Slider("Pan2D:",sample.Settings.Pan2D, -1, 1);
                    EditorGUI.indentLevel--;
                }
                EditorGUI.indentLevel--;
                EditorGUILayout.Space();
            }
            #endregion

            // Test if necessary
            //AudioLib.Samples[i] = sample;

        }

        #endregion

        #region IfDeleteSample

        // Do the deletion outside of the loop
        if (removeAt >= 0)
        {
            RemoveSample(AudioLib, removeAt);
        }

        #endregion
    }
예제 #41
0
 private void AddClipToList(AudioLibrary AudioLib, AudioClip audioClip)
 {
     //data.foldSettings.Add(false);
     //data._3DSettings.Add(false);
     //data._2DSettings.Add(false);
     AudioSample sample = new AudioSample();
     sample.Clip = audioClip;
     AudioLib.Samples.Add(sample);
 }
예제 #42
0
파일: BackButton.cs 프로젝트: yheno/osu
 private void load(AudioManager audio, OsuColour colours)
 {
     sampleClick = audio.Sample.Get(@"Menu/menuback");
     Children = new Drawable[]
     {
         new Container
         {
             RelativeSizeAxes = Axes.Both,
             Width = 0.4f,
             Children = new Drawable[]
             {
                 leftBox = new Box
                 {
                     RelativeSizeAxes = Axes.Both,
                     Colour = colours.PinkDark,
                     Shear = new Vector2(shear, 0),
                 },
                 icon = new TextAwesome
                 {
                     Anchor = Anchor.Centre,
                     TextSize = 25,
                     Icon = FontAwesome.fa_osu_left_o
                 },
             }
         },
         new Container
         {
             Origin = Anchor.TopRight,
             Anchor = Anchor.TopRight,
             RelativeSizeAxes = Axes.Both,
             Width = 0.6f,
             Children = new Drawable[]
             {
                 rightBox = new Box
                 {
                     Colour = colours.Pink,
                     Origin = Anchor.TopLeft,
                     Anchor = Anchor.TopLeft,
                     RelativeSizeAxes = Axes.Both,
                     Shear = new Vector2(shear, 0),
                     EdgeSmoothness = new Vector2(1.5f, 0),
                 },
                 new SpriteText
                 {
                     Origin = Anchor.Centre,
                     Anchor = Anchor.Centre,
                     Text = @"Back",
                 }
             }
         }
     };
 }
예제 #43
0
파일: PlaySongSelect.cs 프로젝트: yheno/osu
        private void load(BeatmapDatabase beatmaps, AudioManager audio, BaseGame game,
            OsuGame osuGame, OsuColour colours)
        {
            const float carouselWidth = 640;
            const float bottomToolHeight = 50;
            Children = new Drawable[]
            {
                new ParallaxContainer
                {
                    ParallaxAmount = 0.005f,
                    RelativeSizeAxes = Axes.Both,
                    Children = new []
                    {
                        new WedgeBackground
                        {
                            RelativeSizeAxes = Axes.Both,
                            Padding = new MarginPadding { Right = carouselWidth * 0.76f },
                        },
                    }
                },
                carousel = new CarouselContainer
                {
                    RelativeSizeAxes = Axes.Y,
                    Size = new Vector2(carouselWidth, 1),
                    Anchor = Anchor.CentreRight,
                    Origin = Anchor.CentreRight,
                },
                beatmapInfoWedge = new BeatmapInfoWedge
                {
                    Alpha = 0,
                    Position = wedged_container_start_position,
                    Size = wedged_container_size,
                    RelativeSizeAxes = Axes.X,
                    Margin = new MarginPadding { Top = 20, Right = 20, },
                },
                new Container
                {
                    RelativeSizeAxes = Axes.X,
                    Height = bottomToolHeight,
                    Anchor = Anchor.BottomCentre,
                    Origin = Anchor.BottomCentre,
                    Children = new Drawable[]
                    {
                        new Box
                        {
                            RelativeSizeAxes = Axes.Both,
                            Size = Vector2.One,
                            Colour = Color4.Black.Opacity(0.5f),
                        },
                        new BackButton
                        {
                            Anchor = Anchor.BottomLeft,
                            Origin = Anchor.BottomLeft,
                            //RelativeSizeAxes = Axes.Y,
                            Action = () => Exit()
                        },
                        new Button
                        {
                            Anchor = Anchor.CentreRight,
                            Origin = Anchor.CentreRight,
                            RelativeSizeAxes = Axes.Y,
                            Width = 100,
                            Text = "Play",
                            Colour = colours.Pink,
                            Action = start
                        },
                    }
                }
            };
        
            if (osuGame != null)
            {
                playMode = osuGame.PlayMode;
                playMode.ValueChanged += playMode_ValueChanged;
            }

            if (database == null)
                database = beatmaps;

            database.BeatmapSetAdded += onDatabaseOnBeatmapSetAdded;

            trackManager = audio.Track;

            sampleChangeDifficulty = audio.Sample.Get(@"SongSelect/select-difficulty");
            sampleChangeBeatmap = audio.Sample.Get(@"SongSelect/select-expand");

            initialAddSetsTask = new CancellationTokenSource();

            Task.Factory.StartNew(() => addBeatmapSets(game, initialAddSetsTask.Token), initialAddSetsTask.Token);
        }
예제 #44
0
파일: Audio.cs 프로젝트: henon/manic_digger
 AudioSample GetSample(string filename)
 {
     if (!audio.cache.ContainsKey(filename))
     {
         Stream stream = audio.d_GetFile.GetFile(filename);
         if (stream.ReadByte() == 'R'
             && stream.ReadByte() == 'I'
             && stream.ReadByte() == 'F'
             && stream.ReadByte() == 'F')
         {
             stream.Position = 0;
             int channels, bits_per_sample, sample_rate;
             byte[] sound_data = LoadWave(stream, out channels, out bits_per_sample, out sample_rate);
             AudioSample sample = new AudioSample()
             {
                 Pcm = sound_data,
                 BitsPerSample = bits_per_sample,
                 Channels = channels,
                 Rate = sample_rate,
             };
             audio.cache[filename] = sample;
         }
         else
         {
             stream.Position = 0;
             AudioSample sample = new OggDecoder().OggToWav(stream);
             audio.cache[filename] = sample;
         }
     }
     return audio.cache[filename];
 }