/// <summary> /// Gets the sample rate from wave file /// </summary> /// <param name="waveFileName">The path to the wave file</param> /// <returns></returns> private int sampleRate(string waveFileName) { using (var reader = new NAudio.Wave.AudioFileReader(waveFileName)) { return(reader.WaveFormat.SampleRate); } }
//removendo as casas decimais do valor em segundos public string GetDuration(string directory) { string[] duration = new NAudio.Wave.AudioFileReader(directory).TotalTime.ToString().Split(':'); duration[2] = Math.Floor(double.Parse(duration[2], CultureInfo.InvariantCulture)).ToString(); duration[2] = int.Parse(duration[2]) > 9 ? duration[2] : int.Parse(duration[2]) == 0 ? "0" + 1 : "0" + duration[2]; return(string.Join(":", duration)); }
/// <summary> /// Adds file path to database /// </summary> /// <param name="playlistName">Playlist to which file will be bound</param> /// <param name="filePath">File path to be stored</param> public static void AddFileToPlaylist(string playlistName, string filePath) { int playlistID = GetPlaylistID(playlistName); TagLib.File file = TagLib.File.Create(filePath); NAudio.Wave.AudioFileReader audioFile = new NAudio.Wave.AudioFileReader(filePath); string commandString = "INSERT INTO Files (file_path, file_name, duration, song_name, artist, album, year, playlist_id)" + " VALUES (@filepath, @filename, @duration, @songname, @artist, @album, @year, @playlistid);"; using (SqlCommand command = new SqlCommand(commandString, connection)) { try { command.Parameters.Add("@filepath", SqlDbType.VarChar).Value = filePath; command.Parameters.Add("@filename", SqlDbType.VarChar).Value = Path.GetFileNameWithoutExtension(filePath); command.Parameters.Add("@duration", SqlDbType.BigInt).Value = audioFile.TotalTime.Ticks; command.Parameters.Add("@songname", SqlDbType.VarChar).Value = String.IsNullOrEmpty(file.Tag.Title) ? "" : file.Tag.Title; command.Parameters.Add("@artist", SqlDbType.VarChar).Value = String.IsNullOrEmpty(file.Tag.JoinedPerformers) ? "" : file.Tag.JoinedPerformers; command.Parameters.Add("@album", SqlDbType.VarChar).Value = String.IsNullOrEmpty(file.Tag.Album) ? "" : file.Tag.Album; command.Parameters.Add("@year", SqlDbType.Int).Value = file.Tag.Year; command.Parameters.Add("@playlistid", SqlDbType.Int).Value = playlistID; connection.Open(); command.ExecuteNonQuery(); connection.Close(); } catch (Exception e) { connection.Close(); MessageBox.Show(e.Message, "Error trying to insert data"); } } }
//audio processing private int audioProcessTask() { silenceDict.Clear(); using (NAudio.Wave.AudioFileReader wave = new NAudio.Wave.AudioFileReader(tempFiles[currentTempIndex])) { int samplesPerSecond = Convert.ToInt32(Math.Round(wave.WaveFormat.SampleRate * wave.WaveFormat.Channels * sampleLength));; var readBuffer = new float[samplesPerSecond]; int samplesRead; int i = 1; do { samplesRead = wave.Read(readBuffer, 0, samplesPerSecond); if (samplesRead == 0) { break; } var max = readBuffer.Take(samplesRead).Max(); if ((int)(max * 100) > minDecibel) { silenceDict.Add(i, false); } else { silenceDict.Add(i, true); } i++; } while (samplesRead > 0); } return(1); }
public double getRealDuringTime(bool forceReload = false) { if (realDuringTime < 0 || forceReload) { if (System.IO.File.Exists(wavfilename)) { TimeSpan ts; try { using (NAudio.Wave.AudioFileReader audioFileReader = new NAudio.Wave.AudioFileReader(wavfilename)) { ts = audioFileReader.TotalTime; } } catch (Exception) { realDuringTime = 0; return(0); } realDuringTime = ts.TotalSeconds; return(ts.TotalSeconds); } else { realDuringTime = 0; return(0); } } else { return(realDuringTime); } }
private void buttonSelectFile_Click(object sender, EventArgs e) { using (var dialog = new OpenFileDialog()) { dialog.FileName = textBoxFilename.Text; dialog.Filter = "Audio files (*.mp3;*.wma;*.wav)|*.mp3;*.wma;*.wav|All files (*.*)|*.*"; var result = dialog.ShowDialog(); if (result == DialogResult.Cancel) { return; } textBoxFilename.Text = dialog.FileName; } try { using (var reader = new NAudio.Wave.AudioFileReader(FileName)) { fileLengthSeconds = (int)reader.TotalTime.TotalSeconds; } } catch (Exception ex) { fileLengthSeconds = 0; textBoxFilename.Text = ""; MessageBox.Show(ex.Message, "Cannot open file", MessageBoxButtons.OK, MessageBoxIcon.Error); } UpdateLabels(); }
private static void normalizeWAV(string inputFile) { string tmpFile = inputFile.Substring(0, inputFile.Length - 4) + "_normalized" + Speaker.AudioFileExtension; try { //float max = 0; using (NAudio.Wave.AudioFileReader reader = new NAudio.Wave.AudioFileReader(inputFile)) { float max = getMaxPeak(inputFile); if (Mathf.Abs(max) < Common.Util.BaseConstants.FLOAT_TOLERANCE || max > 1f) { Debug.LogWarning("File cannot be normalized!"); } else { // rewind and amplify reader.Position = 0; reader.Volume = 1f / max; // write out to a new WAV file //NAudio.Wave.WaveFileWriter.CreateWaveFile16(inputFile, reader); NAudio.Wave.WaveFileWriter.CreateWaveFile16(tmpFile, reader); } } //System.IO.File.Delete(tmpFile); } catch (System.Exception ex) { Debug.LogError("Could not normalize audio file: " + ex); } }
private void stopped(object sender, EventArgs e) { NAudio.Wave.AudioFileReader reader = new NAudio.Wave.AudioFileReader(File); NAudio.Wave.WaveOutEvent output = (NAudio.Wave.WaveOutEvent)sender; output.Init(reader); output.Play(); }
private static float getMaxPeak(string inputFile) { float max = 0; try { using (NAudio.Wave.AudioFileReader reader = new NAudio.Wave.AudioFileReader(inputFile)) { // find the max peak float[] buffer = new float[reader.WaveFormat.SampleRate]; int read; do { read = reader.Read(buffer, 0, buffer.Length); for (int ii = 0; ii < read; ii++) { float abs = Mathf.Abs(buffer[ii]); if (abs > max) { max = abs; } } } while (read > 0); } } catch (System.Exception ex) { Debug.LogError("Could not find the max peak in audio file: " + ex); } return(max); }
static void ConvertToMP3(string sourceFilename, string targetFilename) { using (var reader = new NAudio.Wave.AudioFileReader(sourceFilename)) using (var writer = new NAudio.Lame.LameMP3FileWriter(targetFilename, reader.WaveFormat, NAudio.Lame.LAMEPreset.STANDARD)) { reader.CopyTo(writer); } }
public void Alert() { using (var audioFile = new NAudio.Wave.AudioFileReader(@"./Bensound-moose.wav")) using (var outputDevice = new NAudio.Wave.WaveOutEvent()) { outputDevice.Init(audioFile); outputDevice.Play(); while (outputDevice.PlaybackState == NAudio.Wave.PlaybackState.Playing) { System.Threading.Thread.Sleep(1000); } } }
private SortedList <string, double> ReadMediaLength(List <string> files) { SortedList <string, double> audiobook_files = new SortedList <string, double>(); files.Sort(); foreach (string s in files) { Debug.WriteLine("Trying to get media information from " + s); NAudio.Wave.AudioFileReader reader = new NAudio.Wave.AudioFileReader(s); audiobook_files.Add(s, reader.TotalTime.TotalSeconds); } return(audiobook_files); }
public void Play() { NAudio.Wave.AudioFileReader reader = new NAudio.Wave.AudioFileReader(File); NAudio.Wave.WaveOutEvent output = new NAudio.Wave.WaveOutEvent { Volume = Volume }; output.Init(reader); if (Looping) { output.PlaybackStopped += stopped; } output.Play(); }
private static void WmaToMp3(XConvertJob param) { var targetFilename = param.SourceFileName.GenerateOutPutPath(XFileType.Mp3); if (param.SourceData != null) { File.WriteAllBytes(param.SourceFileName, param.SourceData); } using (var reader = new NAudio.Wave.AudioFileReader(param.SourceFileName)) using (var writer = new NAudio.Lame.LameMP3FileWriter(targetFilename, reader.WaveFormat, NAudio.Lame.LAMEPreset.STANDARD)) { reader.CopyTo(writer); } param.ResulFileName = targetFilename; }
public static (double[] audio, int sampleRate) ReadWAV(string filePath, double multiplier = 16_000) { using var afr = new NAudio.Wave.AudioFileReader(filePath); int sampleRate = afr.WaveFormat.SampleRate; int sampleCount = (int)(afr.Length / afr.WaveFormat.BitsPerSample / 8); int channelCount = afr.WaveFormat.Channels; var audio = new List <double>(sampleCount); var buffer = new float[sampleRate * channelCount]; int samplesRead = 0; while ((samplesRead = afr.Read(buffer, 0, buffer.Length)) > 0) { audio.AddRange(buffer.Take(samplesRead).Select(x => x * multiplier)); } return(audio.ToArray(), sampleRate); }
private void Import(string inputFilePath, string outputFilePath, float tapeImportPosition, IProgress <float> progress = null) { byte[] buffer = new byte[1024 * 128 * 2]; Utils.WAVFile outputWavFile = Utils.WAVFile.Load(outputFilePath); try { long byteImportPosition = outputWavFile.dataOffsetBytes + (long)(Common.WaveFormat.SampleRate * tapeImportPosition) * (Common.WaveFormat.BitsPerSample / 8) * Common.WaveFormat.Channels; outputWavFile.stream.Seek(byteImportPosition, SeekOrigin.Begin); using (var reader = new NAudio.Wave.AudioFileReader(inputFilePath)) using (var tempConverter = new NAudio.Wave.Wave32To16Stream(reader)) using (var converter = new NAudio.Wave.WaveFormatConversionStream(Common.WaveFormat, tempConverter)) { int readCount = 0; int stepCount = 100; int step = 0; int stepSize = (int)(reader.Length / stepCount); int nextStep = 0; do { readCount = converter.Read(buffer, 0, buffer.Length); readCount = (int)Math.Min(readCount, outputWavFile.stream.Length - outputWavFile.stream.Position); outputWavFile.stream.Write(buffer, 0, readCount); if (progress != null && reader.Position >= nextStep) { nextStep += stepSize; progress.Report(step / (float)stepCount); step++; } }while (readCount > 0); } } finally { outputWavFile.Close(); } }
public DemoPlayable() { file = TagLib.File.Create(path); reader = new NAudio.Wave.AudioFileReader(path); waveOut = new NAudio.Wave.WaveOut() { Volume = 0.2F }; waveOut.Init(reader); var tag = file.Tag; Title = tag.Title; Duration = file.Properties.Duration; }
public static void ProcessFile(string fileName) { try { string fileExt = System.IO.Path.GetExtension(fileName.ToLower()); if (fileExt.Contains("mp3")) { using (NAudio.Wave.Mp3FileReader rdr = new NAudio.Wave.Mp3FileReader(fileName)) { //var newFormat = new NAudio.Wave.WaveFormat(48000, 16, 1); var newFormat = new NAudio.Wave.WaveFormat(16000, 16, 1); using (var conversionStream = new NAudio.Wave.WaveFormatConversionStream(newFormat, rdr)) { if (System.IO.File.Exists("mdc1200tmp.wav")) { System.IO.File.Delete("mdc1200tmp.wav"); } NAudio.Wave.WaveFileWriter.CreateWaveFile("mdc1200tmp.wav", conversionStream); } } } else { using (NAudio.Wave.WaveFileReader rdr = new NAudio.Wave.WaveFileReader(fileName)) { var newFormat = new NAudio.Wave.WaveFormat(16000, 16, 1); using (var conversionStream = new NAudio.Wave.WaveFormatConversionStream(newFormat, rdr)) { if (System.IO.File.Exists("mdc1200tmp.wav")) { System.IO.File.Delete("mdc1200tmp.wav"); } NAudio.Wave.WaveFileWriter.CreateWaveFile("mdc1200tmp.wav", conversionStream); } } } using (NAudio.Wave.AudioFileReader rdr = new NAudio.Wave.AudioFileReader("mdc1200tmp.wav")) { ProcessProvider(rdr, fileName); } } catch (Exception ex) { Console.WriteLine("Process File Exception: {0}", ex.Message); } }
public static void ProcessFile(string fileName) { try { string fileExt = System.IO.Path.GetExtension(fileName.ToLower()); if (fileExt.Contains("mp3")) { using (NAudio.Wave.Mp3FileReader rdr = new NAudio.Wave.Mp3FileReader(fileName)) { //var newFormat = new NAudio.Wave.WaveFormat(48000, 16, 1); var newFormat = new NAudio.Wave.WaveFormat(16000, 16, 1); using (var conversionStream = new NAudio.Wave.WaveFormatConversionStream(newFormat, rdr)) { if (System.IO.File.Exists("mdc1200tmp.wav")) System.IO.File.Delete("mdc1200tmp.wav"); NAudio.Wave.WaveFileWriter.CreateWaveFile("mdc1200tmp.wav", conversionStream); } } } else { using (NAudio.Wave.WaveFileReader rdr = new NAudio.Wave.WaveFileReader(fileName)) { var newFormat = new NAudio.Wave.WaveFormat(16000, 16, 1); using (var conversionStream = new NAudio.Wave.WaveFormatConversionStream(newFormat, rdr)) { if (System.IO.File.Exists("mdc1200tmp.wav")) System.IO.File.Delete("mdc1200tmp.wav"); NAudio.Wave.WaveFileWriter.CreateWaveFile("mdc1200tmp.wav", conversionStream); } } } using (NAudio.Wave.AudioFileReader rdr = new NAudio.Wave.AudioFileReader("mdc1200tmp.wav")) { ProcessProvider(rdr, fileName); } } catch (Exception ex) { Console.WriteLine("Process File Exception: {0}", ex.Message); } }
/// <summary> /// 노래 다운로드 (사운드만 추출해서 다운) /// </summary> /// <param name="videoId">비디오 고유 아이디</param> /// <param name="videoName">비디오 제목</param> public async void Download(string videoId, string videoName) { try { var youtube = new YoutubeClient(); var streamManifest = await youtube.Videos.Streams.GetManifestAsync(videoId); var streamInfo = streamManifest.GetAudioOnly().WithHighestBitrate(); Regex pattern = new Regex(@"[\/:*?<>|]"); videoName = pattern.Replace(videoName, string.Empty); string path = AppDomain.CurrentDomain.BaseDirectory + @"playlist\"; if (streamInfo != null) { await youtube.Videos.Streams.DownloadAsync(streamInfo, path + videoName + ".webm"); await Task.Run(() => { using (var reader = new NAudio.Wave.AudioFileReader(path + videoName + ".webm")) { using (var writer = new NAudio.Lame.LameMP3FileWriter(path + videoName + ".prepareMp3", reader.WaveFormat, NAudio.Lame.LAMEPreset.STANDARD)) { reader.CopyTo(writer); } } // 변환 도중에 사용자가 음악 재생을 클릭했을때 IOException이 나는것을 방지하기 위해 // 확장명을 일부러 다르게 써서 mp3 파일로 변환이 끝나면 확장명을 바꿔준다. File.Move(path + videoName + ".prepareMp3", path + videoName + ".mp3"); File.Delete(path + videoName + ".webm"); File.Delete(path + videoName + ".prepareMp3"); }); } } catch { alert(); } }
//TODO document! public void Normalize(string inputFile) { #if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN string tmpFile = inputFile.Substring(0, inputFile.Length - 4) + "_normalized" + Speaker.AudioFileExtension; try { //float max = 0; using (NAudio.Wave.AudioFileReader reader = new NAudio.Wave.AudioFileReader(inputFile)) { float max = GetMaxPeak(inputFile); if (max == 0 || max > 1f) { Debug.LogWarning("File cannot be normalized!"); } else { // rewind and amplify reader.Position = 0; reader.Volume = 1f / max; // write out to a new WAV file //NAudio.Wave.WaveFileWriter.CreateWaveFile16(inputFile, reader); NAudio.Wave.WaveFileWriter.CreateWaveFile16(tmpFile, reader); } } //System.IO.File.Delete(tmpFile); } catch (System.Exception ex) { Debug.LogError("Could not normalize audio file: " + ex); } #else Debug.LogError("Can only normalize WAV audio files under Windows standalone!"); #endif }
//TODO document! public float GetMaxPeak(string inputFile) { #if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN float max = 0; try { using (NAudio.Wave.AudioFileReader reader = new NAudio.Wave.AudioFileReader(inputFile)) { // find the max peak float[] buffer = new float[reader.WaveFormat.SampleRate]; int read; do { read = reader.Read(buffer, 0, buffer.Length); for (int ii = 0; ii < read; ii++) { float abs = Mathf.Abs(buffer[ii]); if (abs > max) { max = abs; } } } while (read > 0); } } catch (System.Exception ex) { Debug.LogError("Could not find the max peak in audio file: " + ex); } return(max); #else Debug.LogWarning("Can only find max peak from WAV audio files under Windows standalone!"); return(1f); #endif }
public PlayAudioUpdatePositionEventArgs(NAudio.Wave.AudioFileReader audio) { AudioReader = audio; }
public void StartRending(System.IO.DirectoryInfo baseTempDir, List <VocalUtau.Calculators.BarkerCalculator.BgmPreRender> BList, string RendToWav = "") { _IsRending = true; _ExitRending = false; if (RendingStateChange != null) { RendingStateChange(this); } string ProcessIDStr = Process.GetCurrentProcess().Id.ToString(); DirectoryInfo tempDir = baseTempDir.CreateSubdirectory("temp"); DirectoryInfo cacheDir = baseTempDir.CreateSubdirectory("cache"); string TrackFileName = tempDir.FullName + "\\Bgm_" + CacheSignal + ".wav"; FileStream Fs; headSize = InitFile(out Fs, TrackFileName); Semaphore semaphore = new Semaphore(1, 1, "VocalUtau.WavTool." + ProcessIDStr + ".Bgm_" + CacheSignal); for (int i = 0; i < BList.Count; i++) { if (BList[i].DelayTime > 0) { int ByteTime = (int)(IOHelper.NormalPcmMono16_Format.AverageBytesPerSecond * BList[i].DelayTime); ByteTime -= ByteTime % 2; byte[] byteL = new byte[ByteTime]; Array.Clear(byteL, 0, ByteTime); Fs.Write(byteL, 0, ByteTime); } semaphore.WaitOne(); try { int ByteTime = (int)(IOHelper.NormalPcmMono16_Format.AverageBytesPerSecond * BList[i].PassTime); ByteTime -= ByteTime % 2; using (NAudio.Wave.AudioFileReader reader = new NAudio.Wave.AudioFileReader(BList[i].FilePath)) { int JumpLoops = ByteTime / 2; using (NAudio.Wave.Wave32To16Stream w16 = new NAudio.Wave.Wave32To16Stream(reader)) { using (NAudio.Wave.WaveStream wfmt = new NAudio.Wave.BlockAlignReductionStream(w16)) { using (NAudio.Wave.WaveStream wout = new NAudio.Wave.WaveFormatConversionStream(IOHelper.NormalPcmMono16_Format, wfmt)) { while (wout.Position < wout.Length) { if (_ExitRending) { break; } byte[] by = new byte[2]; int rd = wout.Read(by, 0, 2); if (JumpLoops > 0) { JumpLoops--; } else { Fs.Write(by, 0, 2); } /* for (int w = 1; w < w16.WaveFormat.Channels; w++) * { * int rdr = w16.Read(by, 0, 2); * }*/ } } } } } } catch {; } Fs.Flush(); semaphore.Release(); if (_ExitRending) { break; } } _IsRending = false; long total = Fs.Length; byte[] head = IOHelper.GenerateHead((int)(total - headSize)); Fs.Seek(0, SeekOrigin.Begin); Fs.Write(head, 0, head.Length); Fs.Flush(); Fs.Close(); _ExitRending = false; if (RendingStateChange != null) { RendingStateChange(this); } if (RendToWav != "") { File.Copy(TrackFileName, RendToWav, true); try { File.Delete(TrackFileName); } catch {; } } }