private Stream DecodeFLAC(SndAssetBankEntry entry)
        {
            var wavOutput = new MemoryStream();

            try
            {
                using (var input = new MemoryStream(entry.Data.Get()))
                    using (var wavWriter = new WavWriter(wavOutput))
                        using (var reader = new FlacReader(input, wavWriter))
                        {
                            reader.SampleProcessed += (s, args) =>
                                                      BeginInvoke(new MethodInvoker(() =>
                                                                                    currentTimetoolStripLabel.Text = "Please wait, decoding audio... " + args.Progress + "%"));
                            reader.Process();
                        }
                wavOutput.Position = 0;
                return(wavOutput);
            }
            catch (Exception e)
            {
                // Ignore exception for headerless FLAC
                if (e.Message.IndexOf("until eof", StringComparison.InvariantCulture) != -1 &&
                    entry.Data is AudioDataStream && ((AudioDataStream)entry.Data).Stream is HeaderlessFLACStream)
                {
                    wavOutput.Position = 0;
                    return(wavOutput);
                }
                return(null);
            }
        }
        public FlacReader(Stream input, WavWriter output)
        {
            if (output == null)
            {
                throw new ArgumentNullException("output");
            }

            stream = input;
            writer = output;

            context = _flacStreamDecoderNew();

            if (context == IntPtr.Zero)
            {
                throw new ApplicationException("FLAC: Could not initialize stream decoder!");
            }

            write    = Write;
            metadata = Metadata;
            error    = Error;
            read     = Read;
            seek     = Seek;
            tell     = Tell;
            length   = Length;
            eof      = Eof;

            if (_flacStreamDecoderInitStream(context, read, seek, tell, length, eof, write, metadata,
                                             error, IntPtr.Zero) != 0)
            {
                throw new ApplicationException("FLAC: Could not open stream for reading!");
            }
        }
Example #3
0
        private static void Main(string[] args)
        {
            string fileName;
            if (args.Length == 1)
            {
                fileName = args[0];
            }
            else
            {
                var dialog = new OpenFileDialog {Title = "Select an audio file (wma, mp3, ...etc.) or video file..."};
                if (dialog.ShowDialog() != DialogResult.OK)
                    return;
                fileName = dialog.FileName;
            }

            var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            var audioDecoder = new AudioDecoder(stream);

            var outputWavStream = new FileStream("output.wav", FileMode.Create, FileAccess.Write);

            var wavWriter = new WavWriter(outputWavStream);

            // Write the WAV file
            wavWriter.Begin(audioDecoder.WaveFormat);

            // Decode the samples from the input file and output PCM raw data to the WAV stream.
            wavWriter.AppendData(audioDecoder.GetSamples());

            // Close the wav writer.
            wavWriter.End();

            audioDecoder.Dispose();
            outputWavStream.Close();
            stream.Close();
        }
Example #4
0
        private bool WriteWavFile(PcmData pcmData, string path)
        {
            using (BinaryWriter bw = new BinaryWriter(
                       File.Open(path, FileMode.Create, FileAccess.Write, FileShare.Write))) {
                var wavW = new WavWriter();
                wavW.Set(pcmData.NumChannels, pcmData.BitsPerSample, pcmData.ValidBitsPerSample, pcmData.SampleRate,
                         pcmData.SampleValueRepresentationType, pcmData.NumFrames, pcmData.GetSampleArray());
                wavW.Write(bw);
            }

            return(true);
        }
Example #5
0
        public void Header()
        {
            WavHeader header = GetHeader();

            using (var memory = new MemoryStream())
            {
                var writer = new WavWriter(memory, header);
                writer.ToString();                  // we just need it to process header

                Assert.AreEqual(WavHeader.Size + WavChunkHeader.Size, memory.Position);
            }
        }
        private void WriteNoise(int[] noiseSignal, int ml)
        {
            DigitalAudio digitalAudio = new DigitalAudio();

            digitalAudio.AddChannel(noiseSignal);
            digitalAudio.SampleRate = 44100;
            digitalAudio.SignificantBitsPerSample = 16;
            var stream = File.Create("nr_" + NoiseRate + "ml_" + ml + ".wav");

            using (WavWriter writer = new WavWriter(stream))
                writer.WriteWavDefault(digitalAudio);
        }
Example #7
0
        private static void processFile(string text, string outFilePattern, ConfigurationManager configurationManager)
        {
            FrontEnd            frontEnd            = (FrontEnd)configurationManager.lookup("endpointer");
            AudioFileDataSource audioFileDataSource = (AudioFileDataSource)configurationManager.lookup("audioFileDataSource");

            [email protected](text);
            audioFileDataSource.setAudioFile(new File(text), null);
            WavWriter wavWriter = (WavWriter)configurationManager.lookup("wavWriter");

            wavWriter.setOutFilePattern(outFilePattern);
            frontEnd.initialize();
            while (frontEnd.getData() != null)
            {
            }
        }
Example #8
0
        private void SaveSound()
        {
            SaveFileDialog sfd = new SaveFileDialog
            {
                Filter           = "Sound file ( *.wav)| *.wav",
                AddExtension     = true,
                OverwritePrompt  = true,
                RestoreDirectory = true,
                FileName         = Name
            };

            if (sfd.ShowDialog() == true)
            {
                WavWriter.WriteData(sfd.FileName, WavData);
            }
        }
Example #9
0
        public static Stream DecodeHeaderlessWav(SndAssetBankEntry entry)
        {
            var data = entry.Data.Get();
            var ms   = new MemoryStream();

            // Write the header.
            using (var writer = new WavWriter(ms))
            {
                writer.WriteHeader(48000, 16, entry.ChannelCount);
                writer.AudioDataBytes = data.Length;
            }

            // Write the data.
            ms.Write(data, 0, data.Length);
            data = ms.ToArray();

            ms.Position = 0;
            return(ms);
        }
Example #10
0
        private static void RenderVgmToWav(string fileName, VgmHeader header, IEnumerable <VgmCommand> commands)
        {
            var wave         = CreateWave(header.GetSamplesCount());
            var sampleNumber = 0;
            var amplitude    = 15000f;
            var values       = Renderer.Render(commands);

            foreach (var value in values)
            {
                wave.Samples[sampleNumber++] = (short)(amplitude * value);
            }

            using (var outputStream = new FileStream(fileName + ".wav", FileMode.Create))
            {
                using (var writer = new BinaryWriter(outputStream))
                {
                    WavWriter.Write(wave, writer);
                }
            }
        }
Example #11
0
        public bool RunDffToWav(string fromPath, string toPath)
        {
            DsdiffReader dr = new DsdiffReader();
            PcmData      pcm;

            using (BinaryReader br = new BinaryReader(File.Open(fromPath, FileMode.Open))) {
                using (BinaryWriter bw = new BinaryWriter(File.Open(toPath, FileMode.Create))) {
                    var result = dr.ReadStreamBegin(br, out pcm);
                    if (result != DsdiffReader.ResultType.Success)
                    {
                        Console.WriteLine("Error: {0}", result);
                        return(false);
                    }

                    long numBytes = pcm.NumFrames * pcm.BitsPerFrame;
                    WavWriter.WriteRF64Header(bw, pcm.NumChannels, pcm.BitsPerSample, pcm.SampleRate, pcm.NumFrames);

                    bool bContinue = true;
                    do
                    {
                        var data = dr.ReadStreamReadOne(br, 1024 * 1024);
                        if (data == null || data.Length == 0)
                        {
                            bContinue = false;
                        }

                        bw.Write(data);
                    } while (bContinue);

                    if ((numBytes & 1) == 1)
                    {
                        byte pad = 0;
                        bw.Write(pad);
                    }

                    dr.ReadStreamEnd();
                }
            }

            return(true);
        }
Example #12
0
        public async Task FlushUpdatesSizes()
        {
            WavHeader header = GetHeader();

            using (var memory = new MemoryStream())
            {
                var writer = new WavWriter(memory, header);

                var data = new byte[12];
                await writer.Write(data, 0, data.Length);

                writer.Flush();

                // read data, that has been written above
                memory.Position = 0;
                var reader = new WavReader(memory);
                var h      = reader.ReadChunkHeader();

                Assert.AreEqual(WavHeader.Size + WavChunkHeader.Size - 8 + data.Length, reader.Header.FileSize);
                Assert.AreEqual(data.Length, h.ChunkLength);
            }
        }
Example #13
0
        public async Task Copy()
        {
            var input = GetType().Assembly.GetManifestResourceStream("WavSplitterTest.Resources.source.wav");

            var path   = Path.Combine(TestContext.CurrentContext.TestDirectory, "copy.wav");
            var output = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write);

            var reader = new WavReader(input);
            var writer = new WavWriter(output, reader.Header);

            var fllr = reader.ReadChunkHeader(skipFllr: false);

            writer.SetCurrentChunkId(fllr.ChunkId);

            var bytes = new byte[fllr.ChunkLength];
            await reader.ReadDataChunk(bytes);

            await writer.Write(bytes, 0, bytes.Length);

            writer.Flush();

            Assert.AreEqual(input.Position, output.Position, "First chunk test");
            Assert.AreEqual(fllr.ChunkLength, writer.LastDataChunkLength);

            var data = reader.ReadChunkHeader(skipFllr: false);

            bytes = new byte[data.ChunkLength];
            await reader.ReadDataChunk(bytes);

            writer.StartNewDataChunk(data.ChunkId);
            await writer.Write(bytes, 0, bytes.Length);

            writer.Flush();

            Assert.IsFalse(reader.HasMore);
            Assert.AreEqual(input.Position, output.Position, "Second chunk test");
            Assert.AreEqual(data.ChunkLength, writer.LastDataChunkLength);
        }
Example #14
0
        public static void DecodeAudioToWav(string fileName)
        {
            fileName = "Assets/sounds/" + fileName;
            var stream       = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            var audioDecoder = new AudioDecoder(stream);

            var outputWavStream = new FileStream(fileName + ".wav", FileMode.Create, FileAccess.Write);

            var wavWriter = new WavWriter(outputWavStream);

            // Write the WAV file
            wavWriter.Begin(audioDecoder.WaveFormat);

            // Decode the samples from the input file and output PCM raw data to the WAV stream.
            wavWriter.AppendData(audioDecoder.GetSamples());

            // Close the wav writer.
            wavWriter.End();

            audioDecoder.Dispose();
            outputWavStream.Close();
            stream.Close();
        }
Example #15
0
        public void WavReaderReadsSamplesAccuratelytMultiChannelRandom(int bitDepth, int sampleRate, int channels)
        {
            const int testSampleCount = 500;

            // generate some fake data
            // generates a repeating saw wave of 0, 1, 0 -1
            var a = new double[testSampleCount].Select((v, i) => i % 4 == 3 ? -1.0 : i % 2).ToArray();

            // random data
            var random = TestHelpers.Random.GetRandom();

            double Clamp(double value)
            {
                return(Math.Max(Math.Min(value, 1.0), -1.0));
            }

            var b = new double[testSampleCount].Select(v => Clamp(random.NextDouble() * 2.0 - 1.0)).ToArray();

            // now write the file
            var temp    = PathHelper.GetTempFile("wav");
            var signals = new double[channels][];

            switch (channels)
            {
            case 4:
                signals[0] = a;
                signals[1] = b;
                signals[2] = b;
                signals[3] = a;
                break;

            case 2:
                signals[0] = a;
                signals[1] = b;
                break;

            case 1:
                var c = new double[a.Length + b.Length];
                a.CopyTo(c, 0);
                b.CopyTo(c, a.Length);
                signals[0] = c;
                break;

            default:
                throw new InvalidOperationException();
            }

            WavWriter.WriteWavFileViaFfmpeg(temp, signals, bitDepth, sampleRate);

            // verify file written correctly
            var info = this.audioUtility.Info(temp);

            var reader = new WavReader(temp);

            // verify the writer wrote (the header) correctly
            TestHelper.WavReaderAssertions(reader, new AudioUtilityInfo()
            {
                BitsPerSample = bitDepth,
                BitsPerSecond = channels * bitDepth * sampleRate,
                ChannelCount  = channels,
                Duration      = TimeSpan.FromSeconds(testSampleCount * (channels == 1 ? 2 : 1) / (double)sampleRate),
                MediaType     = MediaTypes.MediaTypeWav1,
                SampleRate    = sampleRate,
            });

            // verify the wav reader read correctly
            TestHelper.WavReaderAssertions(reader, info);

            // our ability to faithfully convert numbers depends on the bit depth of the signal
            double epilson = reader.Epsilon;

            for (int c = 0; c < channels; c++)
            {
                double[] expected;
                double   e;
                switch (c)
                {
                case 0 when channels == 1:
                    var ex = new double[a.Length + b.Length];
                    a.CopyTo(ex, 0);
                    b.CopyTo(ex, a.Length);
                    expected = ex;

                    e = epilson;
                    break;

                case 0:
                    expected = a;
                    e        = 0.0;
                    break;

                case 1:
                    expected = b;
                    e        = epilson;
                    break;

                case 2:
                    expected = b;
                    e        = epilson;
                    break;

                case 3:
                    expected = a;
                    e        = 0.0;
                    break;

                default:
                    throw new InvalidOperationException();
                }

                var mono = reader.GetChannel(c);
                Assert.AreEqual(expected.Length, mono.Length);

                for (int i = 0; i < a.Length; i++)
                {
                    Assert.AreEqual(expected[i], mono[i], epilson, $"failed at index {i} channel {c}");
                }
            }
        }
        public void Code()
        {
            OutputLogs logs = OutputLogs.Instance();

            switch (action)
            {
            case NavigationCodes.Extract:
                OutputLogs.Instance().AddLog(new Message(MessageType.Info, "Extracting started...", method.ToString()));
                try
                {
                    var bytes = method.Extract(cover);
                    if (bytes == null)
                    {
                        throw new ApplicationException("No embedded message found.");
                    }
                    Message = Encoding.ASCII.GetString(bytes);
                    string goodMsg = "Embedded message successfuly extracted.";
                    logs.AddLog(new Message(MessageType.Info, goodMsg, method.ToString()));
                }
                catch (ApplicationException ex)
                {
                    logs.AddLog(new Message(MessageType.Error, ex.Message, method.ToString()));
                }
                break;

            case NavigationCodes.Embed:
                logs.AddLog(new Message(MessageType.Info, "Embedding started...", method.ToString()));
                try
                {
                    int[] signal = null;
                    if (GetStatistics)
                    {
                        signal = (int[])cover.GetSignal().Clone();
                    }
                    var data = Encoding.ASCII.GetBytes(Message);
                    method.Embed(cover, data);
                    logs.AddLog(new Message(MessageType.Info, "Message successfuly embeded.", method.ToString()));
                    SaveFileDialogService.DefaultExt      = "wav";
                    SaveFileDialogService.DefaultFileName = "StegoAudio";
                    if (SaveFileDialogService.ShowDialog())
                    {
                        using (var stream = new WavWriter(SaveFileDialogService.OpenFile()))
                            stream.WriteWavDefault(cover);
                        logs.AddLog(new Message(MessageType.Info, "File was succesfuly saved.", "WavWriter"));
                    }
                    if (GetStatistics)
                    {
                        var stegosignal = cover.GetSignal();
                        var service     = DocumentManagerService;
                        var doc         = service.CreateDocument("Statistics", new StatisticsViewModel(signal, stegosignal));
                        doc.Show();
                    }
                }
                catch (ApplicationException ex)
                {
                    logs.AddLog(new Message(MessageType.Error, ex.Message, method.ToString()));
                }
                break;

            default:
                logs.AddLog(new Message(MessageType.Error, "Internal error", method.ToString()));
                break;
            }
        }
        /// <summary>
        /// Normalize a file using EBU R128 standard
        /// </summary>
        /// <param name="inputFile">Input filename</param>
        /// <param name="outputFile">Output filename</param>
        public static void Normalize(string inputFile, string outputFile)
        {
            try
            {
                // Decode
                WavReader wavReader = null;
                if (Path.GetExtension(inputFile).ToLower() == ".wav")
                {
                    try
                    {
                        using (FileStream fileStream = new FileStream(inputFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            wavReader = new WavReader(fileStream, Encoding.Default);
                        }
                    }
                    catch (WavReader.FormatNotSupportedException ex)
                    {
                        wavReader = null;
                    }
                }
                if (wavReader == null)
                {
                    Stream ffStream;
                    try
                    {
                        ffStream = FFmpegWavPiper.GetS32WavStream(inputFile, FFmpegLogReceived);
                    }
                    catch (FFmpegWavPiper.FFmepgNotFoundException)
                    {
                        Console.WriteLine("FFmpeg not found. Non-wav files require ffmpeg for decoding support. File skipped.");
                        return;
                    }
                    wavReader = new WavReader(ffStream, Encoding.UTF8);
                }

                WavReader.FmtChunk fmt    = (WavReader.FmtChunk)wavReader.Riff.Chunks["fmt "];
                double[][]         buffer = wavReader.GetSampleData();

                // Normalize
                buffer = Normalize(buffer, fmt.SampleRate);

                // Encode
                WavWriter wavWriter = new WavWriter(buffer, fmt.SampleRate, 0x0003, 32, null, Encoding.Default);
                if (wavReader.Riff.Chunks.ContainsKey("LIST"))
                {
                    wavWriter.Infos = ((WavReader.ListChunk)wavReader.Riff.Chunks["LIST"]).Data;
                }
                else
                {
                    wavWriter.Infos = new System.Collections.Generic.SortedDictionary <string, string>();
                }
                wavWriter.Infos["ISFT"] = "Build-in codec";
                wavWriter.Infos["ITCH"] = "R128Normalization";
                wavWriter.Save(outputFile);
                Console.WriteLine("File saved: {0}", Path.GetFileNameWithoutExtension(outputFile));
            }
            catch (Exception ex)
            {
                Console.WriteLine("An exception has occurred : ");
                Console.WriteLine($"{ex.GetType()} : {ex.Message}");
                Console.WriteLine(ex.StackTrace);
            }
            GC.Collect();
        }
Example #18
0
 public void Close()
 {
     m_Writer = null;
 }
Example #19
0
 public void Open(string filename)
 {
     m_Writer = new WavWriter();
       m_Writer.WriteFactChunk = false;
       m_Filename = filename;
 }
Example #20
0
        private async void btnSharpDXMP3toWav_Click(object sender, RoutedEventArgs e)
        {
            var LocalFolder = await ApplicationData.Current.LocalFolder
                                             .CreateFolderAsync(@"Assets", CreationCollisionOption.OpenIfExists);
            var folder = await StorageFolder.GetFolderFromPathAsync(Windows.ApplicationModel.Package.Current.InstalledLocation.Path + @"\Assets");
            var fileMP3 = await folder.GetFileAsync(string.Format("{0}", "Clk_1Sec1_10s_70s_150s_210s_270s.mp3"));
            var fileWav = await LocalFolder.CreateFileAsync(string.Format("{0}", "SharpDx.wav"), CreationCollisionOption.ReplaceExisting);


            using (Stream streamMP3 = await fileMP3.OpenStreamForReadAsync())
            {
                using (Stream streamWav = await fileWav.OpenStreamForWriteAsync())
                {
                    AudioDecoder audioDecoder = new AudioDecoder(streamMP3);
                    WavWriter wavWriter = new WavWriter(streamWav);
                    

                    wavWriter.Begin(audioDecoder.WaveFormat);

                    // Decode the samples from the input file and output PCM raw data to the WAV stream.
                    wavWriter.AppendData(audioDecoder.GetSamples());

                    // Close the wav writer.
                    wavWriter.End();

                    audioDecoder.Dispose();
                }
            }

            this.me1.Source = new Uri(string.Format("ms-appdata:///local/Assets/{0}", "SharpDx.wav"));

            //Stream streamMP3 = await fileMP3.OpenStreamForReadAsync();
            //Stream streamWav = await fileWav.OpenStreamForWriteAsync();
            //AudioDecoder audioDecoder = new AudioDecoder(streamMP3);
            //WavWriter wavWriter = new WavWriter(streamWav);

            //wavWriter.Begin(audioDecoder.WaveFormat);

            //// Decode the samples from the input file and output PCM raw data to the WAV stream.
            //wavWriter.AppendData(audioDecoder.GetSamples());

            //// Close the wav writer.
            //wavWriter.End();

            //audioDecoder.Dispose();
            //await streamWav.FlushAsync();
        }
 public FlacReader(string input, WavWriter output)
     : this(File.OpenRead(input), output)
 {
 }
Example #22
0
 public MyWavWriter(string path, int bitsPerSample, int channelCount, int sampleRate)
 {
     Path        = path;
     _wr         = new WavWriter(path, bitsPerSample, channelCount, sampleRate);
     _blockAlign = bitsPerSample / 8 * channelCount;
 }
Example #23
0
        public bool RunDsfToWav(string fromPath, string toPath)
        {
            DsfReader dr = new DsfReader();
            PcmData   pcm;

            using (BinaryReader br = new BinaryReader(File.Open(fromPath, FileMode.Open))) {
                using (BinaryWriter bw = new BinaryWriter(File.Open(toPath, FileMode.Create))) {
                    var result = dr.ReadStreamBegin(br, out pcm);
                    if (result != DsfReader.ResultType.Success)
                    {
                        Console.WriteLine("Error: {0}", result);
                        return(false);
                    }

                    if (mOneBitWav)
                    {
                        pcm.SampleDataType = PcmDataLib.PcmData.DataType.PCM;
                        pcm.SetFormat(
                            pcm.NumChannels,
                            16,
                            16,
                            dr.SampleRate,
                            PcmDataLib.PcmData.ValueRepresentationType.SInt,
                            dr.SampleCount);
                    }

                    long numBytes = pcm.NumFrames * pcm.BitsPerFrame;
                    WavWriter.WriteRF64Header(bw, pcm.NumChannels, pcm.BitsPerSample, pcm.SampleRate, pcm.NumFrames);

                    bool bContinue = true;
                    do
                    {
                        var data = dr.ReadStreamReadOne(br, 1024 * 1024);
                        if (data == null || data.Length == 0)
                        {
                            bContinue = false;
                        }

                        if (mOneBitWav)
                        {
                            // 24bitPCMのDoPフレームが出てくるが、1bitずつ、16bit値に伸ばして出力。
                            // DoPのデータのSDMはビッグエンディアンビットオーダーで15ビット目→0ビット目に入っている。
                            int readPos = 0;
                            for (int i = 0; i < data.Length / 3 / pcm.NumChannels; ++i)
                            {
                                for (int ch = 0; ch < pcm.NumChannels; ++ch)
                                {
                                    ushort v = (ushort)((data[readPos + 1] << 8) + (data[readPos + 0] << 0));
                                    for (int bitPos = 15; 0 <= bitPos; --bitPos)
                                    {
                                        int b = 1 & (v >> bitPos);
                                        if (b == 1)
                                        {
                                            short writePcm = +32767;
                                            bw.Write(writePcm);
                                        }
                                        else
                                        {
                                            short writePcm = -32767;
                                            bw.Write(writePcm);
                                        }
                                    }
                                    readPos += 3;
                                }
                            }
                        }
                        else
                        {
                            // DoP WAVデータを書き込む。
                            bw.Write(data);
                        }
                    } while (bContinue);

                    if ((numBytes & 1) == 1)
                    {
                        byte pad = 0;
                        bw.Write(pad);
                    }

                    dr.ReadStreamEnd();
                }
            }

            return(true);
        }
Example #24
0
        public void TestAnalyzeSr64000Recording()
        {
            int    sampleRate = 64000;
            double duration   = 420; // signal duration in seconds = 7 minutes

            int[]  harmonics     = { 500, 1000, 2000, 4000, 8000 };
            var    recording     = DspFilters.GenerateTestRecording(sampleRate, duration, harmonics, WaveType.Cosine);
            string recordingName = "TemporaryRecording2";
            var    recordingPath = this.outputDirectory.CombineFile(recordingName + ".wav");

            WavWriter.WriteWavFileViaFfmpeg(recordingPath, recording.WavReader);

            var fst       = FreqScaleType.Linear125Octaves7Tones28Nyquist32000;
            var freqScale = new FrequencyScale(fst);

            /*
             * // draw the signal as spectrogram just for debugging purposes
             * // but can only draw a two minute spectrogram when sr=64000 - change duration above.
             * duration = 120; // if drawing sonogram, then set signal duration = 2 minutes
             * var sonogram = OctaveFreqScale.ConvertRecordingToOctaveScaleSonogram(recording, fst);
             * var sonogramImage = sonogram.GetImageFullyAnnotated(sonogram.GetImage(), "SPECTROGRAM", freqScale.GridLineLocations);
             * var outputImagePath = this.outputDirectory.CombineFile("SignalSpectrogram_OctaveFreqScale.png");
             * sonogramImage.Save(outputImagePath.FullName);
             */

            // Now need to rewrite the config file with new parameter settings
            var configPath = PathHelper.ResolveConfigFile("Towsey.Acoustic.yml");

            // Convert the Config config to IndexCalculateConfig class and merge in the unnecesary parameters.
            //Config configuration = Yaml.Deserialise(configPath);
            //IndexCalculateConfig config = IndexCalculateConfig.GetConfig(configuration, false);

            // because of difficulties in dealing with Config config files, just edit the text file!!!!!
            var configLines = File.ReadAllLines(configPath.FullName);

            configLines[configLines.IndexOf(x => x.StartsWith("IndexCalculationDuration: "))] = "IndexCalculationDuration: 15.0";

            //configLines[configLines.IndexOf(x => x.StartsWith("BgNoiseBuffer: "))] = "BgNoiseBuffer: 5.0";
            configLines[configLines.IndexOf(x => x.StartsWith("FrequencyScale: Linear"))] = "FrequencyScale: " + fst;

            // the is the only octave scale currently functioning for IndexCalculate class
            configLines[configLines.IndexOf(x => x.StartsWith("FrameLength"))]    = $"FrameLength: {freqScale.WindowSize}";
            configLines[configLines.IndexOf(x => x.StartsWith("ResampleRate: "))] = "ResampleRate: 64000";

            // write the edited Config file to temporary output directory
            var newConfigPath = this.outputDirectory.CombineFile("Towsey.Acoustic.yml");

            File.WriteAllLines(newConfigPath.FullName, configLines);

            PathHelper.ResolveConfigFile("IndexPropertiesConfig.yml").CopyTo(this.outputDirectory.CombineFile("IndexPropertiesConfig.yml").FullName);

            var arguments = new AnalyseLongRecording.Arguments
            {
                Source        = recordingPath,
                Config        = newConfigPath.FullName,
                Output        = this.outputDirectory,
                MixDownToMono = true,
                Parallel      = !Debugger.IsAttached,
            };

            AnalyseLongRecording.Execute(arguments);

            var resultsDirectory = this.outputDirectory.Combine("Towsey.Acoustic");
            var listOfFiles      = resultsDirectory.EnumerateFiles().ToArray();

            Assert.AreEqual(19, listOfFiles.Length);

            var csvCount = listOfFiles.Count(f => f.Name.EndsWith(".csv"));

            Assert.AreEqual(15, csvCount);

            var jsonCount = listOfFiles.Count(f => f.Name.EndsWith(".json"));

            Assert.AreEqual(2, jsonCount);

            var pngCount = listOfFiles.Count(f => f.Name.EndsWith(".png"));

            Assert.AreEqual(2, pngCount);

            var bgnFile = resultsDirectory.CombineFile(recordingName + "__Towsey.Acoustic.BGN.csv");

            double[,] actualBgn = Csv.ReadMatrixFromCsv <double>(bgnFile, TwoDimensionalArray.None);

            var expectedSpectrumFile = PathHelper.ResolveAsset("LongDuration", "BgnMatrix.OctaveScale.csv");

            // uncomment the following line when first produce the array
            // bgnFile.CopyTo(expectedSpectrumFile.FullName);

            // compare actual BGN file with expected file.
            var expectedBgn = Csv.ReadMatrixFromCsv <double>(expectedSpectrumFile, TwoDimensionalArray.None);

            CollectionAssert.That.AreEqual(expectedBgn, actualBgn, 0.000_000_001);

            var array = MatrixTools.GetRow(actualBgn, 0);

            Assert.AreEqual(28, actualBgn.RowLength());
            Assert.AreEqual(256, array.Length);

            // draw array just to check peaks are in correct places - just for debugging purposes
            var ldsBgnSpectrumFile = this.outputDirectory.CombineFile("Spectrum2.png");

            GraphsAndCharts.DrawGraph(array, "LD BGN SPECTRUM Octave", ldsBgnSpectrumFile);

            // ##########################################
            // SECOND part of test is to create the LD spectrograms because they are not created when IndexCalcDuration < 60 seconds
            // first read in the index generation data
            var icdPath         = resultsDirectory.CombineFile(recordingName + "__IndexGenerationData.json");
            var indexConfigData = Json.Deserialize <IndexGenerationData>(icdPath);

            var indexPropertiesConfig = PathHelper.ResolveConfigFile("IndexPropertiesConfig.yml");

            var ldSpectrogramConfigFile = PathHelper.ResolveConfigFile("SpectrogramFalseColourConfig.yml");
            var ldSpectrogramConfig     = LdSpectrogramConfig.ReadYamlToConfig(ldSpectrogramConfigFile);

            ldSpectrogramConfig.FreqScale = fst.ToString();

            // finally read in the dictionary of spectra
            string analysisType        = "Towsey.Acoustic";
            var    keys                = LDSpectrogramRGB.GetArrayOfAvailableKeys();
            var    dictionaryOfSpectra = IndexMatrices.ReadSpectralIndices(resultsDirectory, recordingName, analysisType, keys);

            LDSpectrogramRGB.DrawSpectrogramsFromSpectralIndices(
                inputDirectory: resultsDirectory,
                outputDirectory: resultsDirectory,
                ldSpectrogramConfig: ldSpectrogramConfig,
                indexPropertiesConfigPath: indexPropertiesConfig,
                indexGenerationData: indexConfigData,
                basename: recordingName,
                analysisType: analysisType,
                indexSpectrograms: dictionaryOfSpectra);

            // test number of images - should now be 23
            listOfFiles = resultsDirectory.EnumerateFiles().ToArray();
            pngCount    = listOfFiles.Count(f => f.Name.EndsWith(".png"));
            Assert.AreEqual(22, pngCount);

            var twoMapsImagePath = resultsDirectory.CombineFile(recordingName + "__2Maps.png");
            var twoMapsImage     = Image.Load <Rgb24>(twoMapsImagePath.FullName);

            // image is (7*4) * 652
            Assert.AreEqual(28, twoMapsImage.Width);
            Assert.AreEqual(652, twoMapsImage.Height);
        }
Example #25
0
        public void TestAnalyzeSr22050Recording()
        {
            int    sampleRate = 22050;
            double duration   = 420; // signal duration in seconds = 7 minutes

            int[] harmonics     = { 500, 1000, 2000, 4000, 8000 };
            var   recording     = DspFilters.GenerateTestRecording(sampleRate, duration, harmonics, WaveType.Cosine);
            var   recordingPath = this.outputDirectory.CombineFile("TemporaryRecording1.wav");

            WavWriter.WriteWavFileViaFfmpeg(recordingPath, recording.WavReader);

            // draw the signal as spectrogram just for debugging purposes

            /*
             * var fst = FreqScaleType.Linear;
             * var freqScale = new FrequencyScale(fst);
             * var sonoConfig = new SonogramConfig
             * {
             *  WindowSize = 512,
             *  WindowOverlap = 0.0,
             *  SourceFName = recording.BaseName,
             *  NoiseReductionType = NoiseReductionType.Standard,
             *  NoiseReductionParameter = 2.0,
             * };
             * var sonogram = new SpectrogramStandard(sonoConfig, recording.WavReader);
             * var image = sonogram.GetImageFullyAnnotated(sonogram.GetImage(), "SPECTROGRAM", freqScale.GridLineLocations);
             * var outputImagePath = this.outputDirectory.CombineFile("Signal1_LinearFreqScale.png");
             * image.Save(outputImagePath.FullName);
             */

            var configPath = PathHelper.ResolveConfigFile("Towsey.Acoustic.yml");

            var arguments = new AnalyseLongRecording.Arguments
            {
                Source        = recordingPath,
                Config        = configPath.FullName,
                Output        = this.outputDirectory,
                MixDownToMono = true,
                Parallel      = !Debugger.IsAttached,
            };

            AnalyseLongRecording.Execute(arguments);

            var resultsDirectory = this.outputDirectory.Combine("Towsey.Acoustic");
            var listOfFiles      = resultsDirectory.EnumerateFiles().ToArray();

            Assert.AreEqual(38, listOfFiles.Length);

            var csvCount = listOfFiles.Count(f => f.Name.EndsWith(".csv"));

            Assert.AreEqual(15, csvCount);

            var jsonCount = listOfFiles.Count(f => f.Name.EndsWith(".json"));

            Assert.AreEqual(2, jsonCount);

            var pngCount = listOfFiles.Count(f => f.Name.EndsWith(".png"));

            Assert.AreEqual(21, pngCount);

            var twoMapsImagePath = resultsDirectory.CombineFile("TemporaryRecording1__2Maps.png");
            var twoMapsImage     = Image.Load <Rgb24>(twoMapsImagePath.FullName);

            // image is 7 * 632
            Assert.AreEqual(7, twoMapsImage.Width);
            Assert.AreEqual(632, twoMapsImage.Height);

            var bgnFile = resultsDirectory.CombineFile("TemporaryRecording1__Towsey.Acoustic.BGN.csv");

            double[,] actualBgn = Csv.ReadMatrixFromCsv <double>(bgnFile, TwoDimensionalArray.None);

            var expectedSpectrumFile = PathHelper.ResolveAsset("LongDuration", "BgnMatrix.LinearScale.csv");

            // uncomment the following line when first produce the array
            // bgnFile.CopyTo(expectedSpectrumFile.FullName);

            // compare actual BGN file with expected file.
            var expectedBgn = Csv.ReadMatrixFromCsv <double>(expectedSpectrumFile, TwoDimensionalArray.None);

            CollectionAssert.That.AreEqual(expectedBgn, actualBgn, 0.000_000_001);

            var array = MatrixTools.GetRow(actualBgn, 0);

            Assert.AreEqual(7, expectedBgn.RowLength());
            Assert.AreEqual(256, array.Length);

            // draw array just to check peaks are in correct places - just for debugging purposes
            var ldsBgnSpectrumFile = this.outputDirectory.CombineFile("Spectrum1.png");

            GraphsAndCharts.DrawGraph(array, "LD BGN SPECTRUM Linear", ldsBgnSpectrumFile);

            var generationData = Json.Deserialize <IndexGenerationData>(IndexGenerationData.FindFile(resultsDirectory));

            Assert.AreEqual("TemporaryRecording1", generationData.RecordingBasename);
        }
        public SoundBufferedDataSource(FileInfo FileName)
        {
            //Extract the data from the sound file, and create a buffer with them

            //Creating the source, was not existing
            Volume = 1.0f;

            SoundStream soundstream;

            switch (FileName.Extension)
            {
            case ".wav":
                //Load the sound and bufferize it
                soundstream = new SoundStream(File.OpenRead(FileName.FullName));
                WaveFormat  = soundstream.Format;
                AudioBuffer = new AudioBuffer()
                {
                    Stream     = soundstream.ToDataStream(),
                    AudioBytes = (int)soundstream.Length,
                    Flags      = BufferFlags.EndOfStream
                };

                soundstream.Close();
                soundstream.Dispose();
                break;

            case ".wma":     // NOT good idea this can be HUGE buffer, better streaming a WMA file !
                //New data stream
                using (FileStream fileStream = new FileStream(FileName.FullName, FileMode.Open, FileAccess.Read))
                {
                    var audioDecoder    = new AudioDecoder(fileStream);
                    var outputWavStream = new MemoryStream();

                    var wavWriter = new WavWriter(outputWavStream);

                    // Write the WAV file
                    wavWriter.Begin(audioDecoder.WaveFormat);
                    // Decode the samples from the input file and output PCM raw data to the WAV stream.
                    wavWriter.AppendData(audioDecoder.GetSamples());
                    // Close the wav writer.
                    wavWriter.End();

                    outputWavStream.Position = 0;
                    soundstream = new SoundStream(outputWavStream);

                    WaveFormat  = soundstream.Format;
                    AudioBuffer = new AudioBuffer()
                    {
                        Stream     = soundstream.ToDataStream(),
                        AudioBytes = (int)soundstream.Length,
                        Flags      = BufferFlags.EndOfStream
                    };

                    soundstream.Close();
                    soundstream.Dispose();
                    outputWavStream.Dispose();
                    audioDecoder.Dispose();
                }

                break;

            default:
                break;
            }
        }