Пример #1
0
        /// <summary>
        /// Initializes the connection string parameters of this <see cref="WavInputAdapter"/>.
        /// </summary>
        public override void Initialize()
        {
            base.Initialize();

            Dictionary <string, string> settings = Settings;
            string setting;

            if (settings.TryGetValue("recoveryDelay", out setting))
            {
                RecoveryDelay = double.Parse(setting);
            }
            else
            {
                RecoveryDelay = DefaultRecoveryDelay;
            }

            if (!settings.TryGetValue("wavFileName", out setting))
            {
                throw new ArgumentException("wavFileName is missing from settings - Example: wavFileName=Bohemian Rhapsody.wav");
            }

            WavFileName = setting;

            if (settings.TryGetValue("memoryCache", out setting))
            {
                MemoryCache = setting.ParseBoolean();
            }

            // Attempt to parse WAV file info during initialization, if this fails - no need to load adapter
            WaveFile fileInfo = WaveFile.Load(WavFileName, false);

            m_channels    = fileInfo.Channels;
            m_sampleRate  = fileInfo.SampleRate;
            m_audioLength = fileInfo.AudioLength;

            if (m_channels > OutputMeasurements.Length)
            {
                throw new ArgumentException($"Not enough output measurements ({OutputMeasurements.Length}) defined for the number of channels in the WAV file ({m_channels})");
            }

            OnStatusMessage(MessageLevel.Info, $"Ready to play \"{Path.GetFileName(WavFileName)}\" with {m_channels} channels...");
        }
Пример #2
0
        static void Main(string[] args)
        {
            //double[] freqs = get_freqs(fmin, get_freq_num(fmin, fmax, fratio), fratio);
            //Complex[,] kernel = calcKernel_matrix(freqs);
            //double[,] kernel_pow = new double[kernel.GetLength(0), kernel.GetLength(1)];
            //for (int i = 0; i < kernel.GetLength(0); i++)
            //{
            //    for (int j = 0; j < kernel.GetLength(1); j++)
            //    {
            //        kernel_pow[i, j] = kernel[i, j].Magnitude;
            //    }
            //}
            //Tuple<double[][], int> tu = WaveFile.Load(@"C:\Users\優\Desktop\音素材\mix3.wav");
            Tuple <double[][], int> tu = WaveFile.Load(@"C:\Users\優\Desktop\音素材\mix3v3.wav");

            double[] wavdata = tu.Item1[0];
            fs = tu.Item2;
            double[,] output = constantQ_transformP(wavdata);

            CsvFileIO.CsvFileIO.WriteData("output.csv", output);
        }
Пример #3
0
        /// <summary>
        /// Attempts to open the file to start getting wave data.
        /// </summary>
        protected override void AttemptConnection()
        {
            WaveFile fileInfo = WaveFile.Load(WavFileName, false);

            m_channels    = fileInfo.Channels;
            m_sampleRate  = fileInfo.SampleRate;
            m_numSamples  = fileInfo.DataChunk.ChunkSize / fileInfo.BlockAlignment;
            m_audioLength = fileInfo.AudioLength;

            m_data      = WaveDataReader.FromFile(WavFileName);
            m_dataIndex = 0;

            //if (file.Channels != OutputMeasurements.Length)
            //    throw new ArgumentException(string.Format("The number of channels in the WAV file must match the number of output measurements. Channels: {0}, Measurements: {1}", file.Channels, OutputMeasurements.Length));

            m_startTime = DateTime.UtcNow.Ticks;

            Thread t = new Thread(ProcessMeasurements);

            t.IsBackground = true;
            t.Start();
        }
Пример #4
0
        static int Main(string[] args)
        {
            // System settings
            ConfigurationFile configFile = ConfigurationFile.Current;
            CategorizedSettingsElementCollection systemSettings = configFile.Settings["systemSettings"];

            systemSettings.Add("NodeID", Guid.NewGuid().ToString(), "Unique Node ID");
            Guid   nodeID            = systemSettings["NodeID"].ValueAs <Guid>();
            string connectionString  = systemSettings["ConnectionString"].Value;
            string nodeIDQueryString = null;
            string parameterizedQuery;
            int    protocolID, signalTypeID;

            // Define guid with query string delimiters according to database needs
            Dictionary <string, string> settings = connectionString.ParseKeyValuePairs();
            string setting;

            if (settings.TryGetValue("Provider", out setting))
            {
                // Check if provider is for Access since it uses braces as Guid delimiters
                if (setting.StartsWith("Microsoft.Jet.OLEDB", StringComparison.OrdinalIgnoreCase))
                {
                    nodeIDQueryString = "{" + nodeID + "}";
                }
            }

            if (string.IsNullOrWhiteSpace(nodeIDQueryString))
            {
                nodeIDQueryString = "'" + nodeID + "'";
            }

            using (AdoDataConnection database = new AdoDataConnection("systemSettings"))
            {
                IDbConnection connection = database.Connection;

                if (Convert.ToInt32(connection.ExecuteScalar("SELECT COUNT(*) FROM Protocol WHERE Acronym='WAV'")) == 0)
                {
                    if (database.IsSQLServer || database.IsJetEngine)
                    {
                        connection.ExecuteNonQuery("INSERT INTO Protocol(Acronym, Name, [Type], Category, AssemblyName, TypeName) VALUES('WAV', 'Wave Form Input Adapter', 'Frame', 'Audio', 'WavInputAdapter.dll', 'WavInputAdapter.WavInputAdapter')");
                    }
                    else
                    {
                        connection.ExecuteNonQuery("INSERT INTO Protocol(Acronym, Name, Type, Category, AssemblyName, TypeName) VALUES('WAV', 'Wave Form Input Adapter', 'Frame', 'Audio', 'WavInputAdapter.dll', 'WavInputAdapter.WavInputAdapter')");
                    }
                }

                protocolID = Convert.ToInt32(connection.ExecuteScalar("SELECT ID FROM Protocol WHERE Acronym='WAV'"));

                // Typically these values should be defined as analogs, however, we use a voltage magnitude signal type
                // since these types of values can be better graphed with auto-scaling in the visualization tools
                signalTypeID = Convert.ToInt32(connection.ExecuteScalar("SELECT ID FROM SignalType WHERE Acronym='VPHM'"));
                //signalTypeID = Convert.ToInt32(connection.ExecuteScalar("SELECT ID FROM SignalType WHERE Acronym='ALOG'"));

                string pathRoot   = FilePath.GetDirectoryName((args.Length > 0) ? args[0] : systemSettings["MusicDirectory"].Value);
                string sourcePath = Path.Combine(pathRoot, "*" + Path.DirectorySeparatorChar + "*.wav");

                foreach (string sourceFileName in FilePath.GetFileList(sourcePath))
                {
                    WaveFile sourceWave;
                    string   fileName     = FilePath.GetFileName(sourceFileName);
                    char[]   invalidChars = new[] { '\'', '[', ']', '(', ')', ',', '-', '.' };

                    Console.WriteLine("Loading metadata for \"{0}\"...\r\n", fileName);
                    sourceWave = WaveFile.Load(sourceFileName, false);

                    fileName = FilePath.GetFileNameWithoutExtension(fileName).RemoveDuplicateWhiteSpace().RemoveCharacters(invalidChars.Contains).Trim();
                    string acronym = fileName.Replace(' ', '_').ToUpper() + "_" + (int)(sourceWave.SampleRate / SI.Kilo) + "KHZ";
                    string name    = GenerateSongName(sourceWave, fileName);

                    Console.WriteLine("   Acronym = {0}", acronym);
                    Console.WriteLine("      Name = {0}", name);
                    Console.WriteLine("");

                    // Check to see if device exists
                    if (Convert.ToInt32(connection.ExecuteScalar(database.ParameterizedQueryString("SELECT COUNT(*) FROM Device WHERE Acronym = {0}", "acronym"), acronym)) == 0)
                    {
                        parameterizedQuery = database.ParameterizedQueryString("INSERT INTO Device(NodeID, Acronym, Name, ProtocolID, FramesPerSecond, " +
                                                                               "MeasurementReportingInterval, ConnectionString, Enabled) VALUES(" + nodeIDQueryString + ", {0}, {1}, {2}, {3}, {4}, {5}, {6})",
                                                                               "acronym", "name", "protocolID", "framesPerSecond", "measurementReportingInterval",
                                                                               "connectionString", "enabled");

                        // Insert new device record
                        connection.ExecuteNonQuery(parameterizedQuery, acronym, name, protocolID, sourceWave.SampleRate, 1000000, string.Format("wavFileName={0}; connectOnDemand=true; outputSourceIDs={1}", FilePath.GetAbsolutePath(sourceFileName), acronym), database.Bool(true));
                        int    deviceID = Convert.ToInt32(connection.ExecuteScalar(database.ParameterizedQueryString("SELECT ID FROM Device WHERE Acronym = {0}", "acronym"), acronym));
                        string pointTag;

                        // Add a measurement for each defined wave channel
                        for (int i = 0; i < sourceWave.Channels; i++)
                        {
                            int index = i + 1;
                            pointTag = acronym + ":WAVA" + index;

                            parameterizedQuery = database.ParameterizedQueryString("INSERT INTO Measurement(DeviceID, PointTag, SignalTypeID, SignalReference, Description, " +
                                                                                   "Enabled) VALUES({0}, {1}, {2}, {3}, {4}, {5})", "deviceID", "pointTag", "signalTypeID", "signalReference", "description", "enabled");

                            // Insert new measurement record
                            connection.ExecuteNonQuery(parameterizedQuery, (object)deviceID, pointTag, signalTypeID, acronym + "-AV" + index, name + " - channel " + index, database.Bool(true));
                            //index = Convert.ToInt32(connection.ExecuteScalar(database.ParameterizedQueryString("SELECT PointID FROM Measurement WHERE PointTag = {0}", "pointTag"), pointTag));
                        }

                        // Disable all non analog measurements that may be associated with this device
                        connection.ExecuteNonQuery(database.ParameterizedQueryString("UPDATE Measurement SET Enabled = {0} WHERE DeviceID = {1} AND SignalTypeID <> {2}", "enabled", "deviceID", "signalTypeID"), database.Bool(false), deviceID, signalTypeID);
                    }
                }
            }

            return(0);
        }
Пример #5
0
 private static AudioClip LoadAudio(byte[] data)
 {
     //TODO handling for things that aren't WAV
     return(WaveFile.Load(data, false).ToAudioClip());
 }