示例#1
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");
        }
示例#2
0
 public void Reset()
 {
     if (reader == null)
     {
         return;
     }
     if (player.PlaybackState != PlaybackState.Stopped)
     {
         player.Stop();
     }
     reader.Close();
     reader = null;
     tmrRefresh.Stop();
 }
示例#3
0
        private void button4_Click(object sender, EventArgs e) //next track
        {
            waveOutDevice.Stop();
            audioFileReader.Close();
            if ((trackNumber + 1) < paths.Count)
            {
                trackNumber++;
            }
            else
            {
                trackNumber = 0;
            }

            playTrack();
        }
        public void API(string filePath)
        {
            AudioFileReader audioFile    = null;
            WaveOutEvent    outputDevice = null;

            try
            {
                audioFile    = new AudioFileReader(filePath);
                outputDevice = new WaveOutEvent();

                outputDevice.Init(audioFile);
                outputDevice.Play();

                Console.ReadKey(true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                outputDevice.Stop();
                outputDevice.Dispose();
                audioFile.Close();
                audioFile.Dispose();
            }
        }
示例#5
0
        public void PlayOneSong()
        {
            AudioFileReader audioFile    = null;
            WaveOutEvent    outputDevice = null;

            try
            {
                string audioFilePath = @"C:\Users\DJTom\OneDrive\Plocha\20201007_hodina\SongsAndVotesSol\Resources\Peter_Nemec_-_Future_Life_OFFICIAL_LYRICS_VIDEO_1.mp3";
                audioFile    = new AudioFileReader(audioFilePath);
                outputDevice = new WaveOutEvent();

                outputDevice.Init(audioFile);
                outputDevice.Play();

                Console.ReadKey(true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadKey(true);
            }
            finally
            {
                if (outputDevice != null)
                {
                    outputDevice.Stop();
                    outputDevice.Dispose();
                }
                if (audioFile != null)
                {
                    audioFile.Close();
                    audioFile.Dispose();
                }
            }
        }
示例#6
0
        private void MixTwoSamples()
        {
            while (writer == null && RecordedAudioWriter == null)
            {
            }

            Thread.Sleep(1000);

            MicFileReader     = new AudioFileReader(saveDirectory.SelectedPath + "\\" + micRecordFIleName);
            SpeakerFileReader = new AudioFileReader(saveDirectory.SelectedPath + "\\" + playBackRecordFileName);

            WaveMixerStream32 mixer = new WaveMixerStream32();

            mixer.AddInputStream(MicFileReader);
            mixer.AddInputStream(SpeakerFileReader);

            WaveFileWriter.CreateWaveFile(saveDirectory.SelectedPath + "\\" + "result.wav", mixer);

            MicFileReader.Close();
            MicFileReader.Dispose();
            MicFileReader = null;

            SpeakerFileReader.Close();
            SpeakerFileReader.Dispose();
            SpeakerFileReader = null;
        }
示例#7
0
        /// <summary>
        /// 获取时间戳
        /// </summary>
        /// <param name="sound_path"></param>
        /// <param name="word_path"></param>
        /// <param name="language"></param>
        /// <param name="splitTime"></param>
        public void GetTimeSpan(string sound_path, string word_path, string language, double splitTime = 1.5)
        {
            var inputStream = new AudioFileReader(sound_path);

            try
            {
                if (sound_path.Contains(".mp3"))
                {
                    sound_path = NAudioHelper.GetWavPath(sound_path);
                }
                WAVReader reader = new WAVReader();
                reader.GetTimeSpan(sound_path, out voicePoint, out voiceMilliSecond, splitTime);
                if (voicePoint.Count % 2 != 0)//voicePoint是为了截取小音频
                {
                    voicePoint.Add(inputStream.TotalTime);
                }
                int _name = 1;//命名
                for (int i = 0; i < voicePoint.Count; i += 2)
                {
                    GetBaiduSpeech(voicePoint[i], voicePoint[i + 1], sound_path, _name, language, splitTime);
                    ++_name;
                }
                //开始比对
                //获取文档内容
                CompareText(word_path, language);
                //通过时间戳集合去匹配路径与歌词文本(百度不准)
                for (int i = 0; i < voiceMilliSecond.Count; i++)
                {
                    MusicResult result = new MusicResult();
                    result.timeSpan = voiceMilliSecond[i];
                    string url = voiceFiles[i];
                    if (url == "")                                                                    //上传失败,重新上传
                    {
                        string fileName  = Path.GetFileNameWithoutExtension(sound_path) + i + ".wav"; //重命名文件
                        string newFolder = System.AppDomain.CurrentDomain.BaseDirectory + "NewSoundFiles/" + Path.GetFileNameWithoutExtension(sound_path) + "/";
                        string newFile   = newFolder + fileName;
                        //绝对路径
                        string path_absolute = context.Server.MapPath("/NewSoundFiles/" + Path.GetFileNameWithoutExtension(sound_path) + "/" + fileName);
                        result.fileUrl = UploadFile.PostFile(path_absolute);
                    }
                    else
                    {
                        result.fileUrl = i < voiceFiles.Count ? voiceFiles[i] : "";
                    }

                    result.text = i < baiduText.Count ? baiduText[i] : "未匹配上字符串";
                    return_list.Add(result);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex.Message);
            }
            finally
            {
                inputStream.Close();
                inputStream.Dispose();
                isFinish = true;
            }
        }
示例#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
 private void RefreshAudios()
 {
     try
     {
         var folder = new DirectoryInfo(AUDIOFOLDER);
         lstAudioLocal.BeginUpdate();
         lstAudioLocal.Items.Clear();
         foreach (var info in folder.EnumerateFiles())
         {
             var item = new ListViewItem {
                 Name = info.FullName, Text = info.Name, Group = lstAudioLocal.Groups[2]
             };
             try
             {
                 var reader = new AudioFileReader(info.FullName);
                 if (info.Extension.Equals(RINGTONEEXTENSION))
                 {
                     item.ImageKey = "ringtone_local";
                     item.Group    = lstAudioLocal.Groups[0];
                 }
                 else
                 {
                     item.ImageKey = "audio";
                     item.Group    = lstAudioLocal.Groups[1];
                 }
                 reader.Close();
             }
             catch { }
             lstAudioLocal.Items.Add(item);
         }
         lstAudioLocal.EndUpdate();
     }
     catch (Exception ex) { HandleException(ex); }
 }
示例#10
0
        private void button4_Click(object sender, EventArgs e)
        {
            synth.SelectVoice(ddlVoices.SelectedItem.ToString());
            if (audioFile != null)
            {
                audioFile.Close();
            }
            synth.SpeakAsyncCancelAll();
            Thread.Sleep(1000);
            Console.WriteLine("Redirecting output");
            synth.SetOutputToWaveFile("temp.wav");
            Console.WriteLine("Speaking text...");
            synth.Speak(rtfText.Text);
            Console.WriteLine("Done speaking text");
            synth.SetOutputToNull();
            Console.WriteLine("Done setting output to null");
            SaveFileDialog ofd = new SaveFileDialog();

            ofd.Filter = "Text files (*.mp3)|*.mp3|All files (*.*)|*.*";
            ofd.ShowDialog();
            using (var reader = new AudioFileReader("temp.wav"))
                using (var writer = new LameMP3FileWriter(ofd.FileName, reader.WaveFormat, LAMEPreset.ABR_128))
                    reader.CopyTo(writer);
            LastSavedFile = ofd.FileName;
        }
示例#11
0
 private void HandleFile(string filename)
 {
     try
     {
         FileInfo file = new FileInfo(filename);
         string   path = System.IO.Path.Combine(file.Directory.FullName, "output");
         if (!Directory.Exists(path))
         {
             Directory.CreateDirectory(path);
         }
         AudioFileReader waveFileReader      = new AudioFileReader(filename);
         int             bytesPerMillisecond = waveFileReader.WaveFormat.AverageBytesPerSecond / 1000;
         int             startPos            = GetSilenceTime(waveFileReader, SilenceLocation.Start, config.Config.SilenceThreshold);
         int             endPos2             = GetSilenceTime(waveFileReader, SilenceLocation.End, config.Config.SilenceThreshold);
         endPos2 -= endPos2 % 4;
         WaveFileWriter waveFileWriter = new WaveFileWriter(filename + ".temp.wav", waveFileReader.WaveFormat);
         TrimSound(waveFileReader, waveFileWriter, startPos, endPos2);
         byte[] temp = new byte[bytesPerMillisecond * 500];
         waveFileWriter.Write(temp, 0, temp.Length);
         waveFileWriter.Close();
         waveFileReader.Close();
         WaveFileReader           filereader = new WaveFileReader(filename + ".temp.wav");
         WaveFormat               format     = new WaveFormat(8000, 16, 1);
         MediaFoundationResampler resample   = new MediaFoundationResampler(filereader, format);
         WaveFileWriter.CreateWaveFile(System.IO.Path.Combine(path, file.Name.Replace(file.Extension, ".wav")), resample);
         resample.Dispose();
         filereader.Close();
         File.Delete(filename + ".temp.wav");
     }
     catch (Exception)
     {
     }
 }
        private void OnButtonDeleteClick(object sender, EventArgs e)
        {
            if (listBoxRecordings.SelectedItem != null)
            {
                try
                {
                    if (writer != null)
                    {
                        writer.Close();
                        writer.Dispose();
                        writer = null;
                    }
                    if (afr != null)
                    {
                        afr.Close();
                        afr.Dispose();
                        afr = null;
                    }

                    File.Delete(Path.Combine(outputFolder, (string)listBoxRecordings.SelectedItem));
                    listBoxRecordings.Items.Remove(listBoxRecordings.SelectedItem);

                    if (listBoxRecordings.Items.Count > 0)
                    {
                        listBoxRecordings.SelectedIndex = 0;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Could not delete recording: {ex}");
                }
            }
        }
示例#13
0
 /// <summary>
 /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
 /// </summary>
 public void Dispose()
 {
     RemoveInput();
     inputStream.Close();
     try { inputStream.Dispose(); }
     catch (NullReferenceException) { Trace.WriteLine("Caught NullReferenceException in NAudioChannel.Dispose() => inputStream.Dispose() (Is this a bug?)"); }
 }
示例#14
0
        /// <summary>
        /// 노래 정보 업데이트 후 재생
        /// </summary>
        public void UpdateMedia(string songName)
        {
            App.Current.Dispatcher.Invoke(() =>
            {
                if (waveOut != null)
                {
                    waveOut.Dispose();
                }
                if (audioReader != null)
                {
                    audioReader.Dispose(); audioReader.Close();
                }


                audioReader = new AudioFileReader(AppDomain.CurrentDomain.BaseDirectory + @"playlist\" + songName);

                audioReader.Volume = SongInfo.Volume / 100;

                DisplayInfo.NowSong       = songName;
                DisplayInfo.ButtonImage   = (ImageSource)c.ConvertFrom("./Resource/stop.png");
                DisplayInfo.PlayModeImage = (ImageSource)c.ConvertFrom("./Resource/shuffle.png");

                DisplayInfo.SliderLength = audioReader.TotalTime.TotalSeconds;

                SongInfo.TotalLength = audioReader.TotalTime;
                SongInfo.IsRun       = true;
                waveOut = new WaveOut();

                waveOut.Init(audioReader);
                waveOut.Play();
            });
        }
示例#15
0
        /// <summary>
        /// 停止播放
        /// </summary>
        /// <param name="e"></param>
        /// <param name="sound_path">音频路径</param>
        /// <param name="word_path">文档路径</param>
        /// <param name="language">语言</param>
        /// <param name="splitTime">间隔时间</param>
        private void PlaybackStopped(StoppedEventArgs e, string sound_path, string word_path, string language, out bool isFinish, double splitTime, AudioFileReader reader, IWavePlayer playbackDevice)
        {
            //最后的结束时间
            if (voicePoint.Count % 2 != 0)
            {
                voicePoint.Add(reader.TotalTime);
            }
            int _name = 1;//命名

            for (int i = 0; i < voicePoint.Count; i += 2)
            {
                GetBaiduSpeech(voicePoint[i], voicePoint[i + 1], sound_path, _name, language, splitTime);
                ++_name;
            }
            //开始比对
            //获取文档内容
            CompareText(word_path, language);
            reader.Close();
            reader.Dispose();
            if (playbackDevice != null)
            {
                playbackDevice.Stop();
            }
            isFinish = true;
        }
示例#16
0
 public void Dispose()
 {
     if (reader != null)
     {
         reader.Dispose();
         reader.Close();
         reader = null;
     }
 }
示例#17
0
 public void Stop()
 {
     if (waveOutDevice != null)
     {
         waveOutDevice.Stop();
         waveOutDevice = null;
         audioFileReader.Close();
         audioFileReader = null;
     }
 }
示例#18
0
        private void voiceStop()
        {
            // stop playback
            player.Stop();
            // finalise the WAV file
            //savingWaveProvider.Dispose();

            player.Dispose();
            afr.Close();
            Console.WriteLine("Voice stop.");
        }
示例#19
0
        public bool makeLoud(string inPath, string outPath)
        {
            if (lvlLoud == 50 && !this.przester)
            {
                return(false);
            }

            float max = 0;

            AudioFileReader reader = new AudioFileReader(inPath);

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

            do
            {
                read = reader.Read(buffer, 0, buffer.Length);
                for (int n = 0; n < read; n++)
                {
                    var abs = Math.Abs(buffer[n]);
                    if (abs > max)
                    {
                        max = abs;
                    }
                }
            } while (read > 0);

            if (max == 0 || max > 1.0f)
            {
                throw new InvalidOperationException("File cannot be normalized");
            }

            // rewind and amplify
            reader.Position = 0;
            if (this.przester)
            {
                reader.Volume = 1.0f / (max * (lvlLoud / 100));
            }
            else
            {
                reader.Volume = 1.0f / (max * (100 / (float)lvlLoud));
            }

            // write out to a new WAV file
            WaveFileWriter.CreateWaveFile16(outPath, reader);
            reader.Close();

            return(true);
        }
        private void btnPlay_Click(object sender, EventArgs e)
        {
            if (waveOutDevice != null && waveOutDevice.PlaybackState == PlaybackState.Playing)
            {
                if (waveOutDevice != null)
                {
                    waveOutDevice.Stop();
                    waveOutDevice = null;
                }

                if (audioFileReader != null)
                {
                    audioFileReader.Close();
                    audioFileReader = null;
                }

                // change to play icon
                this.btnPlay.ImageIndex = 0;
            }
            else
            {
                try {
                    waveOutDevice   = new WaveOut();
                    audioFileReader = new AudioFileReader(filePath);
                    waveOutDevice.Init(audioFileReader);
                    waveOutDevice.PlaybackStopped += onPlaybackStopped;
                    waveOutDevice.Play();

                    // change to stop icon
                    this.btnPlay.ImageIndex = 2;
                } catch (Exception ex) {
                    Console.WriteLine(ex.Message);
                    MessageBox.Show("Could not play the selected sound.", Program.APP_NAME, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
示例#21
0
        private static void finishPlayback()
        {
            if (wavePlayer != null)
            {
                wavePlayer.Stop();
            }

            if (audioFileReader != null)
            {
                audioFileReader.Close();
                audioFileReader = null;
            }
            nowPlayingTrack  = string.Empty;
            currentlyPlaying = false;
        }
示例#22
0
        public void Close()
        {
            if (!IsOpen)
            {
                return;
            }

            fileReader.Close();
            fileReader.Dispose();
            fileReader = null;

            read = null;

            IsOpen = false;
        }
示例#23
0
 public void Reset()
 {
     if (reader == null)
     {
         return;
     }
     if (player.PlaybackState != PlaybackState.Stopped)
     {
         player.Stop();
     }
     reader.Close();
     reader       = null;
     lblTime.Text = string.Empty;
     tmrRefresh.Stop();
 }
示例#24
0
        //Plays a selection of media
        private void PlayClip(int index)
        {
            waveOut.Stop();
            reader.Close();

            reader  = new AudioFileReader(fileDirectory + currentSong + ".mp3");
            waveOut = new WaveOut();
            waveOut.Init(reader);

            provider        = reader.ToSampleProvider(); //Here I get the samples
            reader.Position = 0;                         //Go to the position 0 after reading the samples

            waveOut.Play();
            NowPlaying.Text = "Now Playing: " + currentSong;
            PlayBtn.Text    = "Pause";
        }
示例#25
0
        private static void Close()
        {
            if (fileReader != null)
            {
                fileReader.Close();
                fileReader.Dispose();
                fileReader = null;

                read = null;
            }

            if (current != null)
            {
                current.Dispose();
                current = null;
            }
        }
示例#26
0
 private void CloseWaveOut()
 {
     if (waveOut != null)
     {
         waveOut.Stop();
         waveOut.Dispose();
     }
     if (audioFileReader != null)
     {
         // this one really closes the file and ACM conversion
         audioFileReader.Close();
         audioFileReader.Dispose();
         //setVolumeDelegate = null;
         //audioFileReader = null;
     }
     sampleProvider = null;
 }
示例#27
0
 public static void Load(String path)
 {
     try
     {
         audioFile.Close();
     }
     catch (NullReferenceException) { }
     try
     {
         Console.WriteLine(path.ToString());
         audioFile = new AudioFileReader(path.ToString());
         wave.Init(audioFile);
     }
     catch (Exception e) {
         Console.WriteLine(e.Message);
     }
 }
示例#28
0
        public AudioPlayer(string url, bool loop = false, float?volum = null)
        {
            if (volum == null)
            {
                volum = SharedSetting.BGMVolum;
            }
            PlayThread = new Thread(() =>
            {
                string path_rele = PackStream.Locate(url);
                var audioFile    = new AudioFileReader(path_rele);
                outputDevice     = new WaveOutEvent();
                outputDevice.Init(audioFile);
                outputDevice.Volume = (float)volum;
                do
                {
                    outputDevice.Play(); // 异步执行
                    while (outputDevice.PlaybackState == PlaybackState.Playing)
                    {
                        Thread.Sleep(100);
                        if (!canplay)
                        {
                            break;
                        }
                    }
                    outputDevice.Stop();
                    audioFile.Seek(0, SeekOrigin.Begin);
                } while (loop && canplay);

                outputDevice.Dispose();
                audioFile.Close();
                audioFile.Dispose();
                try
                {
                    File.Delete(path_rele);
                }
                catch
                {
                }
            })
            {
                IsBackground = true
            };
            PlayThread.Start();
        }
示例#29
0
        //음악재생에 사용되는 서브스레드 함수
        static void play_music(object filename)
        {
            //하드디스크에 저장된 음악파일을 로드하는 객체 생성
            AudioFileReader audioFile = new AudioFileReader((string)filename);

            //스피커에 음악파일을 출력할 때 사용하는 객체 생성
            using (WaveOutEvent wave = new WaveOutEvent())
            {
                //재생할 음악파일 객체를 설정
                wave.Init(audioFile);
                wave.Play(); //설정된 음악파일 재생
                //음악파일을 모두 재생할 때 까지 대기
                while (source.IsCancellationRequested == false && wave.PlaybackState == PlaybackState.Playing)
                {
                    Thread.Sleep(500);
                }
            }
            audioFile.Close();
        }
示例#30
0
        private void stopButton__Click(object sender, EventArgs e)
        {
            Debug.Assert(audioPlayer_ != null);
            Debug.Assert(thread_ != null);

            isPlaying_ = false;
            thread_.Join();
            thread_ = null;

            audioPlayer_.Stop();
            audioPlayer_ = null;

            audioReader_.Close();
            audioReader_ = null;

            deviceComboBox_.Enabled   = true;
            selectFileButton_.Enabled = true;
            stopButton_.Enabled       = false;

            playOrPauseButton_.Text = "Play";
        }