Inheritance: ScriptableObject
Esempio n. 1
0
 // creates a snippet along with its new AudioData object based on the filename
 public Segment(int id, AudioData audioData)
 {
     init();
     this.AudioData = audioData;
     Id = id;
     this.Name = System.IO.Path.GetFileNameWithoutExtension(System.IO.Path.GetFileName(audioData.FilePathRelativeToProjectDir));
 }
Esempio n. 2
0
 public override void ReadBlock(FlvContext context)
 {
     base.ReadBlock(context);
     var br = context.Reader;
     var dat = br.ReadBytes((int)this.Header.DataLength);
     data = new AudioData(dat);
     this.Size += this.Header.DataLength;
     context.CurrentPostion += this.Size;
 }
Esempio n. 3
0
 internal int Set(string key, AudioData bmp)
 {
     int id = GetId(key);
     if (id != -1)
     {
         values[id] = bmp;
         return id;
     }
     for (int i = 0; i < max; i++)
     {
         if (keys[i] == null)
         {
             keys[i] = key;
             values[i] = bmp;
             return i;
         }
     }
     return -1;
 }
 public static AudioData[] EditAudioDataArray(GameObject gameObject,
                                              AudioData[] AudioDataArray)
 {
     if (GUILayout.Button ("Add Audio Data")) {
         AudioData audioData = new AudioData ();
         AudioDataArray = Util.AddToArray<AudioData> (audioData, AudioDataArray);
     }
     for(int i=0; i<AudioDataArray.Length; i++)
     {
         AudioData audio = AudioDataArray [i];
         EditorGUILayout.LabelField ("------------------------ " + audio.Name);
         audio.Name = EditorGUILayout.TextField (new GUIContent ("Name", ""), audio.Name);
         audio.randomAudioClips = EditorCommon.EditObjectArray<AudioClip>("Edit Audio clips:", audio.randomAudioClips);
         //Delete this audio data
         if (GUILayout.Button ("Delete AduioData:" + audio.Name)) {
             AudioDataArray = Util.CloneExcept<AudioData> (AudioDataArray, audio);
         }
     }
     EditorGUILayout.Space ();
     return AudioDataArray;
 }
 public bool Register(string name, AudioData data)
 {
     if (sounds.ContainsKey (name)) {
         return false;
     }
     sounds.Add (name, data);
     return true;
 }
Esempio n. 6
0
 public AudioData GetClone()
 {
     AudioData clone = new AudioData();
     clone.Name = this.Name;
     clone.randomAudioClips = randomAudioClips;
     return clone;
 }
 public void Play(AudioData audio)
 {
     Load(audio.clip);
     Play();
 }
Esempio n. 8
0
    /// <summary>
    /// Initializes this emitter. This is either called from the audio engine if the emitter is static, or from a game object in the world if it's spawned dynamically.
    /// </summary>
    public void Initialize(bool dynamic)
    {
        if (!string.IsNullOrEmpty(audioDataFileName))
        {
            audioData = AudioBank.GetAudioData(audioDataFileName);
            outputRateFactor = (float)audioData.Frequency / AudioSettings.outputSampleRate;
            isCreatedDynamically = dynamic;

            if (is3DSound)
            {
                leftPan = 0.0f;
                rightPan = 0.0f;
            }
        }
    }
    private IEnumerator RecordingHandler()
    {
        Log.Debug("ExampleStreaming.RecordingHandler()", "devices: {0}", Microphone.devices);
        _recording = Microphone.Start(_microphoneID, true, _recordingBufferSize, _recordingHZ);
        yield return(null);      // let _recordingRoutine get set..

        if (_recording == null)
        {
            StopRecording();
            yield break;
        }

        bool bFirstBlock = true;
        int  midPoint    = _recording.samples / 2;

        float[] samples = null;

        while (_recordingRoutine != 0 && _recording != null)
        {
            int writePos = Microphone.GetPosition(_microphoneID);
            if (writePos > _recording.samples || !Microphone.IsRecording(_microphoneID))
            {
                Log.Error("ExampleStreaming.RecordingHandler()", "Microphone disconnected.");

                StopRecording();
                yield break;
            }

            if ((bFirstBlock && writePos >= midPoint) ||
                (!bFirstBlock && writePos < midPoint))
            {
                // front block is recorded, make a RecordClip and pass it onto our callback.
                samples = new float[midPoint];

                _recording.GetData(samples, bFirstBlock ? 0 : midPoint);

                samplesGlobal = samples;

                AudioData record = new AudioData();
                record.MaxLevel = Mathf.Max(Mathf.Abs(Mathf.Min(samples)), Mathf.Max(samples));
                record.Clip     = AudioClip.Create("Recording", midPoint, _recording.channels, _recordingHZ, false);
                record.Clip.SetData(samples, 0);

                _service.OnListen(record);

                //healthBar.UpdateBar(25, 100);
                //Debug.Log(healthBar.ToString());

                bFirstBlock = !bFirstBlock;
                //Handheld.Vibrate();
                FindDecibelLevels();
            }
            else
            {
                // calculate the number of samples remaining until we ready for a block of audio,
                // and wait that amount of time it will take to record.
                int   remaining     = bFirstBlock ? (midPoint - writePos) : (_recording.samples - writePos);
                float timeRemaining = (float)remaining / (float)_recordingHZ;

                yield return(new WaitForSeconds(timeRemaining));
            }
        }

        yield break;
    }
Esempio n. 10
0
 public override AudioCi AudioCreate(AudioData data)
 {
     return audio.CreateAudio((AudioDataCs)data);
 }
Esempio n. 11
0
        private Metadata RequestMetadataInner(string path, bool async)
        {
            //System.Diagnostics.Debug.WriteLine("Loading metadata \"" + path + "\"...");

#if UNCOMPRESSED_CONTENT
            string pathAbsolute = PathOp.Combine(DualityApp.DataDirectory, "Metadata", path + ".res");
#else
            string pathAbsolute = PathOp.Combine(DualityApp.DataDirectory, "Main.dz", "Metadata", path + ".res");
#endif

            MetadataJson json;
            using (Stream s = FileOp.Open(pathAbsolute, FileAccessMode.Read)) {
                lock (jsonParser) {
                    json = jsonParser.Parse<MetadataJson>(s);
                }
            }

            Metadata metadata = new Metadata();
            metadata.Referenced = true;
            metadata.AsyncFinalizingRequired = async;

            // Pre-load graphics
            if (json.Animations != null) {
                metadata.Graphics = new Dictionary<string, GraphicResource>();

                foreach (KeyValuePair<string, MetadataJson.AnimationsSection> g in json.Animations) {
                    if (g.Value.Path == null) {
                        // No path provided, skip resource...
                        continue;
                    }

#if !THROW_ON_MISSING_RESOURCES
                    try {
#endif
                        bool isIndexed = (g.Value.Flags & 0x02) != 0x00;

                        ColorRgba color;
                        if (g.Value.ShaderColor == null || g.Value.ShaderColor.Count < 4) {
                            color = (isIndexed ? new ColorRgba(0, 255) : ColorRgba.White);
                        } else {
                            color = new ColorRgba((byte)g.Value.ShaderColor[0], (byte)g.Value.ShaderColor[1], (byte)g.Value.ShaderColor[2], (byte)g.Value.ShaderColor[3]);
                        }

                        GenericGraphicResource resBase = RequestGraphicResource(g.Value.Path, async);

                        // Create copy of generic resource
                        GraphicResource res;
                        if (async) {
                            res = GraphicResource.From(resBase, g.Value.Shader, color, isIndexed);
                        } else {
                            ContentRef<DrawTechnique> drawTechnique;
                            if (g.Value.Shader == null) {
                                drawTechnique = (isIndexed ? paletteNormal : basicNormal);
                            } else {
                                drawTechnique = RequestShader(g.Value.Shader);
                            }

                            res = GraphicResource.From(resBase, drawTechnique, color, isIndexed, paletteTexture);
                        }

                        res.FrameOffset = g.Value.FrameOffset;

                        string raw1, raw2; int raw3;
                        if ((raw1 = g.Value.FrameCount as string) != null && int.TryParse(raw1, out raw3)) {
                            res.FrameCount = raw3;
                        } else {
                            res.FrameCount -= res.FrameOffset;
                        }
                        if ((raw2 = g.Value.FrameRate as string) != null && int.TryParse(raw2, out raw3)) {
                            res.FrameDuration = (raw3 <= 0 ? -1 : (1f / raw3) * 5); // ToDo: I don't know...
                        }

                        res.OnlyOnce = (g.Value.Flags & 0x01) != 0x00;

                        if (g.Value.States != null) {
                            res.State = new HashSet<AnimState>();
                            for (int i = 0; i < g.Value.States.Count; i++) {
                                res.State.Add((AnimState)g.Value.States[i]);
                            }
                        }

                        metadata.Graphics[g.Key] = res;
#if !THROW_ON_MISSING_RESOURCES
                    } catch (Exception ex) {
#if !SERVER
                        Log.Write(LogType.Warning, "Can't load animation \"" + g.Key + "\" from metadata \"" + path + "\": " + ex.Message);
#endif
                    }
#endif
                    }
            }

#if !DISABLE_SOUND
            // Pre-load sounds
            if (json.Sounds != null) {
                metadata.Sounds = new Dictionary<string, SoundResource>();

                foreach (var sound in json.Sounds) {
                    if (sound.Value.Paths == null || sound.Value.Paths.Count == 0) {
                        // No path provided, skip resource...
                        continue;
                    }

#if !THROW_ON_MISSING_RESOURCES
                    try {
#endif
                        IList<string> filenames = sound.Value.Paths;
                        ContentRef<AudioData>[] data = new ContentRef<AudioData>[filenames.Count];
                        for (int i = 0; i < data.Length; i++) {
#if UNCOMPRESSED_CONTENT
                            using (Stream s = FileOp.Open(PathOp.Combine(DualityApp.DataDirectory, "Animations", filenames[i]), FileAccessMode.Read))
#else
                            using (Stream s = FileOp.Open(PathOp.Combine(DualityApp.DataDirectory, "Main.dz", "Animations", filenames[i]), FileAccessMode.Read))
#endif
                            {
                                data[i] = new AudioData(s);
                            }
                        }

                        SoundResource resource = new SoundResource();
                        resource.Sound = new Sound(data);
                        metadata.Sounds[sound.Key] = resource;
#if !THROW_ON_MISSING_RESOURCES
                    } catch (Exception ex) {
#if !SERVER
                        Log.Write(LogType.Warning, "Can't load sound \"" + sound.Key + "\" from metadata \"" + path + "\": " + ex.Message);
#endif
                    }
#endif
                    }
                }
#endif

            // Bounding Box
            if (json.BoundingBox != null && json.BoundingBox.Count == 2) {
                metadata.BoundingBox = new Point2(json.BoundingBox[0], json.BoundingBox[1]);
            }

            cachedMetadata[path] = metadata;

            // Request children
            if (json.Preload != null) {
                for (int i = 0; i < json.Preload.Count; i++) {
                    PreloadAsync(json.Preload[i]);
                }
            }

            return metadata;
        }
        private IEnumerator RecordingHandler()
        {
            Failure = false;
#if UNITY_WEBPLAYER
            yield return(Application.RequestUserAuthorization(UserAuthorization.Microphone));
#endif
            m_Recording = Microphone.Start(m_MicrophoneID, true, m_RecordingBufferSize, m_RecordingHZ);
            yield return(null);      // let m_RecordingRoutine get set..

            if (m_Recording == null)
            {
                Failure = true;
                StopRecording();
                yield break;
            }

            bool bFirstBlock = true;
            int  midPoint    = m_Recording.samples / 2;

            bool bOutputLevelData = m_LevelOutput.IsConnected;
            bool bOutputAudio     = m_AudioOutput.IsConnected || m_PlaybackRecording;

            int     lastReadPos = 0;
            float[] samples     = null;

            while (m_RecordingRoutine != 0 && m_Recording != null)
            {
                int writePos = Microphone.GetPosition(m_MicrophoneID);
                if (writePos > m_Recording.samples || !Microphone.IsRecording(m_MicrophoneID))
                {
                    Log.Error("MicrophoneWidget", "Microphone disconnected.");

                    Failure = true;
                    StopRecording();
                    yield break;
                }

                if (bOutputAudio)
                {
                    if ((bFirstBlock && writePos >= midPoint) ||
                        (!bFirstBlock && writePos < midPoint))
                    {
                        // front block is recorded, make a RecordClip and pass it onto our callback.
                        samples = new float[midPoint];
                        m_Recording.GetData(samples, bFirstBlock ? 0 : midPoint);

                        AudioData record = new AudioData();
                        record.MaxLevel = Mathf.Max(samples);
                        record.Clip     = AudioClip.Create("Recording", midPoint, m_Recording.channels, m_RecordingHZ, false);
                        record.Clip.SetData(samples, 0);

                        if (m_PlaybackRecording)
                        {
                            m_Playback.Add(record.Clip);
                        }
                        if (m_AudioOutput.IsConnected && !m_AudioOutput.SendData(record))
                        {
                            StopRecording();        // automatically stop recording if the callback goes away.
                        }
                        bFirstBlock = !bFirstBlock;
                    }
                    else
                    {
                        // calculate the number of samples remaining until we ready for a block of audio,
                        // and wait that amount of time it will take to record.
                        int   remaining     = bFirstBlock ? (midPoint - writePos) : (m_Recording.samples - writePos);
                        float timeRemaining = (float)remaining / (float)m_RecordingHZ;
                        if (bOutputLevelData && timeRemaining > m_LevelOutputInterval)
                        {
                            timeRemaining = m_LevelOutputInterval;
                        }
                        yield return(new WaitForSeconds(timeRemaining));
                    }
                }
                else
                {
                    yield return(new WaitForSeconds(m_LevelOutputInterval));
                }

                if (m_Recording != null && bOutputLevelData)
                {
                    float fLevel = 0.0f;
                    if (writePos < lastReadPos)
                    {
                        // write has wrapped, grab the last bit from the buffer..
                        samples = new float[m_Recording.samples - lastReadPos];
                        m_Recording.GetData(samples, lastReadPos);
                        fLevel = Mathf.Max(fLevel, Mathf.Max(samples));

                        lastReadPos = 0;
                    }

                    if (lastReadPos < writePos)
                    {
                        samples = new float[writePos - lastReadPos];
                        m_Recording.GetData(samples, lastReadPos);
                        fLevel = Mathf.Max(fLevel, Mathf.Max(samples));

                        lastReadPos = writePos;
                    }

                    m_LevelOutput.SendData(new LevelData(fLevel * m_LevelOutputModifier, m_LevelOutputModifier));
                }
            }

            yield break;
        }
        private static int ReadFlacFile(string path, out AudioData ad)
        {
            ad = new AudioData();

            ad.fileFormat = FileFormatType.FLAC;

            var flac = new WWFlacRWCS.FlacRW();
            int rv = flac.DecodeAll(path);
            if (rv < 0) {
                return rv;
            }

            rv = flac.GetDecodedMetadata(out ad.meta);
            if (rv < 0) {
                return rv;
            }

            rv = flac.GetDecodedPicture(out ad.picture, ad.meta.pictureBytes);
            if (rv < 0) {
                return rv;
            }

            ad.pcm = new List<AudioDataPerChannel>();
            for (int ch=0; ch < ad.meta.channels; ++ch) {
                byte [] data;
                long lrv = flac.GetDecodedPcmBytes(ch, 0, out data, ad.meta.totalSamples * (ad.meta.bitsPerSample / 8));
                if (lrv < 0) {
                    return (int)lrv;
                }

                var adp = new AudioDataPerChannel();
                adp.data = data;
                adp.offsBytes = 0;
                adp.bitsPerSample = ad.meta.bitsPerSample;
                adp.totalSamples = ad.meta.totalSamples;
                ad.pcm.Add(adp);
            }

            flac.DecodeEnd();

            return 0;
        }
Esempio n. 14
0
 public void registerAudioData(Audio_Type type, AudioData data)
 {
     AudioDatas.Add(type, data);
 }
Esempio n. 15
0
        protected override AudioSource CreateSound(AudioData data)
        {
            GameObject go = new GameObject($"Sound_{data.Id}");

            return(go.AddComponent <AudioSource>());
        }
Esempio n. 16
0
        /** 
        @brief Unlock the previously acquired buffer.
        @param[in] data		The sample data storage previously acquired.
        @return PXCM_STATUS_NO_ERROR	Successful execution.
        */
        public pxcmStatus ReleaseAccess(AudioData data)
        {
            AudioDataNative dataNative = data as AudioDataNative;
            if (dataNative == null) return pxcmStatus.PXCM_STATUS_HANDLE_INVALID;
            if (dataNative.native == IntPtr.Zero) return pxcmStatus.PXCM_STATUS_HANDLE_INVALID;

            Marshal.WriteInt32(dataNative.native, Marshal.OffsetOf(typeof(AudioData), "dataSize").ToInt32(), unchecked((Int32)data.dataSize));
            pxcmStatus sts = PXCMAudio_ReleaseAccess(instance, dataNative.native);
            Marshal.FreeHGlobal(dataNative.native);
            dataNative.native = IntPtr.Zero;
            return sts;
        }
Esempio n. 17
0
        /** 
        @brief Lock to access the internal storage of a specified format. The function will perform format conversion if unmatched. 
        @param[in]  access		The access mode.
        @param[in]  format		The requested smaple format.
        @param[in]  options     The option flags
        @param[out] data		The sample data storage, to be returned.
        @return PXC_STATUS_NO_ERROR	Successful execution.
        */
        public pxcmStatus AcquireAccess(Access access, AudioFormat format, Option options, out AudioData data)
        {
            AudioDataNative dataNative = new AudioDataNative();
            dataNative.native = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(AudioDataNative)));
            data = dataNative;

            pxcmStatus sts = PXCMAudio_AcquireAccess(instance, access, format, options, dataNative.native);
            if (sts >= pxcmStatus.PXCM_STATUS_NO_ERROR)
            {
                IntPtr native = dataNative.native;
                Marshal.PtrToStructure(dataNative.native, dataNative);
                dataNative.native = native;
            }
            else
            {
                Marshal.FreeHGlobal(dataNative.native);
                dataNative.native = IntPtr.Zero;
            }
            return sts;
        }
 public void AddAudioData(string name, AudioData audioData)
 {
     audioDatas.Add(name, audioData);
 }
Esempio n. 19
0
    /// <summary>
    /// Attempts loading an audio file with a specified filename.
    /// Will throw an exception if the file could not be read for some reason.
    /// This function does only read 16-bit .wav files with no metadata. If the file is not valid then it could lead to corrupt data,
    /// or unhandled exceptions.
    /// </summary>
    /// <param name="filename">The path to the file to be read.</param>
    /// <returns>AudioData, or null.</returns>
    public static AudioData LoadFromFile(string filename)
    {
        AudioData audioData = null;

        using (BinaryReader reader = new BinaryReader(File.OpenRead(filename)))
        {
            Debug.Log("Reading wav: " + filename);

            reader.BaseStream.Seek(22, SeekOrigin.Begin);
            ushort channels = reader.ReadUInt16();
            //Debug.Log("Channels: " + channels);
            uint sampleRate = reader.ReadUInt32();
            //Debug.Log("Sample rate: " + sampleRate);
            reader.BaseStream.Seek(34, SeekOrigin.Begin);
            ushort bitsPerSample = reader.ReadUInt16();
            //Debug.Log("Bits per sample: " + bitsPerSample);
            reader.BaseStream.Seek(40, SeekOrigin.Begin);
            uint numberOfBytes = reader.ReadUInt32();
            //Debug.Log("Number of bytes: " + numberOfBytes);
            uint numberOfSamples = numberOfBytes * 8 / bitsPerSample;
            //Debug.Log("Number of samples: " + numberOfSamples);

            float maxAmplitude = 0.0f;
            float[] data = new float[numberOfSamples * channels];
            //short[] shortData = new short[numberOfSamples * channels];
            byte[] buffer = new byte[numberOfBytes];

            if (bitsPerSample / 8 == 2)
            {

                reader.BaseStream.Seek(44, SeekOrigin.Begin);
                buffer = reader.ReadBytes((int)numberOfBytes);

                int bufferStep = 0;
                for (int i = 0; i < numberOfSamples && bufferStep < buffer.Length; i++)
                {
                    float sample = (float)BitConverter.ToInt16(buffer, bufferStep) / Int16.MaxValue;

                    float abs = Mathf.Abs(sample);
                    if (abs > maxAmplitude)
                        maxAmplitude = abs;

                    data[i] = sample;
                    bufferStep += 2;
                }
            }
            else
                Debug.LogWarning(filename + "is not a 16-bit wav.");

            audioData = new AudioData(data, (int)channels, (int)sampleRate, maxAmplitude, (int)numberOfSamples / (int)channels);
        }

        return audioData;
    }
Esempio n. 20
0
 public override bool AudioDataLoaded(AudioData data)
 {
     return true;
 }
Esempio n. 21
0
 public int EnqueueSamples(AudioData audioData)
 {
     return EnqueueSamples(audioData.Channels, audioData.Rate, audioData.Samples, audioData.Frames);
 }
Esempio n. 22
0
 public abstract AudioCi AudioCreate(AudioData data);
Esempio n. 23
0
        private IPromise <AudioData> loadAudioClipPath(string path, int type, float volume)
        {
            if (string.IsNullOrEmpty(path))
            {
                return(null);
            }

            if (sounds[path] != null)
            {
                AudioData audioData = sounds[path];
                if (audioData != null && audioData.audio != null)
                {
                    audioData.audio.volume = _closeSound ? 0f : volume;
                }
                else
                {
                    sounds.RemoveKey(path);
                }
                return(Promise <AudioData> .Resolved(audioData));
            }

            int       priority     = 128;
            bool      loop         = false;
            float     minPitch     = 0;
            float     maxPitch     = 3;
            float     maxDistance  = 25;
            float     spatialBlend = 0;
            AudioData data         = new AudioData(path, (SoundType)type, loop, SoundParent.transform, Vector3.zero,
                                                   priority, minPitch, maxPitch, volume, maxDistance, spatialBlend);

            string extension = Path.GetExtension(path);
            string fileName  = path.Replace(extension, "");

            extension = extension.Substring(1);

            IPromise <AudioData> adPromise = new Promise <AudioData>((s, j) =>
            {
                ResourceManager.LoadAudioClipBundleAsync(fileName, extension)
                .Then((audioClip) =>
                {
                    if (audioClip == null)
                    {
                        throw new Exception(string.Format("Cant Load AudioClip! Path :{0}", path));
                    }

                    if (data.audio != null)
                    {
                        data.audio.clip   = audioClip;
                        data.audio.volume = _closeSound ? 0f : volume;
                        sounds.Put(path, data);
                    }
                    s.Invoke(data);
                })
                .Catch(e =>
                {
                    j.Invoke(e);
                    Debug.LogException(e);
                });
            });

            return(adPromise);
        }
Esempio n. 24
0
 public abstract bool AudioDataLoaded(AudioData data);
        private int SetupResultPcm(AudioData from, out AudioData to, FileFormatType toFileFormat)
        {
            to = new AudioData();
            to.fileFormat = toFileFormat;

            var fmt = FilterSetup(from, mFilters);

            to.meta = new WWFlacRWCS.Metadata(from.meta);
            to.meta.sampleRate = fmt.SampleRate;
            to.meta.totalSamples = fmt.NumSamples;
            to.meta.channels = fmt.Channels;

            switch (toFileFormat) {
            case FileFormatType.FLAC:
            #if true
                to.meta.bitsPerSample = 24;
            #endif
                break;
            case FileFormatType.DSF:
                to.meta.bitsPerSample = 1;
                break;
            }

            if (from.picture != null) {
                to.picture = new byte[from.picture.Length];
                System.Array.Copy(from.picture, to.picture, to.picture.Length);
            }

            // allocate "to" pcm data
            to.pcm = new List<AudioDataPerChannel>();
            for (int ch=0; ch < to.meta.channels; ++ch) {
                byte [] data;

                // set silent sample values to output buffer
                switch (toFileFormat) {
                case FileFormatType.DSF:
                    if (0x7FFFFFC7 < (to.meta.totalSamples + 7) / 8) {
                        return (int)WWFlacRWCS.FlacErrorCode.OutputFileTooLarge;
                    }
                    data = new byte[(to.meta.totalSamples + 7) / 8];
                    for (long i=0; i < data.LongLength; ++i) {
                        data[i] = 0x69;
                    }
                    break;
                case FileFormatType.FLAC:
                    if (0x7FFFFFC7 < to.meta.totalSamples * (to.meta.bitsPerSample / 8)) {
                        return (int)WWFlacRWCS.FlacErrorCode.OutputFileTooLarge;
                    }
                    data = new byte[to.meta.totalSamples * (to.meta.bitsPerSample / 8)];
                    break;
                default:
                    System.Diagnostics.Debug.Assert(false);
                    data = null;
                    break;
                }

                var adp = new AudioDataPerChannel();
                adp.data = data;
                adp.bitsPerSample = to.meta.bitsPerSample;
                adp.totalSamples = to.meta.totalSamples;
                to.pcm.Add(adp);
            }
            return 0;
        }
Esempio n. 26
0
 void Start()
 {
     AudioData.PlaySound(SoundHandle.PieCharge, gameObject);
     loadDirIndicator();
     indicatorCalc();
 }
Esempio n. 27
0
 /** 
     @brief Lock to access the internal storage of a specified format. 
     @param[in]  access		The access mode.
     @param[out] data		The sample data storage, to be returned.
     @return PXCM_STATUS_NO_ERROR	Successful execution.
 */
 public pxcmStatus AcquireAccess(Access access, out AudioData data)
 {
     return AcquireAccess(access, (AudioFormat)0, out data);
 }
Esempio n. 28
0
 public abstract bool AudioDataLoaded(AudioData data);
Esempio n. 29
0
 public abstract AudioCi AudioCreate(AudioData data);
Esempio n. 30
0
 // Used for UI SFX
 public void PlaySFX(AudioData audioData)
 {
     sFXPlayer.PlayOneShot(audioData.audioClip, audioData.volume);
 }
Esempio n. 31
0
 protected override byte[] GetData(AudioData audio)
 {
     return(new IdspWriter().GetFile(audio));
 }
Esempio n. 32
0
 // Used for repeat-play SFX
 public void PlayRandomSFX(AudioData audioData)
 {
     sFXPlayer.pitch = Random.Range(MIN_PITCH, MAX_PITCH);
     PlaySFX(audioData);
 }
Esempio n. 33
0
 void IConsumer.ConsumeAudioData(AudioData data)
 {
     _audioFile.Write(data.Data, 0, data.Data.Length);
 }
 public abstract void OnData(AudioData data);
 public void Load(AudioData audio)
 {
     Load(audio.clip);
 }
Esempio n. 36
0
 /// <summary>
 /// Writes the specified audio data to the stream as the next frame.
 /// </summary>
 /// <param name="data">The audio data to write.</param>
 /// <param name="customTime">Custom timestamp for this frame.</param>
 public void AddFrame(AudioData data, TimeSpan customTime) => AddFrame(data, customTime.ToTimestamp(Configuration.TimeBase));
Esempio n. 37
0
 public void PlayAudioEvent(AudioData data)
 {
     controller.PlayAudio(data, gameObject);
 }
Esempio n. 38
0
 /// <summary>
 /// Writes the specified audio data to the stream as the next frame.
 /// </summary>
 /// <param name="data">The audio data to write.</param>
 public void AddFrame(AudioData data) => AddFrame(data, lastFramePts + 1);
 public void SetAudioData(AudioData value)
 {
     _audioData = value;
 }
Esempio n. 40
0
 private static void SaveAudioData(AudioData audio, string targetPath)
 {
     File.WriteAllBytes(targetPath, audio.OggVorbisData);
 }
Esempio n. 41
0
    // Add a section of an ini file to game content
    // name is from the ini file and must start with the type
    // path is relative and is used for images or other paths in the content
    void AddContent(string name, Dictionary <string, string> content, string path, string packID)
    {
        // Is this a "PackType" entry?
        if (name.IndexOf(PackTypeData.type) == 0)
        {
            PackTypeData d = new PackTypeData(name, content, path);
            // Ignore invalid entry
            if (d.name.Equals(""))
            {
                return;
            }
            // If we don't already have one then add this
            if (!packTypes.ContainsKey(name))
            {
                packTypes.Add(name, d);
                d.sets.Add(packID);
            }
            // If we do replace if this has higher priority
            else if (packTypes[name].priority < d.priority)
            {
                packTypes.Remove(name);
                packTypes.Add(name, d);
            }
            // items of the same priority belong to multiple packs
            else if (packTypes[name].priority == d.priority)
            {
                packTypes[name].sets.Add(packID);
            }
        }

        // Is this a "TileSide" entry?
        if (name.IndexOf(TileSideData.type) == 0)
        {
            TileSideData d = new TileSideData(name, content, path);
            // Ignore invalid entry
            if (d.name.Equals(""))
            {
                return;
            }
            // If we don't already have one then add this
            if (!tileSides.ContainsKey(name))
            {
                tileSides.Add(name, d);
                d.sets.Add(packID);
            }
            // If we do replace if this has higher priority
            else if (tileSides[name].priority < d.priority)
            {
                tileSides.Remove(name);
                tileSides.Add(name, d);
            }
            // items of the same priority belong to multiple packs
            else if (tileSides[name].priority == d.priority)
            {
                tileSides[name].sets.Add(packID);
            }
        }

        // Is this a "Hero" entry?
        if (name.IndexOf(HeroData.type) == 0)
        {
            HeroData d = new HeroData(name, content, path);
            // Ignore invalid entry
            if (d.name.Equals(""))
            {
                return;
            }
            // If we don't already have one then add this
            if (!heroes.ContainsKey(name))
            {
                heroes.Add(name, d);
                d.sets.Add(packID);
            }
            // If we do replace if this has higher priority
            else if (heroes[name].priority < d.priority)
            {
                heroes.Remove(name);
                heroes.Add(name, d);
            }
            // items of the same priority belong to multiple packs
            else if (heroes[name].priority == d.priority)
            {
                heroes[name].sets.Add(packID);
            }
        }

        // Is this a "Class" entry?
        if (name.IndexOf(ClassData.type) == 0)
        {
            ClassData d = new ClassData(name, content, path);
            // Ignore invalid entry
            if (d.name.Equals(""))
            {
                return;
            }
            // If we don't already have one then add this
            if (!classes.ContainsKey(name))
            {
                classes.Add(name, d);
                d.sets.Add(packID);
            }
            // If we do replace if this has higher priority
            else if (classes[name].priority < d.priority)
            {
                classes.Remove(name);
                classes.Add(name, d);
            }
            // items of the same priority belong to multiple packs
            else if (classes[name].priority == d.priority)
            {
                classes[name].sets.Add(packID);
            }
        }

        // Is this a "Skill" entry?
        if (name.IndexOf(SkillData.type) == 0)
        {
            SkillData d = new SkillData(name, content, path);
            // Ignore invalid entry
            if (d.name.Equals(""))
            {
                return;
            }
            // If we don't already have one then add this
            if (!skills.ContainsKey(name))
            {
                skills.Add(name, d);
                d.sets.Add(packID);
            }
            // If we do replace if this has higher priority
            else if (skills[name].priority < d.priority)
            {
                skills.Remove(name);
                skills.Add(name, d);
            }
            // items of the same priority belong to multiple packs
            else if (skills[name].priority == d.priority)
            {
                skills[name].sets.Add(packID);
            }
        }

        // Is this a "Item" entry?
        if (name.IndexOf(ItemData.type) == 0)
        {
            ItemData d = new ItemData(name, content, path);
            // Ignore invalid entry
            if (d.name.Equals(""))
            {
                return;
            }
            // If we don't already have one then add this
            if (!items.ContainsKey(name))
            {
                items.Add(name, d);
                d.sets.Add(packID);
            }
            // If we do replace if this has higher priority
            else if (items[name].priority < d.priority)
            {
                items.Remove(name);
                items.Add(name, d);
            }
            // items of the same priority belong to multiple packs
            else if (items[name].priority == d.priority)
            {
                items[name].sets.Add(packID);
            }
        }

        // Is this a "Monster" entry?
        if (name.IndexOf(MonsterData.type) == 0)
        {
            MonsterData d = new MonsterData(name, content, path);
            // Ignore invalid entry
            if (d.name.Equals(""))
            {
                return;
            }
            // Ignore monster activations
            if (name.IndexOf(ActivationData.type) != 0)
            {
                // If we don't already have one then add this
                if (!monsters.ContainsKey(name))
                {
                    monsters.Add(name, d);
                    d.sets.Add(packID);
                }
                // If we do replace if this has higher priority
                else if (monsters[name].priority < d.priority)
                {
                    monsters.Remove(name);
                    monsters.Add(name, d);
                }
                // items of the same priority belong to multiple packs
                else if (monsters[name].priority == d.priority)
                {
                    monsters[name].sets.Add(packID);
                }
            }
        }

        // Is this a "Activation" entry?
        if (name.IndexOf(ActivationData.type) == 0)
        {
            ActivationData d = new ActivationData(name, content, path);
            // Ignore invalid entry
            if (d.name.Equals(""))
            {
                return;
            }
            // If we don't already have one then add this
            if (!activations.ContainsKey(name))
            {
                activations.Add(name, d);
                d.sets.Add(packID);
            }
            // If we do replace if this has higher priority
            else if (activations[name].priority < d.priority)
            {
                activations.Remove(name);
                activations.Add(name, d);
            }
            // items of the same priority belong to multiple packs
            else if (activations[name].priority == d.priority)
            {
                activations[name].sets.Add(packID);
            }
        }

        // Is this a "Attack" entry?
        if (name.IndexOf(AttackData.type) == 0)
        {
            AttackData d = new AttackData(name, content, path);
            // Ignore invalid entry
            if (d.name.Equals(""))
            {
                return;
            }
            // If we don't already have one then add this
            if (!investigatorAttacks.ContainsKey(name))
            {
                investigatorAttacks.Add(name, d);
                d.sets.Add(packID);
            }
            // If we do replace if this has higher priority
            else if (investigatorAttacks[name].priority < d.priority)
            {
                investigatorAttacks.Remove(name);
                investigatorAttacks.Add(name, d);
            }
            // items of the same priority belong to multiple packs
            else if (investigatorAttacks[name].priority == d.priority)
            {
                investigatorAttacks[name].sets.Add(packID);
            }
        }

        // Is this a "Evade" entry?
        if (name.IndexOf(EvadeData.type) == 0)
        {
            EvadeData d = new EvadeData(name, content, path);
            // Ignore invalid entry
            if (d.name.Equals(""))
            {
                return;
            }
            // If we don't already have one then add this
            if (!investigatorEvades.ContainsKey(name))
            {
                investigatorEvades.Add(name, d);
                d.sets.Add(packID);
            }
            // If we do replace if this has higher priority
            else if (investigatorEvades[name].priority < d.priority)
            {
                investigatorEvades.Remove(name);
                investigatorEvades.Add(name, d);
            }
            // items of the same priority belong to multiple packs
            else if (investigatorEvades[name].priority == d.priority)
            {
                investigatorEvades[name].sets.Add(packID);
            }
        }

        // Is this a "Horror" entry?
        if (name.IndexOf(HorrorData.type) == 0)
        {
            HorrorData d = new HorrorData(name, content, path);
            // Ignore invalid entry
            if (d.name.Equals(""))
            {
                return;
            }
            // If we don't already have one then add this
            if (!horrorChecks.ContainsKey(name))
            {
                horrorChecks.Add(name, d);
                d.sets.Add(packID);
            }
            // If we do replace if this has higher priority
            else if (horrorChecks[name].priority < d.priority)
            {
                horrorChecks.Remove(name);
                horrorChecks.Add(name, d);
            }
            // items of the same priority belong to multiple packs
            else if (horrorChecks[name].priority == d.priority)
            {
                horrorChecks[name].sets.Add(packID);
            }
        }

        // Is this a "Token" entry?
        if (name.IndexOf(TokenData.type) == 0)
        {
            TokenData d = new TokenData(name, content, path);
            // Ignore invalid entry
            if (d.name.Equals(""))
            {
                return;
            }
            // If we don't already have one then add this
            if (!tokens.ContainsKey(name))
            {
                tokens.Add(name, d);
                d.sets.Add(packID);
            }
            // If we do replace if this has higher priority
            else if (tokens[name].priority < d.priority)
            {
                tokens.Remove(name);
                tokens.Add(name, d);
            }
            // items of the same priority belong to multiple packs
            else if (tokens[name].priority == d.priority)
            {
                tokens[name].sets.Add(packID);
            }
        }

        // Is this a "Peril" entry?
        if (name.IndexOf(PerilData.type) == 0)
        {
            PerilData d = new PerilData(name, content);
            // Ignore invalid entry
            if (d.sectionName.Equals(""))
            {
                return;
            }
            // If we don't already have one then add this
            if (!perils.ContainsKey(name))
            {
                perils.Add(name, d);
            }
            // If we do replace if this has higher priority
            else if (perils[name].priority < d.priority)
            {
                perils.Remove(name);
                perils.Add(name, d);
            }
        }

        // Is this a "Puzzle" entry?
        if (name.IndexOf(PuzzleData.type) == 0)
        {
            PuzzleData d = new PuzzleData(name, content, path);
            // Ignore invalid entry
            if (d.name.Equals(""))
            {
                return;
            }
            // If we don't already have one then add this
            if (!puzzles.ContainsKey(name))
            {
                puzzles.Add(name, d);
                d.sets.Add(packID);
            }
            // If we do replace if this has higher priority
            else if (puzzles[name].priority < d.priority)
            {
                puzzles.Remove(name);
                puzzles.Add(name, d);
            }
            // items of the same priority belong to multiple packs
            else if (puzzles[name].priority == d.priority)
            {
                puzzles[name].sets.Add(packID);
            }
        }

        // Is this a "Image" entry?
        if (name.IndexOf(ImageData.type) == 0)
        {
            ImageData d = new ImageData(name, content, path);
            // Ignore invalid entry
            if (d.name.Equals(""))
            {
                return;
            }
            // If we don't already have one then add this
            if (!images.ContainsKey(name))
            {
                images.Add(name, d);
                d.sets.Add(packID);
            }
            // If we do replace if this has higher priority
            else if (images[name].priority < d.priority)
            {
                images.Remove(name);
                images.Add(name, d);
            }
            // items of the same priority belong to multiple packs
            else if (images[name].priority == d.priority)
            {
                images[name].sets.Add(packID);
            }
        }

        // Is this a "Audio" entry?
        if (name.IndexOf(AudioData.type) == 0)
        {
            AudioData d = new AudioData(name, content, path);
            // Ignore invalid entry
            if (d.name.Equals(""))
            {
                return;
            }
            // If we don't already have one then add this
            if (!audio.ContainsKey(name))
            {
                audio.Add(name, d);
            }
            // If we do replace if this has higher priority
            else if (audio[name].priority < d.priority)
            {
                audio.Remove(name);
                audio.Add(name, d);
            }
        }
    }
Esempio n. 42
0
 void OnUpdateAudio(AudioClip tex, AudioData data)
 {
     m_log += "Audio: " + tex.name + "\n";
 }
Esempio n. 43
0
	void EncodingUpdate()
	{		
		if(Microphone.devices.Length != 0)
		{
			if(m_bRecording == false)
			{
				//if(Input.GetKeyDown(KeyCode.LeftAlt))
				{
					m_acVoiceInput = Microphone.Start(Microphone.devices[0], true, m_kiRecordTime, 44000);
					
					//start timer
					m_fRecordingTimer = 0.0f; 
					m_bRecording = true;
				}
			}			
			else if(m_bRecording)
			{
				m_fRecordingTimer += Time.deltaTime;
								
				if(m_fRecordingTimer >= (float)m_kiRecordTime)
				{
					Microphone.End(Microphone.devices[0]);
					
					// Calculate sound size (To the nearest frame size)
					int iAudioDataSize = m_acVoiceInput.samples * m_acVoiceInput.channels * sizeof(float);
					iAudioDataSize -= iAudioDataSize % m_iFrameSize;
									
					// Extract audio data through the bum
					float[] fAudioData = new float[iAudioDataSize / sizeof(float)];
					m_acVoiceInput.GetData(fAudioData, 0);
					
					// Convert to short
					short[] saAudioData = new short[fAudioData.Length];
			
					for (int i = 0; i < fAudioData.Length; ++i)
					{
						saAudioData[i] = (short)(fAudioData[i] * 32767.0f);
					}					
								
					AudioData voiceData = new AudioData();
					voiceData.iAudioDataSize = iAudioDataSize;
					voiceData.iFrequency = m_acVoiceInput.frequency;
					voiceData.saData = saAudioData;				
					
					m_bEncoding = true;
					
					m_EncodeThread = new Thread(new ParameterizedThreadStart(EncodeAudio));
					m_EncodeThread.Start((object)voiceData);
					
					m_bRecording = false;
				}
			}
		}		
		
		if(!m_EncodeThread.IsAlive && m_bEncoding)
		{
			m_bEncoding = false;
			CNetwork.Connection.TransmitMicrophoneAudio(s_AudioPacket);
			
			s_AudioPacket.Clear();
		}		
	}
Esempio n. 44
0
    private IEnumerator RecordingHandler()
    {
        m_Recording = Microphone.Start(null, true, m_RecordingBufferSize, m_RecordingHZ);
        Debug.Log("Initialising microphone");
        yield return(null);      // let m_RecordingRoutine get set..


        //If the recording doesn't initialise properly
        if (m_Recording == null)
        {
            //Stop recording
            StopRecording();
            //Break out of function
            yield break;
        }

        bool bFirstBlock = true;
        int  midPoint    = m_Recording.samples / 2;

        float[] samples = null;

        //While our recording routine is still running and the recording isn't null
        while (m_RecordingRoutine != 0 && m_Recording != null)
        {
            //Get the position to write to
            int writePos = Microphone.GetPosition(null);
            //If we are going to overload the samples array or the mic isn't recording anymore
            if (writePos > m_Recording.samples || !Microphone.IsRecording(null))
            {
                Log.Error("MicrophoneWidget", "Microphone disconnected.");

                //Stop recording
                StopRecording();
                yield break;
            }

            //Recording is done in two halves for some reason
            if ((bFirstBlock && writePos >= midPoint) ||
                (!bFirstBlock && writePos < midPoint))
            {
                // front block is recorded, make a RecordClip and pass it onto our callback.
                samples = new float[midPoint];
                m_Recording.GetData(samples, bFirstBlock ? 0 : midPoint);

                AudioData record = new AudioData();
                record.MaxLevel = Mathf.Max(samples);
                record.Clip     = AudioClip.Create("Recording", midPoint, m_Recording.channels, m_RecordingHZ, false);
                record.Clip.SetData(samples, 0);

                m_SpeechToText.OnListen(record);

                bFirstBlock = !bFirstBlock;
            }
            else
            {
                // calculate the number of samples remaining until we ready for a block of audio,
                // and wait that amount of time it will take to record.
                int   remaining     = bFirstBlock ? (midPoint - writePos) : (m_Recording.samples - writePos);
                float timeRemaining = (float)remaining / (float)m_RecordingHZ;

                yield return(new WaitForSeconds(timeRemaining));
            }
        }

        yield break;
    }
    private IEnumerator RecordingHandler()
    {
        Log.Debug("ExampleStreamingSplitSamples.RecordingHandler()", "devices: {0}", Microphone.devices);
        //  Start recording
        _recording = Microphone.Start(_microphoneID, true, _recordingBufferSize, _recordingHZ);
        yield return(null);

        if (_recording == null)
        {
            StopRecording();
            yield break;
        }

#if ENABLE_TIME_LOGGING
        //  Set a reference to now to check timing
        DateTime now = DateTime.Now;
#endif

        //  Current sample segment number
        int sampleSegmentNum = 0;

        //  Size of the sample segment in samples
        int sampleSegmentSize = _recording.samples / _sampleSegments;

        //  Init samples
        float[] samples = null;

        while (_recordingRoutine != 0 && _recording != null)
        {
            //  Get the mic position
            int microphonePosition = Microphone.GetPosition(_microphoneID);
            if (microphonePosition > _recording.samples || !Microphone.IsRecording(_microphoneID))
            {
                Log.Error("ExampleStreamingSplitSamples.RecordingHandler()", "Microphone disconnected.");

                StopRecording();
                yield break;
            }

            int sampleStart = sampleSegmentSize * sampleSegmentNum;
            int sampleEnd   = sampleSegmentSize * (sampleSegmentNum + 1);

#if ENABLE_DEBUGGING
            Log.Debug("ExampleStreamingSplitSamples.RecordinHandler", "microphonePosition: {0} | sampleStart: {1} | sampleEnd: {2} | sampleSegmentNum: {3}",
                      microphonePosition.ToString(),
                      sampleStart.ToString(),
                      sampleEnd.ToString(),
                      sampleSegmentNum.ToString());
#endif
            //If the write position is past the end of the sample segment or if write position is before the start of the sample segment
            while (microphonePosition > sampleEnd || microphonePosition < sampleStart)
            {
                //  Init samples
                samples = new float[sampleSegmentSize];
                //  Write data from recording into samples starting from the sampleSegmentStart
                _recording.GetData(samples, sampleStart);

                //  Create AudioData and use the samples we just created
                AudioData record = new AudioData();
                record.MaxLevel = Mathf.Max(Mathf.Abs(Mathf.Min(samples)), Mathf.Max(samples));
                record.Clip     = AudioClip.Create("Recording", sampleSegmentSize, _recording.channels, _recordingHZ, false);
                record.Clip.SetData(samples, 0);

                //  Send the newly created AudioData to the service
                _speechToText.OnListen(record);

                //  Iterate or reset sampleSegmentNum
                if (sampleSegmentNum < _sampleSegments - 1)
                {
                    sampleSegmentNum++;
#if ENABLE_DEBUGGING
                    Log.Debug("ExampleStreamingSplitSamples.RecordingHandler()", "Iterating sampleSegmentNum: {0}", sampleSegmentNum);
#endif
                }
                else
                {
                    sampleSegmentNum = 0;
#if ENABLE_DEBUGGING
                    Log.Debug("ExampleStreamingSplitSamples.RecordingHandler()", "Resetting sampleSegmentNum: {0}", sampleSegmentNum);
#endif
                }

#if ENABLE_TIME_LOGGING
                Log.Debug("ExampleStreamingSplitSamples.RecordingHandler", "Sending data - time since last transmission: {0} ms", Mathf.Floor((float)(DateTime.Now - now).TotalMilliseconds));
                now = DateTime.Now;
#endif
                sampleStart = sampleSegmentSize * sampleSegmentNum;
                sampleEnd   = sampleSegmentSize * (sampleSegmentNum + 1);
            }

            yield return(0);
        }

        yield break;
    }
        public void LoadFile(AudioData audioData, IFileFormat fileFormat, bool ClearPlaylist = true)
        {
            if (ClearPlaylist)
            {
                ResetAudioList();
            }

            AudioFileFormats.Add(fileFormat);

            //Load Channel Info
            AudioFile file = new AudioFile();

            file.Title = fileFormat.FileName;
            if (fileFormat is VGAdudioFile)
            {
                file.vgAdudioFile = (VGAdudioFile)fileFormat;
            }

            //Loop through each channel and set it's own
            var format = audioData.GetAllFormats().ToArray()[0];

            for (int c = 0; c < format.ChannelCount; c++)
            {
                using (var memWav = new MemoryStream())
                {
                    AudioChannel audioChannel = new AudioChannel();
                    audioChannel.Name = $"Channel [{c}]";
                    file.Channels.Add(audioChannel);

                    //Load data and write to stream
                    var audio  = format.GetChannels(c).ToPcm16();
                    var writer = new WaveWriter();
                    writer.WriteToStream(audio, memWav);
                    audioChannel.Data = memWav.ToArray();

                    memWav.Position = 0;

                    //Load the player
                    audioChannel.audioPlayer.Open(new MemoryStream(audioChannel.Data), "test.wav", activeDevice);

                    /*     OpenFileDialog openFileDialog = new OpenFileDialog();
                     *   if (openFileDialog.ShowDialog() == DialogResult.OK)
                     *   {
                     *       audioChannel.audioPlayer.Open(openFileDialog.FileName, activeDevice);
                     *   }*/


                    audioChannel.audioPlayer.PlaybackStopped += (s, args) =>
                    {
                        //WasapiOut uses SynchronizationContext.Post to raise the event
                        //There might be already a new WasapiOut-instance in the background when the async Post method brings the PlaybackStopped-Event to us.
                        if (audioChannel.audioPlayer.PlaybackState != PlaybackState.Stopped)
                        {
                        }
                    };
                }
            }

            audioListView.AddObject(file);

            if (audioListView.Items.Count != 0)
            {
                audioListView.SelectedIndex = 0;
            }
        }
 private static PcmFormat FilterSetup(AudioData from, List<FilterBase> filters)
 {
     var fmt = new PcmFormat(from.meta.channels, from.meta.sampleRate, from.meta.totalSamples);
     foreach (var f in filters) {
         fmt = f.Setup(fmt);
     }
     return fmt;
 }
Esempio n. 48
0
    public override void OnNewFrame(Game game, NewFrameEventArgs args)
    {
        if (game.assetsLoadProgress.value != 1)
        {
            return;
        }

        if (!wasLoaded)
        {
            wasLoaded = true;
            Preload(game);
        }

        // Load audio
        for (int i = 0; i < game.audio.soundsCount; i++)
        {
            Sound_ sound = game.audio.sounds[i];
            if (sound == null)
            {
                continue;
            }
            if (sound.audio != null)
            {
                continue;
            }

            AudioData data = GetAudioData(game, sound.name);
            if (game.platform.AudioDataLoaded(data))
            {
                sound.audio = game.platform.AudioCreate(data);
                game.platform.AudioPlay(sound.audio);
            }
        }

        // Update audio position
        for (int i = 0; i < game.audio.soundsCount; i++)
        {
            Sound_ sound = game.audio.sounds[i];
            if (sound == null)
            {
                continue;
            }
            if (sound.audio == null)
            {
                continue;
            }
            game.platform.AudioSetPosition(sound.audio, sound.x, sound.y, sound.z);
        }

        // Stop audio
        for (int i = 0; i < game.audio.soundsCount; i++)
        {
            Sound_ sound = game.audio.sounds[i];
            if (sound == null)
            {
                continue;
            }
            if (sound.audio == null)
            {
                continue;
            }
            if (sound.stop)
            {
                game.platform.AudioDelete(sound.audio);
                game.audio.sounds[i] = null;
            }
        }

        // Finish or loop audio
        for (int i = 0; i < game.audio.soundsCount; i++)
        {
            Sound_ sound = game.audio.sounds[i];
            if (sound == null)
            {
                continue;
            }
            if (sound.audio == null)
            {
                continue;
            }
            if (sound.loop)
            {
                if (game.platform.AudioFinished(sound.audio) && sound.loop)
                {
                    //game.platform.AudioPlay(sound.audio);
                    AudioData data = GetAudioData(game, sound.name);
                    if (game.platform.AudioDataLoaded(data))
                    {
                        sound.audio = game.platform.AudioCreate(data);
                        game.platform.AudioPlay(sound.audio);
                    }
                }
            }
            else
            {
                if (game.platform.AudioFinished(sound.audio))
                {
                    game.audio.sounds[i] = null;
                }
            }
        }
    }
        private static int WriteFlacFile(ref AudioData ad, string path)
        {
            int rv;
            var flac = new WWFlacRWCS.FlacRW();
            rv = flac.EncodeInit(ad.meta);
            if (rv < 0) {
                return rv;
            }

            rv = flac.EncodeSetPicture(ad.picture);
            if (rv < 0) {
                flac.EncodeEnd();
                return rv;
            }

            for (int ch=0; ch < ad.meta.channels; ++ch) {
                long lrv = flac.EncodeAddPcm(ch, ad.pcm[ch].data);
                if (lrv < 0) {
                    flac.EncodeEnd();
                    return (int)lrv;
                }
            }

            rv = flac.EncodeRun(path);
            if (rv < 0) {
                flac.EncodeEnd();
                return rv;
            }

            flac.EncodeEnd();
            return 0;
        }
Esempio n. 50
0
        public async Task SendChatAudioData(byte[] sampleData)
        {
            AudioData data = new AudioData(0, NextFrameId, Timestamp, sampleData);

            await SendAsync(data);
        }
Esempio n. 51
0
 // Use this for initialization
 void Start()
 {
     anim = gameObject.GetComponent <Animator>();
     AudioData.PlaySound(SoundHandle.Intro);
 }
Esempio n. 52
0
 public override void OnData(AudioData data)
 {
     throw new NotSupportedException("ChatAudio data on client side");
 }
Esempio n. 53
0
    private IEnumerator RecordingHandler()
    {
        //temp.text += " Recording handler called ";
        m_Recording = Microphone.Start(m_MicrophoneID, true, m_RecordingBufferSize, m_RecordingHZ);

        yield return(null);             // let m_RecordingRoutine get set..

        if (m_Recording == null)
        {
            //temp.text += " m_Recording is null ";
            StopRecording();
            yield break;
        }
        else
        {
            //temp.text += " mike is not null";
        }

        bool bFirstBlock = true;
        int  midPoint    = m_Recording.samples / 2;

        float[] samples = null;

        while (m_RecordingRoutine != 0 && m_Recording != null)
        {
            int writePos = Microphone.GetPosition(m_MicrophoneID);
            //temp.text += " writePos is " + writePos.ToString ();
            if (writePos > m_Recording.samples || !Microphone.IsRecording(m_MicrophoneID))
            {
                Log.Error("MicrophoneWidget", "Microphone disconnected.");
                temp.text += " Problem with the mike ";
                StopRecording();
                yield break;
            }

            if ((bFirstBlock && writePos >= midPoint) ||
                (!bFirstBlock && writePos < midPoint))
            {
                // front block is recorded, make a RecordClip and pass it onto our callback.
                samples = new float[midPoint];
                m_Recording.GetData(samples, bFirstBlock ? 0 : midPoint);
                //temp.text += " Passing to callback ";
                AudioData record = new AudioData();
                record.MaxLevel = Mathf.Max(samples);
                record.Clip     = AudioClip.Create("Recording", midPoint, m_Recording.channels, m_RecordingHZ, false);
                record.Clip.SetData(samples, 0);

                m_SpeechToText.OnListen(record);

                bFirstBlock = !bFirstBlock;
            }
            else
            {
                // calculate the number of samples remaining until we ready for a block of audio,
                // and wait that amount of time it will take to record.
                int   remaining     = bFirstBlock ? (midPoint - writePos) : (m_Recording.samples - writePos);
                float timeRemaining = (float)remaining / (float)m_RecordingHZ;
                //temp.text += " Waiting for audio sample to finish ";
                yield return(new WaitForSeconds(timeRemaining));
            }
        }

        yield break;
    }
Esempio n. 54
0
 /** 
     @brief Lock to access the internal storage of a specified format. The function will perform format conversion if unmatched. 
     @param[in]  access		The access mode.
     @param[in]  format		The requested smaple format.
     @param[out] data		The sample data storage, to be returned.
     @return PXCM_STATUS_NO_ERROR	Successful execution.
 */
 public pxcmStatus AcquireAccess(Access access, AudioFormat format, out AudioData data)
 {
     return AcquireAccess(access, format, 0, out data);
 }