示例#1
0
        public async Task Resample(string srcFile, string destFile)
        {
            var wavFile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(destFile), $"{System.IO.Path.GetFileNameWithoutExtension(destFile)}.wav");

            if (System.IO.File.Exists(wavFile))
            {
                System.IO.File.Delete(wavFile);
            }
            using (var reader = new AudioFileReader(srcFile))
            {
                var resampler = new WdlResamplingSampleProvider(reader, 44100);
                WaveFileWriter.CreateWaveFile16(wavFile, resampler);
            }
            using (var reader = new WaveFileReader(wavFile))
            {
                if (System.IO.File.Exists(destFile))
                {
                    System.IO.File.Delete(destFile);
                }
                using (var writer = new LameMP3FileWriter(destFile, reader.WaveFormat, LAMEPreset.EXTREME))
                {
                    //reader.CopyTo(writer);
                    await reader.CopyToAsync(writer);

                    await writer.FlushAsync();
                }
            }
            System.IO.File.Delete(wavFile);
        }
示例#2
0
        /// <summary>
        /// Mixes two wav files to a single wav file. (Unused).
        /// </summary>
        public void mix()
        {
            window.lockForMixing();

            WaveFileReader reader1 = new WaveFileReader(file1);
            WaveFileReader reader2 = new WaveFileReader(file2);

            int        maxSampleRate = Math.Max(reader1.WaveFormat.SampleRate, reader2.WaveFormat.SampleRate);
            WaveFormat format        = new WaveFormat(maxSampleRate, 1);

            MediaFoundationResampler resampler1 = new MediaFoundationResampler(reader1, format);
            var input1 = resampler1.ToSampleProvider();
            MediaFoundationResampler resampler2 = new MediaFoundationResampler(reader2, format);
            var input2 = resampler2.ToSampleProvider();

            ISampleProvider[] provider = { input1, input2 };

            MixingSampleProvider mixer = new MixingSampleProvider(provider);

            WaveFileWriter.CreateWaveFile16(mixfile, mixer);

            resampler1.Dispose();
            resampler2.Dispose();
            reader1.Close();
            reader2.Close();
            reader1.Dispose();
            reader2.Dispose();

            window.unlock();
        }
示例#3
0
        static void Convert(
            string inputPath, out string intermediateSampleRatePath, SampleRate?sampleRate,
            string outputDirectory, string outputFileName, ref bool isAlreadyConvertedToBitRateHigh)
        {
            if (!sampleRate.HasValue)
            {
                intermediateSampleRatePath = inputPath;
                return;
            }

            var actualSampleRate = SampleRateHelper.GetSampleRate(sampleRate.Value);

            using (var reader = new AudioFileReader(inputPath))
            {
                if (reader.WaveFormat.SampleRate != actualSampleRate)
                {
                    var intermediateSampleRateFileName = $"{outputFileName}-intermediate-samplerate.wav";
                    intermediateSampleRatePath = Path.Combine(outputDirectory, intermediateSampleRateFileName);
                    var resampler = new WdlResamplingSampleProvider(reader, actualSampleRate);
                    WaveFileWriter.CreateWaveFile16(intermediateSampleRatePath, resampler);
                    isAlreadyConvertedToBitRateHigh = true;
                }
                else
                {
                    intermediateSampleRatePath = inputPath;
                }
            }
        }
示例#4
0
        /// <summary>
        /// Пункт конвертации в стерео
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void конвертацияВСтереоToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StopAud();
            SaveFileDialog save = new SaveFileDialog();

            save.InitialDirectory = "C:\\";
            save.Filter           = "wav files (*.wav)|*.wav";
            save.FilterIndex      = 1;
            save.Title            = "Сохранить файл";
            if (save.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }
            string filename = save.FileName;

            if (filename != null)
            {
                using (var inputReader = new AudioFileReader(rfname))
                {
                    var stereo = new MonoToStereoSampleProvider(inputReader);
                    WaveFileWriter.CreateWaveFile16(filename, stereo);
                }
                MessageBox.Show("Файл сохранен!");
            }
            else
            {
                System.Windows.Forms.MessageBox.Show("Не выбран путь сохранения!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
示例#5
0
        /* static void Main(string[] args)
         * {
         *   // Display the number of command line arguments.
         *   Console.WriteLine(args.Length);
         * }*/

        static void ToWav()
        {
            var filePath = $@"C:\Users\blabla\foo\bar\";
            var fileOgg  = "testAudio.ogg";
            var fileWav  = "testAudio.wav";

            using (FileStream fileIn = new FileStream($"{filePath}{fileOgg}", FileMode.Open))
                using (MemoryStream pcmStream = new MemoryStream())
                {
                    OpusDecoder       decoder = OpusDecoder.Create(48000, 1);
                    OpusOggReadStream oggIn   = new OpusOggReadStream(decoder, fileIn);
                    while (oggIn.HasNextPacket)
                    {
                        short[] packet = oggIn.DecodeNextPacket();
                        if (packet != null)
                        {
                            for (int i = 0; i < packet.Length; i++)
                            {
                                var bytes = BitConverter.GetBytes(packet[i]);
                                pcmStream.Write(bytes, 0, bytes.Length);
                            }
                        }
                    }
                    pcmStream.Position = 0;
                    var wavStream      = new RawSourceWaveStream(pcmStream, new WaveFormat(48000, 1));
                    var sampleProvider = wavStream.ToSampleProvider();
                    WaveFileWriter.CreateWaveFile16($"{filePath}{fileWav}", sampleProvider);
                }
        }
示例#6
0
        public static Stream ConvertAiffToMp3(Stream aiffStream, string directory)
        {
            _uniqueTempFileCounter += 1;
            var tempFile = Path.GetTempFileName();

            using (var rdr = new AiffFileReader(aiffStream))
            {
                //can't go from 24 bits aif to mp3 directly, create temporary 16 bit wav
                if (rdr.WaveFormat.BitsPerSample == 24)
                {
                    ISampleProvider sampleprovider = new Pcm24BitToSampleProvider(rdr);                           //24 bit to sample
                    var             resampler      = new WdlResamplingSampleProvider(sampleprovider, SampleRate); //sample to new sample rate
                    WaveFileWriter.CreateWaveFile16(tempFile, resampler);                                         //sample to actual wave file
                    return(ConvertWavFileToMp3MemoryStream(tempFile, true));                                      //file to mp3 bytes
                }
                else
                {
                    var retMs = FilesystemUtils.recyclableMemoryStreamManager.GetStream();
                    using (var wtr = new LameMP3FileWriter(retMs, rdr.WaveFormat, BitRate))
                    {
                        rdr.CopyTo(wtr);
                        return(retMs);
                    }
                }
            }
        }
示例#7
0
        private static void WriteNormalizedAudio(string path, [NotNull] WaveStream reader)
        {
            var sampleReader = reader.ToSampleProvider();

            // find the max peak
            float max    = 0;
            var   buffer = new float[reader.WaveFormat.SampleRate];
            int   read;

            do
            {
                read = sampleReader.Read(buffer, 0, buffer.Length);
                if (read > 0)
                {
                    max = Math.Max(max, Enumerable.Range(0, read).Select(i => Math.Abs(buffer[i])).Max());
                }
            } while (read > 0);

            if (Math.Abs(max) < float.Epsilon || max > 1.0f)
            {
                throw new InvalidOperationException("Audio normalization failed to find a reasonable peak volume");
            }

            // rewind and amplify
            reader.Position = 0;

            // write out to a new WAV file
            WaveFileWriter.CreateWaveFile16(path, new GainSampleProvider(sampleReader, 1 / max - 0.05f));
        }
示例#8
0
 /// <summary>
 /// 截取音频后,对每个小音频获语音转文字
 /// </summary>
 /// <param name="startMilliSecond">开始时间戳</param>
 /// <param name="endMilliSecond">结束时间戳</param>
 /// <param name="reader">音频流</param>
 /// <param name="i">用于创建新的文件</param>
 /// <param name="language">语言(zh,en)</param>
 /// <param name="splitTime">时间间隔</param>
 private void GetBaiduSpeech1(TimeSpan startMilliSecond, TimeSpan endMilliSecond, string sound_path, int i, string language, double splitTime)
 {
     try
     {
         var reader = new AudioFileReader(sound_path);
         //开始时间往前取startMilliSecond一半的偏移,结束时间往后取间隔时间的一半的偏移
         if (i == 0)
         {
             startMilliSecond = startMilliSecond - TimeSpan.FromMilliseconds(startMilliSecond.TotalMilliseconds / 2);
         }
         else
         {
             startMilliSecond = startMilliSecond - TimeSpan.FromMilliseconds(splitTime / 2);
         }
         if (endMilliSecond < reader.TotalTime)//最后一次不用取偏移
         {
             endMilliSecond = endMilliSecond + TimeSpan.FromMilliseconds(splitTime / 2);
         }
         TimeSpan span = endMilliSecond - startMilliSecond;
         if (span.TotalSeconds > 60)//超过60s,只取60秒
         {
             span = TimeSpan.FromSeconds(60);
         }
         var trimed = reader.Skip(startMilliSecond).Take(endMilliSecond - startMilliSecond);
         //保存新的音频文件
         string fileName  = Path.GetFileNameWithoutExtension(sound_path) + "_" + i + Path.GetExtension(sound_path);//重命名文件
         string newFolder = System.AppDomain.CurrentDomain.BaseDirectory + "NewSoundFiles/" + Path.GetFileNameWithoutExtension(sound_path) + "/";
         //重新存储到一个新的文件目录
         if (!System.IO.Directory.Exists(newFolder))
         {
             System.IO.Directory.CreateDirectory(newFolder);
         }
         string newFile = newFolder + fileName;
         WaveFileWriter.CreateWaveFile16(newFile, trimed);
         //绝对路径
         string path_absolute = context.Server.MapPath("/NewSoundFiles/" + Path.GetFileNameWithoutExtension(sound_path) + "/" + fileName);
         voiceFiles.Add(UploadFile.PostFile(path_absolute));
         if (span == TimeSpan.FromSeconds(60))//音频大于60s
         {
             //小音频
             var _reader = new AudioFileReader(sound_path);
             var _trimed = _reader.Skip(startMilliSecond).Take(span);
             //保存新的音频文件
             string _fileName = "_" + Path.GetFileNameWithoutExtension(sound_path) + "_" + i + Path.GetExtension(sound_path);//重命名文件
             string _newFile  = newFolder + _fileName;
             WaveFileWriter.CreateWaveFile16(_newFile, _trimed);
             baidu_text.Add(BaiduSpeech.BaiduTranslateToText(_newFile, language, _trimed.WaveFormat.SampleRate.ToString()));
         }
         else
         {
             baidu_text.Add(BaiduSpeech.BaiduTranslateToText(newFile, language, trimed.WaveFormat.SampleRate.ToString()));
         }
         reader.Close();
         reader.Dispose();
     }
     catch (Exception ex)
     {
         LogHelper.Error(ex.Message);
     }
 }
示例#9
0
        public static Stream ConvertWavToMp3(Stream wavStream)
        {
            _uniqueTempFileCounter += 1;
            var tempFile = Path.GetTempFileName();

            using (var rdr = new WaveFileReader(wavStream))
            {
                if (rdr.WaveFormat.BitsPerSample == 24)                                                           //Can't go from 24 bits wav to mp3 directly, create temporary 16 bit wav
                {
                    ISampleProvider sampleprovider = new Pcm24BitToSampleProvider(rdr);                           //24 bit to sample
                    var             resampler      = new WdlResamplingSampleProvider(sampleprovider, SampleRate); //sample to new sample rate
                    WaveFileWriter.CreateWaveFile16(tempFile, resampler);                                         //sample to actual wave file
                    return(ConvertWavFileToMp3MemoryStream(tempFile, true));                                      //file to mp3 bytes
                }
                else if (!SupportedMPEGSampleRates.Contains(rdr.WaveFormat.SampleRate))                           //Can't go from unsupported Sample Rate wav to mp3 directly
                {
                    var resampler = new WdlResamplingSampleProvider(rdr.ToSampleProvider(), SampleRate);          //sample to new sample rate
                    WaveFileWriter.CreateWaveFile16(tempFile, resampler);                                         //sample to actual wave file
                    return(ConvertWavFileToMp3MemoryStream(tempFile, true));                                      //file to mp3 bytes
                }
                else
                {
                    var retMs = FilesystemUtils.recyclableMemoryStreamManager.GetStream();
                    using (var wtr = new LameMP3FileWriter(retMs, rdr.WaveFormat, BitRate))
                    {
                        rdr.CopyTo(wtr);
                        return(retMs);
                    }
                }
            }
        }
示例#10
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");
            }
        }
示例#11
0
        public static void RecordAudio(string outFile, int msToRecord)
        {
            string sysAudioFile = Helpers.CreateTempFileName(".wav");
            string micAudioFile = Helpers.CreateTempFileName(".wav");
            Thread sysThread    = new Thread(() => Audio.RecordSystemAudio(sysAudioFile, msToRecord));
            Thread micThread    = new Thread(() => Audio.RecordMicrophone(micAudioFile, msToRecord));

            sysThread.Start();
            micThread.Start();
            micThread.Join();

            using (var reader1 = new AudioFileReader(sysAudioFile))
            {
                using (var reader2 = new AudioFileReader(micAudioFile))
                {
                    reader1.Volume = 0.5f;
                    //reader2.Volume = 0.1f;
                    var mixer = new MixingSampleProvider(new[] { reader1, reader2 });
                    WaveFileWriter.CreateWaveFile16(outFile, mixer);
                }
            }

            File.Delete(sysAudioFile);
            File.Delete(micAudioFile);
        }
        private void GenerateToneWaveFile(string path, DtmfTone tone, int sampleRate, double duration, ISampleProvider noise = null)
        {
            var tone1 = new SignalGenerator(sampleRate, 1)
            {
                Gain      = 0.5,
                Frequency = tone.LowTone,
                Type      = SignalGeneratorType.Sin
            }
            .Take(TimeSpan.FromMilliseconds(duration));

            var tone2 = new SignalGenerator(sampleRate, 1)
            {
                Gain      = 0.5,
                Frequency = tone.HighTone,
                Type      = SignalGeneratorType.Sin
            }
            .Take(TimeSpan.FromMilliseconds(duration));

            var list = new List <ISampleProvider>(new[] { tone1, tone2 });

            if (noise != null)
            {
                list.Add(noise.Take(TimeSpan.FromMilliseconds(duration)));
            }

            var mix = new MixingSampleProvider(list);

            WaveFileWriter.CreateWaveFile16(path, mix);
        }
示例#13
0
        // function that converts an audio file into mono 8-bit PCM, at the current sampling rate
        private void formatAudio(String filePath, float audioAmplify, int samplingRate)
        {
            // convert to mono
            var ir = new AudioFileReader(filePath);


            try
            {
                var mono = new StereoToMonoSampleProvider(ir);
                mono.LeftVolume  = 0.0f;
                mono.RightVolume = audioAmplify;
                var resampler = new WdlResamplingSampleProvider(mono, samplingRate);
                WaveFileWriter.CreateWaveFile16("temp.wav", resampler);
                ir.Close();
            } catch (System.ArgumentException)
            {
                var resampler = new WdlResamplingSampleProvider(ir, samplingRate);
                WaveFileWriter.CreateWaveFile16("temp.wav", resampler);
                ir.Close();
            }



            //File.Delete("temp.wav");
        }
示例#14
0
        public void RenderToFiles(UProject project)
        {
            FileInfo         ResamplerFile = new FileInfo(PathManager.Inst.GetExportEnginePath());
            IResamplerDriver driver        = ResamplerDriver.ResamplerDriver.Load(ResamplerFile.FullName);

            if (driver == null)
            {
                return;
            }
            StopPreRender();
            Task.Run(() => {
                var task = Task.Run(() => {
                    RenderEngine engine = new RenderEngine(project, driver, cache);
                    var trackMixes      = engine.RenderTracks();
                    for (int i = 0; i < trackMixes.Count; ++i)
                    {
                        var file = PathManager.Inst.GetExportPath(project.FilePath, i + 1);
                        DocManager.Inst.ExecuteCmd(new ProgressBarNotification(0, $"Exporting to {file}."));
                        WaveFileWriter.CreateWaveFile16(file, new ExportAdapter(trackMixes[i]));
                        DocManager.Inst.ExecuteCmd(new ProgressBarNotification(0, $"Exported to {file}."));
                    }
                });
                try {
                    task.Wait();
                } catch (AggregateException ae) {
                    foreach (var e in ae.Flatten().InnerExceptions)
                    {
                        Log.Error(e, "Failed to render.");
                    }
                }
            });
        }
        /// <summary>
        /// Convert a stereo WAV file to mono.
        /// </summary>
        /// <param name="stereoFilePath">The path to stereo wav file.</param>
        /// <param name="channels">The channels of input file to use in mono output (default: Both).</param>
        /// <returns>The path to created mono file</returns>
        public static string StereoToMono(string stereoFilePath, MonoOutChannels channels = MonoOutChannels.Both)
        {
            if (Path.GetExtension(stereoFilePath).ToLower() != ".wav")
            {
                throw new AudioException("The input file must be a WAV audio file.");
            }
            using (var inputReader = new AudioFileReader(stereoFilePath)) {
                var mono = new StereoToMonoSampleProvider(inputReader);
                switch (channels)
                {
                case MonoOutChannels.Both:
                    mono.LeftVolume  = 0.5f;
                    mono.RightVolume = 0.5f;
                    break;

                case MonoOutChannels.Right:
                    mono.LeftVolume  = 0f;
                    mono.RightVolume = 1f;
                    break;

                case MonoOutChannels.Left:
                    mono.LeftVolume  = 1f;
                    mono.RightVolume = 0f;
                    break;
                }
                string monoOutDir = Path.Combine(Path.GetDirectoryName(stereoFilePath), "mono");//string.Format("{0}/mono",Path.GetDirectoryName(stereoFilePath));
                if (!Directory.Exists(monoOutDir))
                {
                    Directory.CreateDirectory(monoOutDir);
                }
                string monoFile = string.Format("{0}/{1}.wav", monoOutDir, Path.GetFileNameWithoutExtension(stereoFilePath));
                WaveFileWriter.CreateWaveFile16(monoFile, mono);
                return(monoFile);
            }
        }
示例#16
0
        public static WaveStream ResampleWav(WaveFileReader reader, int sampleRate)
        {
            string outFile;

            using (reader)
            {
                var outFormat = new WaveFormat(sampleRate, reader.WaveFormat.Channels);

                using (var resampler = new MediaFoundationResampler(reader, outFormat))
                {
                    resampler.ResamplerQuality = 60;
                    outFile = Path.Combine(Path.GetTempPath(), "resampled.wav");
                    WaveFileWriter.CreateWaveFile(outFile, resampler);
                }
            }

            using (var resampledReader = new AudioFileReader(outFile))
            {
                using (var filter = new FilterWaveProvider(resampledReader, sampleRate / 4, 1, 80, 1))
                {
                    outFile = Path.Combine(Path.GetTempPath(), "resample_and_filtered.wav");
                    WaveFileWriter.CreateWaveFile16(outFile, filter);
                }
            }
            return(new WaveFileReader(outFile));
        }
示例#17
0
    public void ConvertToWave(string inputFileOgg, string outputFileWav)
    {
        using (FileStream fileIn = new FileStream(inputFileOgg, FileMode.Open))
            using (MemoryStream pcmStream = new MemoryStream())
            {
                OpusDecoder decoder = OpusDecoder.Create(48000, 1);

                OpusOggReadStream oggIn = new OpusOggReadStream(decoder, fileIn);
                while (oggIn.HasNextPacket)
                {
                    short[] packet = oggIn.DecodeNextPacket();
                    if (packet != null)
                    {
                        for (int i = 0; i < packet.Length; i++)
                        {
                            var bytes = BitConverter.GetBytes(packet[i]);
                            pcmStream.Write(bytes, 0, bytes.Length);
                        }
                    }
                }
                pcmStream.Position = 0;
                var wavStream      = new RawSourceWaveStream(pcmStream, new WaveFormat(48000, 1));
                var sampleProvider = wavStream.ToSampleProvider();
                WaveFileWriter.CreateWaveFile16(outputFileWav, sampleProvider);
            }
    }
示例#18
0
        private void buttonSaveSignals_Click(object sender, EventArgs e)
        {
            var samplesList = new List <ISampleProvider> {
                wg1, wg2
            };

            var mixer = new MixingSampleProvider(samplesList);

            var waveOut = new WaveOut();

            waveOut.Init(mixer);
            //waveOut.Play();

            var saveSeconds = (int)numericUpDownSaveSignalsSeconds.Value;
            var sfd         = new SaveFileDialog {
                Filter = "WAV Файл|*.wav"
            };

            if (sfd.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            var osp = new OffsetSampleProvider(mixer)
            {
                TakeSamples = mixer.WaveFormat.SampleRate * saveSeconds * mixer.WaveFormat.Channels
            };

            WaveFileWriter.CreateWaveFile16(sfd.FileName, osp);
        }
        public LAudioConver(string path)
        {
            AudioFileReader fileReader = new AudioFileReader(path);

            this.pathTT = path + ".temp.wav";
            WaveFileWriter.CreateWaveFile16(pathTT, fileReader);
            fileReader.Flush();
        }
示例#20
0
 public void Join2Audio(string inputFile1, string inputFile2, string outFile)
 {
     using (var reader1 = new AudioFileReader(inputFile1))
         using (var reader2 = new AudioFileReader(inputFile2))
         {
             var mixer = new MixingSampleProvider(new[] { reader1, reader2 });
             WaveFileWriter.CreateWaveFile16(outFile, mixer);
         }
 }
示例#21
0
        /// <summary>
        /// Кнопка изменения частоты дискретизации
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            SaveFileDialog save = new SaveFileDialog();

            save.InitialDirectory = "C:\\";
            save.Filter           = "wav files (*.wav)|*.wav";
            save.FilterIndex      = 1;
            save.Title            = "Сохранить файл";
            if (save.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }
            string filename = save.FileName;

            if (filename != null)
            {
                switch (listBox1.SelectedIndex)
                {
                case 0:
                    outRate = 16000;
                    break;

                case 1:
                    outRate = 32000;
                    break;

                case 2:
                    outRate = 44100;
                    break;

                case 3:
                    outRate = 48000;
                    break;

                case 4:
                    outRate = 96000;
                    break;

                case 5:
                    outRate = 192000;
                    break;
                }
                var inFile  = rfn;
                var outFile = filename;
                using (var reader = new AudioFileReader(inFile))
                {
                    var resampler = new WdlResamplingSampleProvider(reader, outRate);
                    WaveFileWriter.CreateWaveFile16(outFile, resampler);
                }
                MessageBox.Show("Файл сохранен!");
                this.Close();
            }
            else
            {
                System.Windows.Forms.MessageBox.Show("Не выбран путь сохранения!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
示例#22
0
 /// <summary>
 /// 音频混合(混音)
 /// </summary>
 /// <param name="filePath1">音频文件路径</param>
 /// <param name="filePath2">音频文件路径</param>
 /// <param name="mixedPath">混合音频文件路径</param>
 public static void AudioMixing(string filePath1, string filePath2, string mixedPath)
 {
     using (var reader1 = new AudioFileReader(filePath1))
         using (var reader2 = new AudioFileReader(filePath2))
         {
             var mixer = new MixingSampleProvider(new[] { reader1, reader2 });
             WaveFileWriter.CreateWaveFile16(mixedPath, mixer);
         }
 }
        private void ProcessAudioFile(string inputFilePath, string outputFilePath)
        {
            using var reader = new AudioFileReader(inputFilePath);

            var mono         = new StereoToMonoSampleProvider(reader);
            var outputFormat = new WaveFormat(OutputRate, mono.WaveFormat.Channels);

            using var resampler = new MediaFoundationResampler(mono.ToWaveProvider(), outputFormat);
            WaveFileWriter.CreateWaveFile16(outputFilePath, resampler.ToSampleProvider());
        }
示例#24
0
文件: shift.cs 项目: Aveax/PPB-Mic
 //Upsampling (wav -> wav)
 public void upsampler(String x, String y)
 {
     Console.WriteLine("UPSAMPLER START");
     using (var reader = new AudioFileReader(x))
     {
         var resampler = new WdlResamplingSampleProvider(reader, outRate);
         WaveFileWriter.CreateWaveFile16(path + y + ".wav", resampler);
     }
     Console.WriteLine("UPSAMPLER END");
 }
示例#25
0
        /// <summary>
        /// Normalizes the specified input file.
        /// </summary>
        /// <param name="inputFile">The input file.</param>
        /// <param name="outputFile">The output file.</param>
        /// <returns>
        /// Path of changed file
        /// </returns>
        public static string Normalize(string inputFile, string outputFile)
        {
            using (var reader = new AudioFileReader(inputFile))
            {
                var provider = new EffectsProvider(reader);
                provider.Normalize(GetMax(inputFile));
                WaveFileWriter.CreateWaveFile16(outputFile, provider);
            }

            return(outputFile);
        }
示例#26
0
        /// <summary>
        /// Begins the fade information.
        /// </summary>
        /// <param name="inputFile">The input file.</param>
        /// <param name="outputFile">The output file.</param>
        /// <param name="duration">The duration.</param>
        /// <returns>
        /// Path of changed file
        /// </returns>
        public static string BeginFadeIn(string inputFile, string outputFile, double duration)
        {
            using (var reader = new AudioFileReader(inputFile))
            {
                var provider = new EffectsProvider(reader);
                provider.BeginFadeIn(duration * 1000);
                WaveFileWriter.CreateWaveFile16(outputFile, provider);
            }

            return(outputFile);
        }
示例#27
0
        /// <summary>
        /// Ends the fade out.
        /// </summary>
        /// <param name="inputFile">The input file.</param>
        /// <param name="outputFile">The output file.</param>
        /// <param name="duration">The duration.</param>
        /// <returns>
        /// Path of changed file
        /// </returns>
        public static string EndFadeOut(string inputFile, string outputFile, double duration)
        {
            using (var reader = new AudioFileReader(inputFile))
            {
                var provider = new EffectsProvider(reader);
                provider.EndFadeOut(duration * 1000, reader.Length / reader.WaveFormat.BlockAlign);
                WaveFileWriter.CreateWaveFile16(outputFile, provider);
            }

            return(outputFile);
        }
 private static void ConvertMp3ToWav(string inPath, string outPath)
 {
     //mp3 file is already mono
     using (var mp3 = new AudioFileReader(inPath))
     {
         //resample to 32kHz
         var resampler = new WdlResamplingSampleProvider(mp3, 32000);
         // and store as 16 bit
         WaveFileWriter.CreateWaveFile16(outPath, resampler);
     }
 }
        private void LoadAudio(SentenceData data)
        {
            var start   = TimeSpan.FromSeconds(data.Start);
            var end     = TimeSpan.FromSeconds(data.End);
            var len     = end - start;
            var trimmed = new AudioFileReader(AudioFile).Skip(start).Take(len);
            var path    = "abc.avi";

            WaveFileWriter.CreateWaveFile16(path, trimmed);
            mAudioService.UploadSentenceAudio(data.Sentence, path);
        }
示例#30
0
        public static string GenerateAudio(ControllerContext context, string captcha)
        {
            var mixed = Path.GetTempFileName();
            var back  = Path.GetTempFileName();
            var main  = Path.GetTempFileName();



            //gera audio principal
            List <String> chars = new List <string>();

            foreach (var item in captcha)
            {
                chars.Add(context.HttpContext.Server.MapPath("~/Content/Audios/" + item.ToString() + ".wav"));
            }
            Concatenate(main, chars, 1000);

            chars = new List <string>();
            //gera audio aleatorio para sujeira
            for (int i = 0; i < 4; i++)
            {
                var randtext = Captcha.GenerateRandomCode(i);
                foreach (var item in randtext)
                {
                    chars.Add(context.HttpContext.Server.MapPath("~/Content/Audios/" + item.ToString() + ".wav"));
                }
            }
            Concatenate(mixed, chars, 0, true);
            ReverseWaveFile(mixed, back);


            using (var reader1 = new WaveFileReader(main))
                using (var reader2 = new WaveFileReader(back))
                {
                    var volumeProvider = new VolumeSampleProvider(reader2.ToSampleProvider());
                    volumeProvider.Volume = 0.15f;

                    var inputs = new List <ISampleProvider>()
                    {
                        reader1.ToSampleProvider(),
                        volumeProvider
                    };


                    var mixer = new MixingSampleProvider(inputs);
                    WaveFileWriter.CreateWaveFile16(mixed, mixer);
                }

            var mp3file = Path.GetTempFileName();

            WavToMp3(mixed, mp3file, context);

            return(mp3file);
        }