ReadNextFrame() public méthode

Reads the next mp3 frame
public ReadNextFrame ( ) : NAudio.Wave.Mp3Frame
Résultat NAudio.Wave.Mp3Frame
Exemple #1
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();
            }
        }
        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();
        }
Exemple #3
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;
                            }
                        }
                    }
                }
        }
Exemple #4
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;
 }
Exemple #5
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;
			}
		}
Exemple #6
0
        private static void ConcatFiles(string resultFile, string sourceFile)
        {
            using (var reader = new Mp3FileReader(sourceFile))
            {
                FileStream writer = File.Open(resultFile, FileMode.Append);

                Mp3Frame frame;
                while ((frame = reader.ReadNextFrame()) != null)
                {
                    writer.Write(frame.RawData, 0, frame.RawData.Length);
                }

                writer.Dispose();
            }
        }
 public void CanDecompressAnMp3()
 {
     string testFile = @"C:\Users\Public\Music\Coldplay\X&Y\01-Square One.mp3";
     using(Mp3FileReader reader = new Mp3FileReader(testFile))
     {
         var frameDecompressor = new DmoMp3FrameDecompressor(reader.Mp3WaveFormat);
         Mp3Frame frame = null;
         byte[] buffer = new byte[reader.WaveFormat.AverageBytesPerSecond];
         while ((frame = reader.ReadNextFrame()) != null)
         {
             int decompressed = frameDecompressor.DecompressFrame(frame, buffer, 0);
             Console.WriteLine("Decompressed {0} bytes to {1}", frame.FrameLength, decompressed);
         }
     }
 }
 /// <summary>
 /// Transforma o período selecionado em um novo MP3 utilizando o codec LAME.
 /// </summary>
 /// <param name="inputFile">Arquivo de Entrada.</param>                
 /// <param name="inicio">Início da Seleção.</param>
 /// <param name="fim">Fim da Seleção.</param>        
 public static MemoryStream CortarMp3(string inputFile, TimeSpan? inicio, TimeSpan? fim)
 {
     MemoryStream writer = new MemoryStream();
     using (var reader = new Mp3FileReader(inputFile))
     {
         Mp3Frame frame;
         while ((frame = reader.ReadNextFrame()) != null)
             if (reader.CurrentTime >= inicio || !inicio.HasValue)
             {
                 if (reader.CurrentTime <= fim || !fim.HasValue)
                     writer.Write(frame.RawData, 0, frame.RawData.Length);
                 else break;
             }
     }
     return writer;
 }
Exemple #9
0
 public static void Combine(string[] inputFiles, Stream output)
 {
     foreach (string file in inputFiles)
     {
         Mp3FileReader reader = new Mp3FileReader(file);
         if ((output.Position == 0) && (reader.Id3v2Tag != null))
         {
             output.Write(reader.Id3v2Tag.RawData, 0, reader.Id3v2Tag.RawData.Length);
         }
         Mp3Frame frame;
         while ((frame = reader.ReadNextFrame()) != null)
         {
             output.Write(frame.RawData, 0, frame.RawData.Length);
         }
     }
 }
        public static void TrimMp3(string inputPath, string outputPath, 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 Mp3FileReader(inputPath))
            using (var writer = System.IO.File.Create(outputPath))
            {
                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;
                    }
            }
        }
 public void CanDecompressAnMp3()
 {
     var testFile = @"C:\Users\Public\Music\Coldplay\X&Y\01-Square One.mp3";
     if (!File.Exists(testFile))
     {
         Assert.Ignore("{0} not found", testFile);
     }
     using(var reader = new Mp3FileReader(testFile))
     {
         var frameDecompressor = new DmoMp3FrameDecompressor(reader.Mp3WaveFormat);
         Mp3Frame frame = null;
         var buffer = new byte[reader.WaveFormat.AverageBytesPerSecond];
         while ((frame = reader.ReadNextFrame()) != null)
         {
             int decompressed = frameDecompressor.DecompressFrame(frame, buffer, 0);
             Debug.WriteLine(String.Format("Decompressed {0} bytes to {1}", frame.FrameLength, decompressed));
         }
     }
 }
Exemple #12
0
		public void WritePieceOfSomeFile(string srcFilename, double secondIn, double secondOut)
		{
			using (var reader = new Mp3FileReader(srcFilename))
			{
                if (format == null)
                    format = reader.WaveFormat;
				Mp3Frame frame;
				while ((frame = reader.ReadNextFrame()) != null)
				{
					if (reader.CurrentTime.TotalSeconds >= secondIn)
					{
						writer.Write(frame.RawData, 0, frame.RawData.Length);
					}
					if (reader.CurrentTime.TotalSeconds >= secondOut)
						break;
				}
				timeTotal += TimeSpan.FromSeconds(secondOut - secondIn); //TODO: this does not account for ranges outside the length of the file
			}
		}
    public static string DescribeMp3(string fileName)
    {
        StringBuilder stringBuilder = new StringBuilder();
        using (Mp3FileReader 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("Bytes: {0} Time: {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;
            int kbps = 0;
            int frames = 0;
            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);
                 */
                kbps += frame.BitRate / 1000;
                frames++;
            }
            stringBuilder.AppendFormat("Mp3 Avg Kbps: {0} ({1})", kbps / frames, Path.GetFileName(fileName));
        }
        return stringBuilder.ToString();
    }
Exemple #14
0
        string SplitMP3(string SourcePath, string DestPath, int length)
        {
            int lastBackslashIndex = DestPath.LastIndexOf("\\");
            string tmpDirPath = DestPath.Remove(lastBackslashIndex);
            DirectoryInfo dir = new DirectoryInfo(tmpDirPath);

            if (!dir.Exists)
                dir.Create();

            using (var reader = new Mp3FileReader(SourcePath))
            {
                try
                {
                    using (FileStream writer = new FileStream(DestPath, FileMode.Open))
                    {
                        return DestPath;
                    }
                }
                catch (FileNotFoundException ex)
                {
                    using (FileStream writer = new FileStream(DestPath, FileMode.Create))
                    {
                        Mp3Frame frame;
                        while ((frame = reader.ReadNextFrame()) != null && (int)reader.CurrentTime.TotalSeconds < length)
                            writer.Write(frame.RawData, 0, frame.RawData.Length);

                        return DestPath;
                    }
                }
                catch (Exception ex)
                { }

                return "";
            }
        }
        /// <summary>
        /// Trims the MP3.
        /// </summary>
        /// <param name="mp3Path">The MP3 path.</param>
        /// <param name="outputPath">The output path.</param>
        /// <param name="timeFromDouble">The time from double.</param>
        /// <param name="duration">The duration.</param>
        /// <returns>
        /// Path of changed file
        /// </returns>
        public static string TrimMp3(string mp3Path, string outputPath, double timeFromDouble, double duration)
        {
            var timeToDouble = timeFromDouble + duration;

            if (timeToDouble > timeFromDouble)
            {
                var timeFrom = TimeSpan.FromSeconds(timeFromDouble);
                var timeTo = TimeSpan.FromSeconds(timeToDouble);

                using (var reader = new Mp3FileReader(mp3Path))
                using (var writer = File.Create(outputPath))
                {
                    Mp3Frame frame;
                    while ((frame = reader.ReadNextFrame()) != null)
                    {
                        BitRate = frame.BitRate / 1000.0;
                        if (reader.CurrentTime >= timeFrom && reader.CurrentTime <= timeTo)
                        {
                            writer.Write(frame.RawData, 0, frame.RawData.Length);
                        }
                    }
                }
            }

            return outputPath;
        }
Exemple #16
0
        static void Main(string[] args)
        {
            var argsConfig = Args.Configuration.Configure<Options>();
            Options options;
            try
            {
                options = argsConfig.CreateAndBind(args);
            }
            catch (InvalidArgsFormatException)
            {
                ShowHelp(argsConfig);
                return;
            }

            // check file exists
            var mp3Path = options.Path;
            if (!File.Exists(mp3Path)) return;

            TagLib.Tag id3;
            using (var tagFile = TagLib.File.Create(mp3Path)) id3 = tagFile.Tag;

            var mp3Dir = Path.GetDirectoryName(mp3Path);
            var mp3File = Path.GetFileName(mp3Path);
            var splitDir = Path.Combine(mp3Dir, Path.GetFileNameWithoutExtension(mp3Path));
            Directory.CreateDirectory(splitDir);

            Console.WriteLine(mp3File);

            int splitI = 0;
            int secsOffset = 0;
            string splitFilePath = null;

            using (var reader = new Mp3FileReader(mp3Path))
            {
                FileStream writer = null;
                var createWriter = new Action(() =>
                {
                    splitFilePath = Path.Combine(splitDir, Path.ChangeExtension(mp3File, (++splitI).ToString("D4") + ".mp3"));
                    writer = File.Create(splitFilePath);
                });

                var copyId3 = new Action(() =>
                {
                    using (var tagFile = TagLib.File.Create(splitFilePath))
                    {
                        id3.CopyTo(tagFile.Tag, true);
                        tagFile.Tag.Track = (uint)splitI;
                        tagFile.Save();
                    }
                });

                var showProgress = new Action(() =>
                {
                    Console.WriteLine("{0}) {1}", splitI, Path.GetFileName(splitFilePath));
                });

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

                    if ((int)reader.CurrentTime.TotalSeconds - secsOffset >= options.SplitLength)
                    {
                        // time for a new file
                        writer.Dispose();
                        copyId3();
                        showProgress();
                        createWriter();
                        secsOffset = (int)reader.CurrentTime.TotalSeconds;
                    }

                    writer.Write(frame.RawData, 0, frame.RawData.Length);
                }

                if (writer != null)
                {
                    writer.Dispose();
                    copyId3();
                    showProgress();
                }
            }
        }
Exemple #17
0
        void trimMp3(string input, string output, int startOffset, int endOffset)
        {
            using (Mp3FileReader reader = new Mp3FileReader(input)){
                System.IO.FileStream _fs = new System.IO.FileStream(output, System.IO.FileMode.Create, System.IO.FileAccess.Write);

                Mp3Frame mp3Frame;
                do
                {
                    mp3Frame = reader.ReadNextFrame();
                    if (mp3Frame == null) return;
                    if ((int)reader.CurrentTime.TotalSeconds < startOffset) continue;
                    if ((int)reader.CurrentTime.TotalSeconds >= endOffset) break;

                    _fs.Write(mp3Frame.RawData, 0, mp3Frame.RawData.Length);

                } while (mp3Frame != null);
                _fs.Close();
            }
        }
        private void DoTextToSpeech(object parameters)
        {
            Guid documentId = ((ITextToSpeechInfo)parameters).DocumentId;
            IProgressCallback progressCallback = ((ITextToSpeechInfo)parameters).ProgressCallback;

            progressCallback.Begin();
            progressCallback.StepTo(0);
            progressCallback.SetComment("Loading document...");

            IVfDocumentModel document = GetDocument(documentId);
            VfWebServer webClient = new VfWebServer();

            List<IVfPartModel> parts = Repository.GetPartsByDocumentId(documentId, false);

            progressCallback.SetRange(0, parts.Count);

            FileStream fsFullOut = null;
            BinaryWriter bwFull = null;
            string currentFileName = String.Empty;

            int writedParts = 0;
            //int fileIndex = 0;
            Id3v2Tag id3v2tag = null;

            for (int i = 0; i < parts.Count; i++)
            {
                progressCallback.Increment(1);
                progressCallback.SetComment(parts[i].Text);

                byte[] audioData = null;

                string tempId = webClient.GetTempId();
                Thread.Sleep(1000);
                string cardLink = webClient.GetCardLink(tempId, parts[i].Text);

                byte[] previewPage = webClient.PostPreview(tempId, parts[i].Text/*"У Кремля нет повода менять взгляд на отношения с Минском"*/);

                while (true)
                {
                    if (progressCallback.IsAborting)
                    {
                        Log4.DeveloperLog.Info("Job canceled");
                        break;
                    }

                    Thread.Sleep(2000);
                    audioData = webClient.GetSound(tempId);

                    if ((audioData != null) && ((audioData.Length > 100000) || (i == parts.Count - 1)))
                    {
                        break;
                    }
                    Log4.DeveloperLog.InfoFormat("*** Try get sound again. Bytes: {0} tempid: {1}", audioData.Length, tempId);
                    audioData = null;
                }

                if (audioData == null)
                {
                    Log4.DeveloperLog.Info("Job canceled");
                    break;
                }

                if (writedParts == 0)
                {
                    document.FileIndex++;
                    SaveDocument(document);

                    string bookName = document.Title;
                    string author = document.Author;
                    string group = document.Group;
                    string year = document.Year.ToString();
                    string comments = document.Comments;
                    string genre = document.Genre;

                    string fName = String.Format(@"{1:0000}-{0}", bookName, document.FileIndex);
                    string fDir = String.Format(@"{0}\{1}", document.AudioDirectory, bookName);

                    if (!Directory.Exists(fDir))
                    {
                        Directory.CreateDirectory(fDir);
                    }

                    currentFileName = String.Format(@"{0}\{1}.mp3", fDir, fName);
                    Log4.DeveloperLog.InfoFormat("Current file name: {0}", currentFileName);

                    ///////////////////////////////////////////////////////////
                    // http://www.id3.org/id3v2.3.0
                    ///////////////////////////////////////////////////////////
                    Dictionary<string, string> tags = new Dictionary<string, string>
                        {
                            { "TCON", String.Format("{0}", genre) }, /* Genre */
                            { "TALB", String.Format("{0}", bookName) }, /* Album name */
                            { "TRCK", String.Format("{0}", document.FileIndex) }, /* Track No */
                            { "TIT2", String.Format("{0}", fName) }, /* Name */
                            { "TPE1", String.Format("{0}", author) }, /* Artist */
                            { "TPE2", String.Format("{0}", group) }, /* Group name */
                            { "TYER", String.Format("{0}", year) }, /* year of the song */
                            { "COMM", String.Format("{0}", comments) }
                        };
                    id3v2tag = Id3v2Tag.Create(tags);
                    //id3v2tag = Id3v2xTag.Create();
                }

                fsFullOut = new FileStream(currentFileName, FileMode.OpenOrCreate);
                bwFull = new BinaryWriter(fsFullOut);

                using (MemoryStream ms = new MemoryStream(audioData))
                {
                    using (Mp3FileReader mp3Reader = new Mp3FileReader(ms))
                    {
                        bwFull.Seek(0, SeekOrigin.End);

                        Mp3Frame frame;
                        mp3Reader.CurrentTime = TimeSpan.FromSeconds(1.8);
                        while ((frame = mp3Reader.ReadNextFrame()) != null)
                        {
                            if ((mp3Reader.TotalTime.TotalSeconds - mp3Reader.CurrentTime.TotalSeconds) <= 4)
                            {
                                break;
                            }

                            if (id3v2tag != null)
                            {
                                bwFull.Write(id3v2tag.RawData, 0, id3v2tag.RawData.Length);
                                bwFull.Flush();
                                id3v2tag = null;

                                //Mp3Stream mp3Strm = new Mp3Stream(fsFullOut, Mp3Permissions.ReadWrite);
                            }

                            bwFull.Write(frame.RawData, 0, frame.RawData.Length);
                            bwFull.Flush();
                        }
                        mp3Reader.Close();
                    }
                    ms.Close();
                }

                bwFull.Close();
                fsFullOut.Close();

                parts[i].Processed = true;
                Repository.UpdatePart(parts[i]);
                writedParts = (writedParts == 15) ? 0 : writedParts + 1;

                Log4.DeveloperLog.InfoFormat("Writed Parts: {0}", writedParts);
            }

            progressCallback.End();
            ((MainForm)MainForm).RefreshView();
        }
Exemple #19
0
 private static void PlayPieceOfAFile_t(string srcFilename, double secondIn, double secondOut) {
     IWavePlayer waveOutDevice = new WaveOut();
     using (var reader = new Mp3FileReader(srcFilename)) {
         waveOutDevice.Init(reader);
         Mp3Frame frame;
         while ((frame = reader.ReadNextFrame()) != null) {
             if (reader.CurrentTime.TotalSeconds >= secondIn) {
                 break;
                 //writer.Write(frame.RawData, 0, frame.RawData.Length);
             }
             if (reader.CurrentTime.TotalSeconds >= secondOut)
                 break;
         }
         waveOutDevice.Play();
         int millis = (int)(1000 * (secondOut - secondIn));
         Thread.Sleep(millis);
     }
 }
 public static bool ExportarMp3(MemoryStream mp3Stream, String path, bool disposeStream)
 {
     if (mp3Stream == null) return false;
     try
     {
         File.Delete(path);
         mp3Stream.Seek(0, SeekOrigin.Begin);
         using (var writer = File.Create(path))
         using (var reader = new Mp3FileReader(mp3Stream))
         {
             Mp3Frame frame;
             while ((frame = reader.ReadNextFrame()) != null)
                 writer.Write(frame.RawData, 0, frame.RawData.Length);
         }
         if (disposeStream) mp3Stream.Dispose();
         return true;
     }
     catch
     {
         return false;
     }
 }
Exemple #21
0
 public RawAudioData Mp3ToPcm(string fileName)
 {
     var resStream = new MemoryStream();
     var result = new RawAudioData();
     if (File.Exists(fileName))
     {
         using (var mp3 = new Mp3FileReader(fileName))
         {
             var frame0 = mp3.ReadNextFrame();
             result.SampleRate = frame0.SampleRate;
             result.BitRate = frame0.BitRate;
             mp3.Seek(0, SeekOrigin.Begin);
             mp3.CopyTo(resStream);
         }
     }
     result.Data = resStream.ToArray();
     return result;
 }
Exemple #22
0
        private void processStr(String str)
        {
            files.Clear();
            string[] ContentLines = str.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            int len = ContentLines.Length;
            int index = 0;
            for (int i = 0; i < len; i++)
            {
                string currentLine = ContentLines[i];
                string[] delim = { "." };
                // delimeter
                if (textBox1.Text == string.Empty)
                {
                    if (zhRadioButton.Checked)
                        delim = new string[] { "。" };
                    else if (enRadioButton.Checked)
                        delim = new string[] { ",", "." };
                    else if (jpRadioButton.Checked)
                        delim = new string[] { "。" };
                }
                else
                {
                    delim = textBox1.Text.Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries);
                }

                //
                string[] senSet = currentLine.Split(delim, StringSplitOptions.RemoveEmptyEntries);
                int inLen = senSet.Length;
                for (int j = 0; j < inLen; j++)
                {
                    index++;
                    string destStr = senSet[j];
                    statusLabel.ForeColor = Color.Red;
                    statusLabel.Text = "处理中:"+destStr;
                    // length limit
                    if (destStr.Length > 100)
                    {
                        //Console.WriteLine(destStr);
                        MessageBox.Show("这句话太长了,谷歌娘根本来不及给你读嘛!");
                        continue;
                    }

                    //multi-thread switch
                    if (mThreadCheckBox.Checked)
                    {
                        para par = new para();
                        par.str = senSet[j];
                        par.index = index;
                        Thread newThread = new Thread(new ParameterizedThreadStart(getTTSMT));
                        newThread.Start(par);
                        newThread.Join();
                    }
                    else
                    {
                        getTTS(senSet[j], index);
                        statusLabel.ForeColor = Color.Red;
                        statusLabel.Text = "处理中:" + senSet[j];
                    }
                }
            }
            // status
            statusLabel.Text = "正在进行收尾工作...";
            //// merge all files
            string strFilePattern = prefix + "*.mp3";
            string[] strFiles = Directory.GetFiles(mp3dir, strFilePattern);
            //NAudio
            FileStream fileStream = new FileStream(prefix+".mp3", FileMode.OpenOrCreate);
            foreach (string file in strFiles)
            {
                Mp3FileReader reader = new Mp3FileReader(file);
                if ((fileStream.Position == 0) && (reader.Id3v2Tag != null))
                {
                    fileStream.Write(reader.Id3v2Tag.RawData, 0, reader.Id3v2Tag.RawData.Length);
                }
                Mp3Frame frame;
                while ((frame = reader.ReadNextFrame()) != null)
                {
                    fileStream.Write(frame.RawData, 0, frame.RawData.Length);
                }
                reader.Close();
            }
            fileStream.Close();
            ////
            statusLabel.ForeColor = Color.Black;
            statusLabel.Text = "所有句子全部完成!";

            //
            if (playCheckBox.Checked)
            {
                playMp3(prefix+".mp3");
            }

            if (!saveCheckBox.Checked)
            {
                try
                {
                    File.Delete(prefix + ".mp3");
                }
                catch
                {
                    MessageBox.Show("Something is wrong.");
                }
            }
        }
Exemple #23
0
        private IEnumerable<float[]> LoadSamplesMp3(string aPath)
        {
            using (var reader = new Mp3FileReader(aPath))
            {
                var frames = new List<float[]>();

                while (true)
                {
                    var frame = reader.ReadNextFrame();

                    if (frame == null)
                    {
                        return frames;
                    }

                    frames.AddRange(DecompressMp3(frame));
                }
            }
        }
        private void CutMP3()
        {
            while (true)
            {
                // Check if all threads need to be stopped
                if (StopCurrentThread()) return;

                if (ActiveStatus == 4)
                    break;

                System.Threading.Thread.Sleep(1);
            }

            TimeSpan totalTime = new TimeSpan();
            Mp3Frame frame = null;

            Mp3FileReader reader = new Mp3FileReader(workingDir + "\\export\\totalmp3\\output.mp3");
            if (multi)
            {
                this.CreateDirectoryIfNotExists(outputDir);

                for (int i = 0; i < fragmenten.Count; i++)
                {
                    if (fragmenten[i].Liedje.FileContent == null)
                    {
                        continue;
                    }

                    // Create a frame stream to write to
                    FileStream file = new FileStream(outputDir + "\\" + (i + 1).ToString("00") + " - " + fragmenten[i].Liedje.Artiest + " - " + fragmenten[i].Liedje.Titel + ".mp3", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);

                    // Write the last frame of the previous song if it is available
                    if (frame != null)
                    {
                        file.Write(frame.RawData, 0, frame.RawData.Length);
                    }

                    //
                    TimeSpan d = fragmenten[i].EindTijd - fragmenten[i].BeginTijd;
                    if (!fragmenten[i].FadeInBinnen)
                        d = d.Add(TimeSpan.FromSeconds((fragmenten[i].FadeIn - new DateTime(2000, 1, 1)).TotalSeconds));

                    // Continue as long as there are frames available
                    while ((frame = reader.ReadNextFrame()) != null)
                    {
                        if (reader.CurrentTime.TotalSeconds - totalTime.TotalSeconds < d.TotalSeconds)
                        {
                            file.Write(frame.RawData, 0, frame.RawData.Length);
                            frame = null;
                        }
                        else
                            break;
                    }

                    totalTime = totalTime.Add(d);

                    this.cutMP3++;
                }
            }
            else
            {
                cutMP3 = totalFragments;
                System.IO.File.Copy(workingDir + "\\export\\totalmp3\\output.mp3", outputDir, true);
            }

            ActiveStatus = 5;
            OnUpdated();

            ActiveStatus = 6;
            OnUpdated();
            MessageBox.Show("De playbackband is klaar!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }