Class for reading from MP3 files
Inheritance: WaveStream
    protected void FileSelected(string path)
    {
        fileBrowser = null;

        if (path != null)
        {
            Debug.Log(path);
            if(path.Contains(".mp3"))
            {
                Debug.Log(path);
                using (Mp3FileReader reader = new Mp3FileReader(path))
                {
                    Debug.Log("Reached");
                    path = path.Replace(".mp3", ".wav");
                    WaveFileWriter.CreateWaveFile(path , reader);
                }
            }
            path = "file://" + path;
            WWW wtf = new WWW(path);

            //Wait for wtf to finish
            while (!wtf.isDone)
            {
            }
            SceneManager.getInstance.setClip(wtf.GetAudioClip(false));
        }
    }
Exemplo n.º 2
0
        public TestSpeed()
        {
            //WaveStream str1 = new Mp3FileReader("C:\\Users\\mtemkine\\Desktop\\snd\\guitar1.mp3");
            //WaveStream str2 = new Mp3FileReader("C:\\Users\\mtemkine\\Desktop\\snd\\molecules.mp3");
            //WaveMixerStream32 mix = new WaveMixerStream32(new [] {str1, str2}, false);

            var mp3Filename = @"C:\WS\jmerde\trunk\_VisualStudio\AudioBooker\IlyaFranker\Content\snd\ilyafrank_open.mp3";

            WavComposite writer = new WavComposite("../../wawa.wav");

            writer.AppendAllOfFile(mp3Filename, null);
            writer.AppendAllOfFile(mp3Filename, 2);
            writer.AppendAllOfFile(mp3Filename, 0.5);
            writer.Close();

            //format = readerWave.WaveFormat;
            //writer = new WaveFileWriter(destFilename, format);
            //var wave = new Mp3FileReader(mp3Filename);

            using (var reader = new Mp3FileReader(mp3Filename))
            using (var pcmStream = WaveFormatConversionStream.CreatePcmStream(reader))
            using (var downsampledStream = new WaveFormatConversionStream(new WaveFormat(
                (int)(pcmStream.WaveFormat.SampleRate * 1.5),
                reader.WaveFormat.BitsPerSample,
                reader.WaveFormat.Channels), pcmStream))
            {

                WaveFileWriter.CreateWaveFile("../../xello.wav", downsampledStream);
            }
        }
Exemplo n.º 3
0
 private static void ConvertMp3ToWav(string sourceFile, string desFile)
 {
     using var reader =
               new NAudio.Wave.Mp3FileReader(sourceFile);
     NAudio.Wave.WaveFileWriter.CreateWaveFile(desFile, reader);
     Debug.Log($"{sourceFile} => {desFile}");
 }
Exemplo n.º 4
0
 public void PlaySound(string name, Action done = null)
 {
     FileStream ms = File.OpenRead(_soundLibrary[name]);
     var rdr = new Mp3FileReader(ms);
     WaveStream wavStream = WaveFormatConversionStream.CreatePcmStream(rdr);
     var baStream = new BlockAlignReductionStream(wavStream);
     var waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback());
     waveOut.Init(baStream);
     waveOut.Play();
     var bw = new BackgroundWorker();
     bw.DoWork += (s, o) =>
                      {
                          while (waveOut.PlaybackState == PlaybackState.Playing)
                          {
                              Thread.Sleep(100);
                          }
                          waveOut.Dispose();
                          baStream.Dispose();
                          wavStream.Dispose();
                          rdr.Dispose();
                          ms.Dispose();
                          if (done != null) done();
                      };
     bw.RunWorkerAsync();
 }
Exemplo n.º 5
0
        private static void CutFile(string sourceFile, int startSecond, int endSecond, string resultFile)
        {
            using (var reader = new Mp3FileReader(sourceFile))
            {
                FileStream writer = File.Create(resultFile);

                Mp3Frame frame;
                while ((frame = reader.ReadNextFrame()) != null)
                {

                    var currentSecond = (int)reader.CurrentTime.TotalSeconds;
                    if (currentSecond >= startSecond && currentSecond <= endSecond)
                    {
                        writer.Write(frame.RawData, 0, frame.RawData.Length);
                    }
                    else
                    {
                        if (currentSecond > endSecond)
                        {
                            writer.Dispose();
                            break;
                        }
                    }
                }

                writer.Dispose();
            }
        }
Exemplo n.º 6
0
        public static Task Play(this Captcha captcha)
        {
            return Task.Run(() =>
            {
                using (MemoryStream memory = new MemoryStream(captcha.Data, false))
                {
                    memory.Seek(0, SeekOrigin.Begin);

                    using (Mp3FileReader reader = new Mp3FileReader(memory))
                    using (WaveStream pcm = WaveFormatConversionStream.CreatePcmStream(reader))
                    using (WaveStream stream = new BlockAlignReductionStream(pcm))
                    {
                        using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()))
                        {
                            waveOut.Init(stream);
                            waveOut.Play();

                            while (waveOut.PlaybackState == PlaybackState.Playing)
                            {
                                Thread.Sleep(100);
                            }
                        }
                    }
                }
            });
        }
Exemplo n.º 7
0
 private static TimeSpan GetFileLength(string mp3Path)
 {
     using (var reader = new Mp3FileReader(mp3Path))
     {
         return reader.TotalTime;
     }
 }
Exemplo n.º 8
0
 /// <summary>
 /// Считывает данные о заголоке из MP3 файла
 /// </summary>
 public static NAudio.Wave.WaveFormat WavHeaderFromMp3(Stream Stream)
 {
     using (var reader = new NAudio.Wave.Mp3FileReader(Stream))
     {
         return reader.WaveFormat;
     }
 }
Exemplo n.º 9
0
        public double[][] GetNextChunk(int samplesDesired, Mp3FileReader fr, bool fullnormalize = false)
        {
            byte[] buffer = new byte[samplesDesired * 4];
            short[] left = new short[samplesDesired];
            //short[] right = new short[samplesDesired];
            double[] leftd = new double[samplesDesired];
            //double[] rightd = new double[samplesDesired];

            int bytesRead = 0;

            try
            {
                bytesRead = fr.Read(buffer, 0, 4 * samplesDesired);
            }
            catch
            {
                new Exception("An error occurred while reading file");
            }

            int index = 0;
            for (int sample = 0; sample < bytesRead / 4; sample++)
            {
                left[sample] = BitConverter.ToInt16(buffer, index); index += 2;
                //right[sample] = BitConverter.ToInt16(buffer, index);
                index += 2;
            }

            if (fullnormalize)
                leftd = Utilities.NormalizeFull(ref left, left.Length);
            else
                leftd = Utilities.Normalize(ref left, left.Length);

            return new double[][] { leftd, null }; //rightd };
        }
Exemplo n.º 10
0
        public string Describe(string fileName)
        {
            var stringBuilder = new StringBuilder();
            using (var reader = new Mp3FileReader(fileName))
            {
                Mp3WaveFormat wf = reader.Mp3WaveFormat;
                stringBuilder.AppendFormat("MP3 File WaveFormat: {0} {1}Hz {2} channels {3} bits per sample\r\n",
                    wf.Encoding, wf.SampleRate,
                    wf.Channels, wf.BitsPerSample);
                stringBuilder.AppendFormat("Extra Size: {0} Block Align: {1} Average Bytes Per Second: {2}\r\n",
                    wf.ExtraSize, wf.BlockAlign,
                    wf.AverageBytesPerSecond);
                stringBuilder.AppendFormat("ID: {0} Flags: {1} Block Size: {2} Frames per Block: {3}\r\n",
                    wf.id, wf.flags, wf.blockSize, wf.framesPerBlock
                    );

                stringBuilder.AppendFormat("Length: {0} bytes: {1} \r\n", reader.Length, reader.TotalTime);
                stringBuilder.AppendFormat("ID3v1 Tag: {0}\r\n", reader.Id3v1Tag == null ? "None" : reader.Id3v1Tag.ToString());
                stringBuilder.AppendFormat("ID3v2 Tag: {0}\r\n", reader.Id3v2Tag == null ? "None" : reader.Id3v2Tag.ToString());
                Mp3Frame frame;
                while ((frame = reader.ReadNextFrame()) != null)
                {
                    stringBuilder.AppendFormat("{0},{1},{2}Hz,{3},{4}bps, length {5}\r\n",
                        frame.MpegVersion, frame.MpegLayer,
                        frame.SampleRate, frame.ChannelMode,
                        frame.BitRate, frame.FrameLength);
                }
            }
            return stringBuilder.ToString();
        }
Exemplo n.º 11
0
 /// <summary>
 /// Асинхронно считывает данные из MP3 файла в массив; верхний индекс - номер канала, нижний - номер сэмпла
 /// </summary>
 public static async Task<int[][]> DataFromMp3(Stream Stream)
 {
     using (var reader = new NAudio.Wave.Mp3FileReader(Stream))
     {
         return await Task<int[][]>.Factory.StartNew(() => _readMp3(reader));
     }
 }
Exemplo n.º 12
0
 public static void Mp3ToWav(string mp3File, string outputFile)
 {
     using (Mp3FileReader reader = new Mp3FileReader(mp3File))
     {
         WaveFileWriter.CreateWaveFile(outputFile, reader);
     }
 }
Exemplo n.º 13
0
        public byte[] Encode()
        {
            int ms = 20;
            int channels = 2;
            int sampleRate = 48000;

            int blockSize = 48 * 2 * channels * ms; //the size per each frame to encode
            byte[] buffer = new byte[blockSize]; //a nicely sized pcm buffer to work with.
            var outFormat = new WaveFormat(sampleRate, 16, channels);
            
            if(__filename.EndsWith(".mp3"))
            {
                using (var mp3Reader = new Mp3FileReader(__filename))
                {
                    using (var resampler = new WaveFormatConversionStream(outFormat, mp3Reader))
                    {
                        int byteCount;
                        using (BinaryWriter bw = new BinaryWriter(new MemoryStream()))
                        {
                            while ((byteCount = resampler.Read(buffer, 0, blockSize)) > 0)
                            {
                                //now to encode
                                byte[] opusOutput = new byte[buffer.Length]; //extra bytes but that's okay
                                int opusEncoded = encoder.EncodeFrame(buffer, 0, opusOutput);
                                bw.Write((ushort)opusEncoded);
                                bw.Write(opusOutput, 0, opusEncoded);
                            }
                            MemoryStream baseStream = bw.BaseStream as MemoryStream;
                            return baseStream.ToArray();
                        }
                    }
                }
            }
            return null;
        }
        public AudioPlayer(Resource resource, TabPage tab)
        {
            var soundData = (Sound)resource.Blocks[BlockType.DATA];

            var stream = soundData.GetSoundStream();
            waveOut = new WaveOutEvent();

            if (soundData.Type == Sound.AudioFileType.WAV)
            {
                var rawSource = new WaveFileReader(stream);
                waveOut.Init(rawSource);
            }
            else if (soundData.Type == Sound.AudioFileType.MP3)
            {
                var rawSource = new Mp3FileReader(stream);
                waveOut.Init(rawSource);
            }

            playButton = new Button();
            playButton.Text = "Play";
            playButton.TabIndex = 1;
            playButton.Size = new Size(100, 25);
            playButton.Click += PlayButton_Click;

            tab.Controls.Add(playButton);
        }
Exemplo n.º 15
0
        public TestMix()
        {
            //WaveStream str1 = new Mp3FileReader("C:\\Users\\mtemkine\\Desktop\\snd\\guitar1.mp3");
            //WaveStream str2 = new Mp3FileReader("C:\\Users\\mtemkine\\Desktop\\snd\\molecules.mp3");
            //WaveMixerStream32 mix = new WaveMixerStream32(new [] {str1, str2}, false);

            var background = new Mp3FileReader("C:\\Users\\mtemkine\\Desktop\\snd\\ferriss.mp3");
            var message = new Mp3FileReader("C:\\Users\\mtemkine\\Desktop\\snd\\guitar1.mp3");

            var mixer = new WaveMixerStream32();
            mixer.AutoStop = true;

            var messageOffset = background.TotalTime;
            var messageOffsetted = new WaveOffsetStream(message, TimeSpan.FromSeconds(1.5), TimeSpan.Zero, message.TotalTime.Subtract(TimeSpan.FromSeconds(1)));

            var background32 = new WaveChannel32(background);
            background32.PadWithZeroes = false;
            background32.Volume = 0.9f;

            var message32 = new WaveChannel32(messageOffsetted);
            message32.PadWithZeroes = false;
            message32.Volume = 0.7f;

            var s1 = new RawSourceWaveStream(background32, new WaveFormat(8000, 16, 1));
            var s2 = new RawSourceWaveStream(message32, new WaveFormat(8000, 16, 1));
            WaveFormat targetFormat = WaveFormat.CreateIeeeFloatWaveFormat(128, 2);
            var ss1 = new WaveFormatConversionStream(targetFormat, background32);
            //var c = new WaveFormatConversionStream(WaveFormat.CreateALawFormat(8000, 1), background32);
            //var stream_background32 = new WaveFormatConversionStream(new WaveFormat(256, 32, 2), background32);
            //var stream_message32 = new WaveFormatConversionStream(new WaveFormat(256, 32, 2), message32);
            mixer.AddInputStream(s1);
            mixer.AddInputStream(s2);

            WaveFileWriter.CreateWaveFile("mycomposed.wav", new Wave32To16Stream(mixer));
        }
Exemplo n.º 16
0
        public bool PlayMP3(string fileName)
        {
            if (fileName == null) { return false; }

              if (fileName.StartsWith("http")) {
            return StreamMP3(fileName);
              }

              speaking = true;
              WSRConfig.GetInstance().logInfo("PLAYER", "Start MP3 Player");
              using (var ms = File.OpenRead(fileName))
              using (var mp3Reader = new Mp3FileReader(ms))
              using (var pcmStream = WaveFormatConversionStream.CreatePcmStream(mp3Reader))
              using (var baStream = new BlockAlignReductionStream(pcmStream))
              using (var waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback())) {
            waveOut.Init(baStream);
            waveOut.Play();
            played.Add(fileName);
            while (baStream.CurrentTime < baStream.TotalTime && played.Contains(fileName)) {
              Thread.Sleep(100);
            }
            played.Remove(fileName);
            waveOut.Stop();

              }
              WSRConfig.GetInstance().logInfo("PLAYER", "End MP3 Player");
              speaking = false;
              return true;
        }
Exemplo n.º 17
0
        private WaveStream getReader(string filename, Stream inputStream)
        {
            WaveStream result    = null;
            string     extension = System.IO.Path.GetExtension(filename);

            inputStream.Position = 0;

            switch (extension.ToLower())
            {
            case ".mp3":
                Mp3FileReader mp3Reader = new NAudio.Wave.Mp3FileReader(inputStream
                                                                        , new Mp3FileReader.FrameDecompressorBuilder
                                                                            (waveFormat =>
                                                                            new NLayer.NAudioSupport.Mp3FrameDecompressor
                                                                                (waveFormat)));


                result = mp3Reader;
                break;

            case ".wav":
                result = new WaveFileReader(inputStream);
                break;
            }
            return(result);
        }
Exemplo n.º 18
0
 public void CanLoadAndReadVariousProblemMp3Files()
 {
     string testDataFolder = @"C:\Users\Mark\Downloads\NAudio";
     if (!Directory.Exists(testDataFolder))
     {
         Assert.Ignore("{0} not found", testDataFolder);
     }
     foreach (string file in Directory.GetFiles(testDataFolder, "*.mp3"))
     {
         string mp3File = Path.Combine(testDataFolder, file);
         Debug.WriteLine(String.Format("Opening {0}", mp3File));
         using (var reader = new Mp3FileReader(mp3File))
         {
             byte[] buffer = new byte[4096];
             int bytesRead;
             int total = 0;
             do
             {
                 bytesRead = reader.Read(buffer, 0, buffer.Length);
                 total += bytesRead;
             } while (bytesRead > 0);
             Debug.WriteLine(String.Format("Read {0} bytes", total));
         }
     }
 }
Exemplo n.º 19
0
        /// <summary>
        /// Обрезает аудиотрек от заданного семпла до заданного семпла (begin, end).
        /// </summary>
        public void Trim(TimeSpan?begin, TimeSpan?end)
        {
            if (begin.HasValue && end.HasValue && begin > end)
            {
                throw new ArgumentOutOfRangeException("end", "end should be greater than begin");
            }

            using (var reader = new NAudio.Wave.Mp3FileReader(inputPath))
                using (var writer = System.IO.File.Create(outputPath))
                {
                    NAudio.Wave.Mp3Frame frame;
                    while ((frame = reader.ReadNextFrame()) != null)
                    {
                        if (reader.CurrentTime >= begin || !begin.HasValue)
                        {
                            if (reader.CurrentTime <= end || !end.HasValue)
                            {
                                writer.Write(frame.RawData, 0, frame.RawData.Length);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
        }
Exemplo n.º 20
0
        public SoundResource(ResourceManager mgr, string fullName, Stream stream, Format fmt)
        {
            _manager = mgr;
            FullName = fullName;

            switch (fmt)
            {
                case Format.MP3:
                {
                    Mp3FileReader mp3 = new Mp3FileReader(stream);
                    _reader = mp3;
                    break;
                }
                case Format.WAV:
                {
                    WaveFileReader wav = new WaveFileReader(stream);
                    _reader = wav;
                    break;
                }
                default:
                    throw new InvalidOperationException("Unsupported extension.");
            }

            _stream = new WaveChannel32(_reader);
            _stream.PadWithZeroes = false;

            _wavDevice.PlaybackStopped += _wavDevice_PlaybackStopped;
        }
Exemplo n.º 21
0
 //If necessary, convert mp3 to wav - avoid Unity file stream restrictions
 private static void mp3ToWav(string mp3path, string outputPath)
 {
     using (Mp3FileReader reader = new Mp3FileReader(mp3path)) {
         using (WaveStream pcmStream = WaveFormatConversionStream.CreatePcmStream(reader)) {
             WaveFileWriter.CreateWaveFile(outputPath, pcmStream);
         }
     }
 }
Exemplo n.º 22
0
        public mp3Processor(string file)
        {
            buf = new byte[maxLen];

            WaveStream mp3Reader = new Mp3FileReader(file);
            int read = mp3Reader.Read(buf, 0, buf.Length);
            len = read;
        }
Exemplo n.º 23
0
 private static WaveChannel32 OpenMp3Stream(string fileName)
 {
     WaveChannel32 inputStream;
     WaveStream mp3Reader = new Mp3FileReader(fileName);
     WaveStream pcmStream = WaveFormatConversionStream.CreatePcmStream(mp3Reader);
     WaveStream blockAlignedStream = new BlockAlignReductionStream(pcmStream);
     inputStream = new WaveChannel32(blockAlignedStream);
     return inputStream;
 }
Exemplo n.º 24
0
        static void Main(string[] args)
        {
            string sLang = "zh-CN";
            string sText = "";
            
            Uri uriMp3;
            string sMp3Path;
            string sWavPath;

            
            //Read text from text.txt
             if (args.Count() > 0)
            {
                sText = File.ReadAllText(args[0], Encoding.UTF8);
            }
            else
            {
                sText = File.ReadAllText(Environment.CurrentDirectory + @"\text.txt", Encoding.UTF8);
            }
            
            //Detect Language
            using (WebClient wcLang = new WebClient())
            {
                wcLang.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 9.0; Windows;)");
                Uri uriLang = new Uri("http://translate.google.cn/translate_a/t?client=t&sl=auto&text=" + sText);
                
                wcLang.DownloadFile(uriLang, "lang.txt");
                string parseResult = Utils.GetLang(File.ReadAllText("lang.txt"));
                if (parseResult == "") { parseResult = "zh-CN"; }
                sLang = parseResult;
            }

            uriMp3 = new Uri("http://translate.google.cn/translate_tts?tl=" + sLang + "&q=" + sText);  
            sMp3Path = Environment.CurrentDirectory + @"tmp.mp3";
            sWavPath=Environment.CurrentDirectory+@"\..\res\sound\"+sText+".wav";

            //Get MP3 from Google
            using (WebClient wcMp3Speech = new WebClient())
            {
                wcMp3Speech.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 9.0; Windows;)");
                wcMp3Speech.DownloadFile(uriMp3, sMp3Path);
            }

            //Now convert the MP3 to WAV
            using (Mp3FileReader reader = new Mp3FileReader(new FileStream(sMp3Path,FileMode.OpenOrCreate)))
            {
                WaveFileWriter.CreateWaveFile(sWavPath, reader);
            }

            //Now copy the WAV to speech.wav
            if (File.Exists(Environment.CurrentDirectory + @"\..\res\sound\speech.wav"))
            {
                File.Delete(Environment.CurrentDirectory + @"\..\res\sound\speech.wav");
            }

            File.Copy(sWavPath, Environment.CurrentDirectory + @"\..\res\sound\speech.wav");
        }
Exemplo n.º 25
0
        private static WaveStream CreateInputStream(byte[] mediacontent)
        {
            var memoryStream = new MemoryStream(mediacontent);
            var mp3Reader = new Mp3FileReader(memoryStream);

            var inputStream = new WaveChannel32(mp3Reader);

            return inputStream;
        }
Exemplo n.º 26
0
 public static byte[] getByteArray(string file, ref int len, ref int channels)
 {
     byte[] buf = new byte[maxLen];
     WaveStream mp3Reader = new Mp3FileReader(file);
     channels = mp3Reader.WaveFormat.Channels;
     int read = mp3Reader.Read(buf, 0, buf.Length);
     len = read;
     return buf;
 }
Exemplo n.º 27
0
 public void AppendAllOfFileMp3(string srcFilename, double? speedChange = null) {
     //using (var readerMp3 = new Mp3FileReader(srcFilename))
     //using (var PCM = WaveFormatConversionStream.CreatePcmStream(readerMp3))
     //using (var readerWave2 = new WaveChannel32(PCM))
     //using (var downsampledStream = new WaveFormatConversionStream(new WaveFormat(8000, readerWave2.WaveFormat.BitsPerSample, readerWave2.WaveFormat.Channels), readerWave2))
     //using (var readerWave = new WaveFormatConversionStream(format, downsampledStream))
     using (var readerMp3 = new Mp3FileReader(srcFilename)) {
         AppendAllOfFile_stream(readerMp3, speedChange);
     }
 }
Exemplo n.º 28
0
        public void WritePieceOfSomeFileMp3(
            string srcFilename,
            double secondIn,
            double secondOut,
            double? speedChange = null)
		{
            using (var reader = new Mp3FileReader(srcFilename)) {
                WritePieceOfSomeFile_stream(reader, secondIn, secondOut, speedChange);
            }
		}
Exemplo n.º 29
0
 public static long TotalLengthMillis(string srcFilename) {
     long millis = 0;
     using (var reader = new Mp3FileReader(srcFilename)) {
         Mp3Frame frame;
         // read this shit to the end
         while ((frame = reader.ReadNextFrame()) != null) {}
         millis = (long)reader.CurrentTime.TotalMilliseconds;
     }
     return millis;
 }
Exemplo n.º 30
0
 public WzMp3Streamer(WzSoundProperty sound, bool repeat)
 {
     this.repeat = repeat;
     this.sound = sound;
     byteStream = new MemoryStream(sound.GetBytes(false));
     mpegStream = new Mp3FileReader(byteStream);
     wavePlayer = new WaveOut(WaveCallbackInfo.FunctionCallback());
     wavePlayer.Init(mpegStream);
     wavePlayer.PlaybackStopped +=new EventHandler(wavePlayer_PlaybackStopped);
 }
Exemplo n.º 31
0
        private string DoConvert(string baseFilename, Action<string> addLogMessage, Action<long> sourceLengthCallback, Action<long> progressCallback)
        {
            var newFilename = Path.ChangeExtension(baseFilename, ".wav");
            using (var reader = new Mp3FileReader(baseFilename))
            {
                sourceLengthCallback(reader.Length);
                FileCreator.CreateWaveFile(newFilename, reader, progressCallback);
            }

            return newFilename;
        }
Exemplo n.º 32
0
        public void Close()
        {
            if (m_WavePlayer == null)
                return;

            m_FileName = "";
            m_WavePlayer.Dispose();
            m_WavePlayer = null;
            mp3Stream.Dispose();
            mp3Stream = null;
        }
Exemplo n.º 33
0
		public void AppendAllOfFile(string srcFilename)
		{
			using (var reader = new Mp3FileReader(srcFilename))
			{
				Mp3Frame frame;
				while ((frame = reader.ReadNextFrame()) != null)
				{
					writer.Write(frame.RawData, 0, frame.RawData.Length);
				}
				timeTotal += reader.TotalTime;
			}
		}
Exemplo n.º 34
0
 public TimeSpan TimeMP3(string inputPath)
 {
     if (inputPath != null)
     {
         NAudio.Wave.Mp3FileReader reader = new NAudio.Wave.Mp3FileReader(inputPath);
         TimeSpan duration = reader.TotalTime;
         return(duration);
     }
     else
     {
         return(new TimeSpan(0, 0, 0, 0, 0));
     }
 }
Exemplo n.º 35
0
        private void buttonOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Filter = "MP3 Files|*.mp3";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                using (var stream = new NAudio.Wave.Mp3FileReader(ofd.FileName, new Mp3FileReader.FrameDecompressorBuilder(waveFormat => new NLayer.NAudioSupport.Mp3FrameDecompressor(waveFormat))))
                {
                    string fileName = Path.GetFileNameWithoutExtension(ofd.FileName) + ".wav";
                    fileName = Path.Combine(Path.GetTempPath(), fileName);
                    WaveFileWriter.CreateWaveFile(fileName, stream);
                    Process.Start(fileName);
                }
            }
        }
Exemplo n.º 36
0
        private void openButton_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                stopPreview_Click(sender, e);
                if (Path.GetExtension(openFileDialog1.FileName).ToLower() == ".wav")
                {
                    originalFile = File.ReadAllBytes(openFileDialog1.FileName);
                }
                else if (Path.GetExtension(openFileDialog1.FileName).ToLower() == ".mp3")
                {
                    using (var reader = new NAudio.Wave.Mp3FileReader(openFileDialog1.FileName))
                    {
                        using (MemoryStream wavCreate = new MemoryStream())
                        {
                            NAudio.Wave.WaveFileWriter.WriteWavFileToStream(wavCreate, reader);
                            originalFile = wavCreate.ToArray();
                        }
                    }
                }
                else if (Path.GetExtension(openFileDialog1.FileName).ToLower() == ".flac")
                {
                    using (var reader = new NAudio.Wave.MediaFoundationReader(openFileDialog1.FileName))
                    {
                        using (MemoryStream wavCreate = new MemoryStream())
                        {
                            NAudio.Wave.WaveFileWriter.WriteWavFileToStream(wavCreate, reader);
                            originalFile = wavCreate.ToArray();
                        }
                    }
                }
                channels = originalFile[22];
                switch (channels)
                {
                case 1:
                    oneCh.Checked = true;
                    break;

                case 2:
                    twoCh.Checked = true;
                    break;

                case 3:
                    threeCh.Checked = true;
                    break;

                case 4:
                    fourCh.Checked = true;
                    break;

                case 5:
                    fiveCh.Checked = true;
                    break;

                case 6:
                    sixCh.Checked = true;
                    break;

                default:
                    MessageBox.Show("Invalid WAV file!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                bitDepth = originalFile[34];
                switch (bitDepth)
                {
                case 8:
                    eightBit.Checked = true;
                    break;

                case 16:
                    DimaBachilo.Checked = true;
                    break;

                case 24:
                    twentyFourBit.Checked = true;
                    break;

                case 32:
                    thirtyTwoBit.Checked = true;
                    break;

                default:
                    MessageBox.Show("Invalid WAV file!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                byte[] frequency = new byte[4];
                for (int i = 0; i < 4; i++)
                {
                    frequency[i] = originalFile[i + 24];
                }
                byte[] dataSizeByte = new byte[4];
                if (originalFile[35] == 0 && originalFile[36] == 100 && originalFile[37] == 97 && originalFile[38] == 116 && originalFile[39] == 97)
                {
                    dataStartOffset = 0;
                }
                else
                {
                    for (int i = 1; i < originalFile.Length - 4; i++)
                    {
                        if (originalFile[35 + i] == 0 && originalFile[36 + i] == 100 && originalFile[37 + i] == 97 && originalFile[38 + i] == 116 && originalFile[39 + i] == 97)
                        {
                            dataStartOffset = i;
                            break;
                        }
                        else
                        {
                            continue;
                        }
                    }
                }
                for (int i = 0; i < 4; i++)
                {
                    dataSizeByte[i] = originalFile[i + dataStartOffset + 40];
                }
                dataSize      = Convert.ToInt32(LEtoDecByte(dataSizeByte));
                textBox1.Text = openFileDialog1.FileName;
                textBox1.Select(textBox1.Text.Length, 0);
                textBox1.ScrollToCaret();
                freq          = LEtoDecByte(frequency);
                textBox2.Text = freq;
                enableButtons(true);
                checkBox1.Enabled     = true;
                previewButton.Enabled = true;
                saveButton.Enabled    = true;
                checkBox1.Checked     = false;
                swappedFile           = null;
            }
        }
Exemplo n.º 37
0
    private void WriteToFile(string SongID, string strPath, byte[] Buffer)
    {
        try
        {
            int  samplesPerPixel = 128;
            long startPosition   = 0;
            //FileStream newFile = new FileStream(GeneralUtils.Get_SongFilePath() + "/" + strPath, FileMode.Create);
            float[] data         = FloatArrayFromByteArray(Buffer);
            Bitmap  bmp          = new Bitmap(1170, 200);
            int     BORDER_WIDTH = 5;
            int     width        = bmp.Width - (2 * BORDER_WIDTH);
            int     height       = bmp.Height - (2 * BORDER_WIDTH);

            NAudio.Wave.Mp3FileReader reader        = new NAudio.Wave.Mp3FileReader(strPath, wf => new NAudio.FileFormats.Mp3.DmoMp3FrameDecompressor(wf));
            NAudio.Wave.WaveChannel32 channelStream = new NAudio.Wave.WaveChannel32(reader);
            int bytesPerSample = (reader.WaveFormat.BitsPerSample / 8) * channelStream.WaveFormat.Channels;
            using (Graphics g = Graphics.FromImage(bmp))
            {
                g.Clear(Color.White);
                Pen    pen1      = new Pen(Color.Gray);
                int    size      = data.Length;
                string hexValue1 = "#009adf";
                Color  colour1   = System.Drawing.ColorTranslator.FromHtml(hexValue1);
                pen1.Color = colour1;
                Stream wavestream = new NAudio.Wave.Mp3FileReader(strPath, wf => new NAudio.FileFormats.Mp3.DmoMp3FrameDecompressor(wf));
                wavestream.Position = 0;
                int    bytesRead1;
                byte[] waveData1 = new byte[samplesPerPixel * bytesPerSample];
                wavestream.Position = startPosition + (width * bytesPerSample * samplesPerPixel);
                for (float x = 0; x < width; x++)
                {
                    short low  = 0;
                    short high = 0;
                    bytesRead1 = wavestream.Read(waveData1, 0, samplesPerPixel * bytesPerSample);
                    if (bytesRead1 == 0)
                    {
                        break;
                    }
                    for (int n = 0; n < bytesRead1; n += 2)
                    {
                        short sample = BitConverter.ToInt16(waveData1, n);
                        if (sample < low)
                        {
                            low = sample;
                        }
                        if (sample > high)
                        {
                            high = sample;
                        }
                    }
                    float lowPercent  = ((((float)low) - short.MinValue) / ushort.MaxValue);
                    float highPercent = ((((float)high) - short.MinValue) / ushort.MaxValue);
                    float lowValue    = height * lowPercent;
                    float highValue   = height * highPercent;
                    g.DrawLine(pen1, x, lowValue, x, highValue);
                }
            }
            string filename = Server.MapPath("image/060.png");
            bmp.Save(filename);
            bmp.Dispose();
        }
        catch (Exception e)
        {
        }
    }
Exemplo n.º 38
0
        static async Task <bool> To_WAV(int File_Number, string To_Dir, bool IsFromFileDelete, bool IsUseFFmpeg, bool IsUseBass)
        {
            if (!File.Exists(From_Files[File_Number]))
            {
                return(false);
            }
            if (IsUseFFmpeg)
            {
                if (IsUseBass)
                {
                    string To_Audio_File           = To_Dir + "\\" + Path.GetFileNameWithoutExtension(From_Files[File_Number]) + ".wav";
                    Un4seen.Bass.Misc.EncoderWAV w = new Un4seen.Bass.Misc.EncoderWAV(0);
                    w.InputFile         = From_Files[File_Number];
                    w.OutputFile        = To_Audio_File;
                    w.WAV_BitsPerSample = 24;
                    w.Start(null, IntPtr.Zero, false);
                    w.Stop();
                    if (IsFromFileDelete)
                    {
                        File.Delete(From_Files[File_Number]);
                    }
                }
                else
                {
                    string       Encode_Style = "-y -vn -ac 2 -ar 44100 -acodec pcm_s24le -f wav";
                    StreamWriter stw          = File.CreateText(Voice_Set.Special_Path + "/Encode_Mp3/Audio_Encode" + File_Number + ".bat");
                    stw.WriteLine("chcp 65001");
                    stw.Write("\"" + Voice_Set.Special_Path + "/Encode_Mp3/ffmpeg.exe\" -i \"" + From_Files[File_Number] + "\" " + Encode_Style + " \"" + To_Dir + "\\" +
                              Path.GetFileNameWithoutExtension(From_Files[File_Number]) + ".wav\"");
                    stw.Close();
                    ProcessStartInfo processStartInfo = new ProcessStartInfo
                    {
                        FileName        = Voice_Set.Special_Path + "/Encode_Mp3/Audio_Encode" + File_Number + ".bat",
                        CreateNoWindow  = true,
                        UseShellExecute = false
                    };
                    Process p = Process.Start(processStartInfo);
                    await Task.Run(() =>
                    {
                        p.WaitForExit();
                        if (IsFromFileDelete)
                        {
                            File.Delete(From_Files[File_Number]);
                        }
                        File.Delete(Voice_Set.Special_Path + "/Encode_Mp3/Audio_Encode" + File_Number + ".bat");
                    });
                }
            }
            else if (IsUseBass)
            {
                string To_Audio_File           = To_Dir + "\\" + Path.GetFileNameWithoutExtension(From_Files[File_Number]) + ".wav";
                Un4seen.Bass.Misc.EncoderWAV w = new Un4seen.Bass.Misc.EncoderWAV(0);
                w.InputFile         = From_Files[File_Number];
                w.OutputFile        = To_Audio_File;
                w.WAV_BitsPerSample = 24;
                w.Start(null, IntPtr.Zero, false);
                w.Stop();
                if (IsFromFileDelete)
                {
                    File.Delete(From_Files[File_Number]);
                }
            }
            else
            {
                int    Number        = 0;
                string To_Audio_File = To_Dir + "\\" + Path.GetFileNameWithoutExtension(From_Files[File_Number]) + ".wav";
                await Task.Run(() =>
                {
start:
                    try
                    {
                        string Ex = Path.GetExtension(From_Files[File_Number]);
                        if (Ex == ".ogg")
                        {
                            using (NAudio.Vorbis.VorbisWaveReader reader = new NAudio.Vorbis.VorbisWaveReader(From_Files[File_Number]))
                                using (WaveStream pcmStream = WaveFormatConversionStream.CreatePcmStream(reader))
                                    WaveFileWriter.CreateWaveFile(To_Audio_File, pcmStream);
                        }
                        else if (Ex == ".mp3")
                        {
                            using (NAudio.Wave.Mp3FileReader reader = new NAudio.Wave.Mp3FileReader(From_Files[File_Number]))
                                using (WaveStream pcmStream = WaveFormatConversionStream.CreatePcmStream(reader))
                                    WaveFileWriter.CreateWaveFile(To_Audio_File, pcmStream);
                        }
                        else if (Ex == ".flac")
                        {
                            using (NAudio.Flac.FlacReader reader = new NAudio.Flac.FlacReader(From_Files[File_Number]))
                                using (WaveStream pcmStream = WaveFormatConversionStream.CreatePcmStream(reader))
                                    WaveFileWriter.CreateWaveFile(To_Audio_File, pcmStream);
                        }
                        else if (Ex == ".aac" || Ex == ".wma" || Ex == ".mp4")
                        {
                            using (MediaFoundationReader reader = new MediaFoundationReader(From_Files[File_Number]))
                                WaveFileWriter.CreateWaveFile(To_Audio_File, reader);
                        }
                        else if (Ex == ".wav")
                        {
                            using (WaveFileReader reader = new WaveFileReader(From_Files[File_Number]))
                                using (WaveStream pcmStream = WaveFormatConversionStream.CreatePcmStream(reader))
                                    WaveFileWriter.CreateWaveFile(To_Audio_File, pcmStream);
                        }
                        if (IsFromFileDelete)
                        {
                            File.Delete(From_Files[File_Number]);
                        }
                    }
                    catch (Exception e)
                    {
                        if (Number < 4)
                        {
                            Number++;
                            //goto文...許してください...
                            goto start;
                        }
                        else
                        {
                            Sub_Code.Error_Log_Write(e.Message);
                        }
                    }
                });
            }
            return(true);
        }