コード例 #1
0
        /*
         * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
         * Buttons
         *
         * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
         */
        private void exportButton_Click(object sender, EventArgs e)
        {
            if (File.Exists(Environment.CurrentDirectory + @"\preview.wav"))
            {
                save.Filter = "WAV File (*.wav)|*.wav";
                if (save.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                File.Copy(Environment.CurrentDirectory + @"\preview.wav", save.FileName);
            }
            else
            {
                AudioFileReader[] audioArray = compileTexttoSound().ToArray();

                var playlist = new ConcatenatingSampleProvider(audioArray);
                //wrap in try catch(IOException) in event that file is opened when repalcing
                save.Filter = "WAV File (*.wav)|*.wav";
                if (save.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                WaveFileWriter.CreateWaveFile16(save.FileName, playlist);
                MessageBox.Show("Complete");
            }
        }
コード例 #2
0
ファイル: Word.cs プロジェクト: otabk/WpfTTS
 public void Init()
 {
     try
     {
         ISampleProvider[] sources = new ISampleProvider[Syllables.Length];
         for (int i = 0; i < Syllables.Length; i++)
         {
             if (File.Exists(Syllables[i].TWavPath))
             {
                 var wavSource = new AudioFileReader(Syllables[i].TWavPath);
                 sources[i] = wavSource.Take(new TimeSpan(0, 0, 0, 0, (int)(wavSource.TotalTime.Milliseconds * 0.9))).Skip(new TimeSpan(0, 0, 0, 0, (int)(wavSource.TotalTime.Milliseconds * 0.15)));
             }
             else
             {
                 sources[i] = null;
                 return;
             }
         }
         Wav = new ConcatenatingSampleProvider(sources);
     }
     catch (Exception e)
     {
         Console.WriteLine(e.Message);
     }
 }
コード例 #3
0
        private ISampleProvider CreatePlaylistFromText(string text, WaveFormat newFormat)
        {
            text = whitespaceRegex.Replace(text, "");
            var charProviders = text.ToCharArray().ToList()
                                .Select(character => wavCharactersProvider.GetCharacterProvider(character, newFormat));
            var concatenatingPlaylist = new ConcatenatingSampleProvider(charProviders);

            return(concatenatingPlaylist);
        }
コード例 #4
0
        public string ConcatenatingAudio(string firstFilePath, string secondFilePath)
        {
            var first  = new AudioFileReader(firstFilePath);
            var second = new AudioFileReader(secondFilePath);

            var    playlist       = new ConcatenatingSampleProvider(new[] { first, second });
            string outputFileName = secondFilePath.Substring(0, secondFilePath.Length - 4);
            var    outPath        = outputFileName + "Concatenate.wav";

            WaveFileWriter.CreateWaveFile16(outPath, playlist);

            return(outPath);
        }
コード例 #5
0
        static void ConcatAudio(List <string> audioFiles, string outputAudioFile)
        {
            List <AudioFileReader> audioFileReaders = new List <AudioFileReader>();

            audioFiles.ForEach(f => audioFileReaders.Add(new AudioFileReader(f)));
            var mixer           = new ConcatenatingSampleProvider(audioFileReaders);
            var outputDirectory = Path.GetDirectoryName(outputAudioFile);

            if (!Directory.Exists(outputDirectory))
            {
                Directory.CreateDirectory(outputDirectory);
            }
            WaveFileWriter.CreateWaveFile16(outputAudioFile, mixer);
            audioFileReaders.ForEach(r => r.Close());
        }
コード例 #6
0
        public void CanPassTwoProviders()
        {
            // arrange
            var expectedLength = 100;
            var input1         = new TestSampleProvider(44100, 2, 50);
            var input2         = new TestSampleProvider(44100, 2, 50);
            var concatenator   = new ConcatenatingSampleProvider(new[] { input1, input2 });
            var buffer         = new float[2000];

            var read = concatenator.Read(buffer, 0, buffer.Length);

            Assert.AreEqual(expectedLength, read, "read == expectedLength");
            Assert.AreEqual(49, buffer[49]);
            Assert.AreEqual(0, buffer[50]);
            Assert.AreEqual(49, buffer[99]);
        }
コード例 #7
0
        private void PlayChime(RawSourceWaveStream chime, RawSourceWaveStream chimeIntro, RawSourceWaveStream finalChime)
        {
            if (null == chime ||
                null == chimeIntro ||
                null == finalChime)
            {
                Console.Beep();
            }
            else
            {
                int hour = DateTime.Now.Hour;
                if (hour == 0)
                {
                    hour = 12;
                }
                if (hour > 12)
                {
                    hour = hour - 12;
                }

                List <ISampleProvider> providers = new List <ISampleProvider>();
                providers.Add(chimeIntro.ToSampleProvider());

                for (int i = 0; i < hour - 1; i++)
                {
                    MemoryStream stream = new MemoryStream();
                    chime.CopyTo(stream);
                    RawSourceWaveStream waveStream = new RawSourceWaveStream(stream, chime.WaveFormat);
                    waveStream.Position = 0;
                    chime.Position      = 0;
                    providers.Add(waveStream.ToSampleProvider());
                }

                providers.Add(finalChime.ToSampleProvider());
                ConcatenatingSampleProvider provida = new ConcatenatingSampleProvider(providers);

                var outputDevice = new WaveOutEvent();
                outputDevice.Volume = _options.Volume;
                outputDevice.Init(provida);
                outputDevice.Play();
                outputDevice.PlaybackStopped += OnPlaybackStopped;

                chime.Position      = 0;
                chimeIntro.Position = 0;
                finalChime.Position = 0;
            }
        }
コード例 #8
0
        private static void SaveAudioFile(List <Vec> points, string filename)
        {
            var width  = points.Max(p => p.X) + 1;
            var height = points.Max(p => p.Y) + 1;
            var pixels = points.Select(p => p.Y * width + p.X).ToHashSet();

            var sineZero = new SignalGenerator(44100, 1)
            {
                Gain      = 0.2,
                Frequency = 500,
                Type      = SignalGeneratorType.Sin
            };
            var sineOne = new SignalGenerator(44100, 1)
            {
                Gain      = 0.2,
                Frequency = 600,
                Type      = SignalGeneratorType.Sin
            };
            var tick = TimeSpan.FromSeconds(0.05);
            var messageSampleProviders        = Enumerable.Range(0, width * height).Select(i => pixels.Contains(i) ? sineOne.Take(tick) : sineZero.Take(tick));
            var combinedMessageSampleProvider = new ConcatenatingSampleProvider(messageSampleProviders);

            var backgroundNoiseSampleProvider = new SignalGenerator(44100, 1)
            {
                Gain = 0.1,
                Type = SignalGeneratorType.Pink
            }.Take(tick * width * height);
            var messageWithNoiseSampleProvider = new MixingSampleProvider(new List <ISampleProvider> {
                combinedMessageSampleProvider, backgroundNoiseSampleProvider
            });

            var paddingSampleProvider = new SignalGenerator(44100, 1)
            {
                Gain = 0.1,
                Type = SignalGeneratorType.Pink
            }.Take(TimeSpan.FromSeconds(3));
            var messageWithPaddingSampleProvider = new ConcatenatingSampleProvider(new List <ISampleProvider> {
                paddingSampleProvider, messageWithNoiseSampleProvider, paddingSampleProvider
            });

            WaveFileWriter.CreateWaveFile16(filename, messageWithPaddingSampleProvider);
        }
コード例 #9
0
        private static void CreateAudioSprite(List <SoundInfo> soundInfos, int audioSpriteIndex, string destinationDirectory, string baseFileName, string ffmpegFilePath, string wavsDirectory, double spacingDuration)
        {
            string fileNameNoExt = baseFileName + "_" + audioSpriteIndex;

            Console.WriteLine(fileNameNoExt + ":");
            foreach (SoundInfo si in soundInfos)
            {
                Console.WriteLine("+ " + si.displayFilename + " start time: " + si.startTime + " duration: " + si.duration);
            }

            // tell each soundInfo the audio sprite they'll belong to
            foreach (SoundInfo si in soundInfos)
            {
                si.audioSpriteIndex = audioSpriteIndex;
            }

            ISampleProvider[] providersMp3 = new ISampleProvider[soundInfos.Count];
            ISampleProvider[] providersOgg = new ISampleProvider[soundInfos.Count];
            for (int i = 0; i < soundInfos.Count; i++)
            {
                providersMp3[i] = soundInfos[i].audioReaderMp3;
                providersOgg[i] = soundInfos[i].audioReaderOgg;
            }

            ApplyOffset(providersMp3, spacingDuration, true);
            ApplyOffset(providersOgg, spacingDuration, false);

            // concatinate sounds into one sample provider
            ConcatenatingSampleProvider concatMp3 = new ConcatenatingSampleProvider(providersMp3);
            ConcatenatingSampleProvider concatOgg = new ConcatenatingSampleProvider(providersOgg);

            // write to file
            string mp3File = Path.Combine(destinationDirectory, fileNameNoExt + ".mp3");

            CreateMp3File(concatMp3, mp3File);
            string oggFile = Path.Combine(destinationDirectory, fileNameNoExt + ".ogg");
            string wavFile = Path.Combine(wavsDirectory, fileNameNoExt + ".wav");

            CreateOggFile(concatOgg, ffmpegFilePath, wavFile, oggFile);
        }
コード例 #10
0
        public void CanPassASingleProvider()
        {
            // arrange
            const int expectedLength = 5000;
            var       input          = new TestSampleProvider(44100, 2, expectedLength);
            var       concatenator   = new ConcatenatingSampleProvider(new[] { input });
            var       buffer         = new float[2000];
            var       totalRead      = 0;

            // act
            while (true)
            {
                var read = concatenator.Read(buffer, 0, buffer.Length);
                if (read == 0)
                {
                    break;
                }
                totalRead += read;
                Assert.That(totalRead <= expectedLength);
            }
            Assert.That(totalRead == expectedLength);
        }
コード例 #11
0
ファイル: Program.cs プロジェクト: ml-pastore/AudioFlash
        static async Task Main(string[] args)
        {
            string configName = "";

            if (args.Length > 0)
            {
                configName = args[0];
            }
            else
            {
                configName = "_samples/_bin/config_sample.json";
            }

            Console.WriteLine($"{configName}");

            if (!File.Exists(configName))
            {
                Console.WriteLine($"File does not exist: {configName}");
                Environment.Exit((int)RetCodes.ConfigFileNotFound);
            }

            IConfig c = new Config();

            try
            {
                c = JsonConvert.DeserializeObject <Config>(File.ReadAllText(configName));
                c.Authentication = JsonConvert.DeserializeObject <Authentication>(File.ReadAllText(c.FileInPut.authFile));
            }
            catch (Exception e)
            {
                Environment.Exit((int)RetCodes.InvalidConfigInit);
            }

            ILogger lg = new Logger();

            lg.LogFile = String.Concat(c.FileOutPut.LogFolder, "/runLog.txt");
            lg.Write(new string('-', 50));
            lg.Write($"{DateTime.Now}");

            IEnumerable <CSVInput> allQuests = CSVInput.GetAllQuestions(c);

            // build wav output
            int fileCntr = c.FileOutPut.StartOutNum;
            int numRecs  = allQuests.Where(x => x.IsActive.ToUpper() == "TRUE").Count();

            if (numRecs == 0)
            {
                Environment.Exit((int)RetCodes.NoRecs);
            }

            int       numZerosCalc = Convert.ToInt32(Math.Log10(numRecs) + 1);
            int       numZeros     = Math.Max(c.FileOutPut.OutNumPad, numZerosCalc);
            SoundUtil sndUtil      = new SoundUtil();

            const int QUESTION = 0;
            const int ANSWER   = 1;

            TTS_QA[] ttsQA           = { new TTS_QA(), new TTS_QA() };
            string   outFileNameBase = "";

            foreach (CSVInput ln in allQuests.Where(x => x.IsActive.ToUpper() == "TRUE"))
            {
                lg.Write("-".PadLeft(20, '-'));
                lg.Write($"Src file: {ln.SourceCSVFile}, Line#: {ln.FileLineNum}");

                outFileNameBase = string.Format(@"{0}/{1}.wav", c.FileOutPut.SoundFolder
                                                , c.FileOutPut.WAVPrefix.Replace("{#}", fileCntr.ToString().PadLeft(numZeros, '0')));

                int    pauseSec  = Convert.ToInt32(ln.AnswerWaitSeconds) * 1000;
                string pauseText = $"<break time=\"{pauseSec}ms\"/>";

                string question = $"{ln.Question} {pauseText}";

                ttsQA[QUESTION] = new TTS_QA {
                    QAText = question,
                    Lang   = ln.QuesLang, ProsodyRate = ln.QuesProsodyRate, OutFile = outFileNameBase.Replace(".wav", "_ques.wav")
                };

                ttsQA[ANSWER] = new TTS_QA {
                    QAText = ln.Answer,
                    Lang   = ln.AnsLang, ProsodyRate = ln.AnsProsodyRate, OutFile = outFileNameBase.Replace(".wav", "_resp.wav")
                };                                                                                                              // append "resp" for sorting purposes if Q/A files are separate

                foreach (TTS_QA qa in ttsQA)
                {
                    TextToSpeech t = new TextToSpeech();

                    ISound sndOut = new SoundOutput(c.SoundDefault);
                    t.Sound = sndOut;

                    t.TextIn         = qa.QAText;
                    t.Sound.Language = sndUtil.GetSoundProp(qa.Lang, c.SoundDefault.Language);

                    // random speaker from avail list
                    string spkr = sndUtil.GetRandSpeakerName(t.Sound.Language, c.SoundDefault.Speakers);
                    t.Sound.Speaker     = sndUtil.GetSoundProp(spkr, c.SoundDefault.Speaker);
                    t.Sound.ProsodyRate = sndUtil.GetSoundProp(qa.ProsodyRate, c.SoundDefault.ProsodyRate);

                    t.FileOut = qa.OutFile;

                    if (!string.IsNullOrEmpty(t.TextIn))
                    {
                        lg.Write($"Spkr: {t.Sound.Speaker}, Text: {t.TextIn.Substring(0, Math.Min(t.TextIn.Length, 20))} ... -> {t.FileOut}");
                    }

                    while (File.Exists(t.FileOut))
                    {
                        File.Delete(t.FileOut);
                    }

                    await t.OutPutTTS(c.Authentication);
                }

                if (!c.FileOutPut.SplitQAFiles) // need to merge them
                {
                    var ques = new AudioFileReader(ttsQA[QUESTION].OutFile);
                    var ans  = new AudioFileReader(ttsQA[ANSWER].OutFile);

                    File.Delete(outFileNameBase);

                    ConcatenatingSampleProvider playlist = new ConcatenatingSampleProvider(new[] { ques, ans });

                    lg.Write($"\n---> Merging {ttsQA[QUESTION].OutFile} and {ttsQA[ANSWER].OutFile} to {outFileNameBase}");

                    WaveFileWriter.CreateWaveFile16(outFileNameBase, playlist);

                    ques.Dispose();
                    ans.Dispose();

                    File.Delete(ttsQA[QUESTION].OutFile);
                    File.Delete(ttsQA[ANSWER].OutFile);
                }


                fileCntr++;
            }

            // update config file with last counter ref
            String cOut    = File.ReadAllText(configName);
            string incrTxt = $"\"StartOutNum\":";

            cOut = Regex.Replace(cOut, $"{incrTxt}\\s+\"\\d+\""
                                 , $"{incrTxt} \"{fileCntr.ToString()}\"");

            File.WriteAllText(configName, cOut);

            lg.Write("Done");
            lg.Dispose();

            Console.WriteLine($"Done");
            Environment.Exit((int)RetCodes.Success);
        }