Example #1
0
        private static byte[] SlowAudio(byte[] mp3, float newTempo = 0.95f, float newPitch = 1.2f, float newRate = .8f)
        {
            const int BUFFER_SIZE = 1024 * 16;
            byte[] buffer = new byte[BUFFER_SIZE];
            var format = new WaveFormat();

            try
            {
                using (var output = new MemoryStream())
                {

                    File.Delete("temp.wav");
                    File.Delete("temp2.wav");

                    using (var mp3Stream = new MemoryStream(mp3))
                    using (Mp3FileReader reader = new Mp3FileReader(mp3Stream))
                    {
                        WaveFileWriter.CreateWaveFile("temp.wav", reader);
                    }

                    using (WaveFileReader reader = new WaveFileReader("temp.wav"))
                    {
                        int numChannels = reader.WaveFormat.Channels;

                        if (numChannels > 2)
                            throw new Exception("SoundTouch supports only mono or stereo.");

                        int sampleRate = reader.WaveFormat.SampleRate;

                        int bitPerSample = reader.WaveFormat.BitsPerSample;

                        SoundStretcher stretcher = new SoundStretcher(sampleRate, numChannels);
                        var writer = new NAudio.Lame.LameMP3FileWriter(output, new WaveFormat(sampleRate, 16, numChannels), 128);

                        stretcher.Tempo = newTempo;
                        stretcher.Pitch = newPitch;
                        stretcher.Rate = newRate;

                        short[] buffer2 = null;

                        if (bitPerSample != 16 && bitPerSample != 8)
                        {
                            throw new Exception("Not implemented yet.");
                        }

                        if (bitPerSample == 8)
                        {
                            buffer2 = new short[BUFFER_SIZE];
                        }

                        bool finished = false;

                        while (true)
                        {
                            int bytesRead = 0;
                            if (!finished)
                            {
                                bytesRead = reader.Read(buffer, 0, BUFFER_SIZE);

                                if (bytesRead == 0)
                                {
                                    finished = true;
                                    stretcher.Flush();
                                }
                                else
                                {
                                    if (bitPerSample == 16)
                                    {
                                        stretcher.PutSamplesFromBuffer(buffer, 0, bytesRead);
                                    }
                                    else if (bitPerSample == 8)
                                    {
                                        for (int i = 0; i < BUFFER_SIZE; i++)
                                            buffer2[i] = (short)((buffer[i] - 128) * 256);
                                        stretcher.PutSamples(buffer2);
                                    }
                                }
                            }
                            bytesRead = stretcher.ReceiveSamplesToBuffer(buffer, 0, BUFFER_SIZE);
                            writer.Write(buffer, 0, bytesRead);

                            if (finished && bytesRead == 0)
                                break;
                        }
                        reader.Close();
                        writer.Close();
                    }

                    return output.ToArray();
                }
            }
            finally
            {
                File.Delete("temp.wav");
                File.Delete("temp2.wav");
            }

            /////////////////////////////
        }
Example #2
0
        private static void Concatenate(string outputFile, IEnumerable<byte[]> mp3s)
        {
            int i = 0;
            byte[] buffer = new byte[1024];
            NAudio.Lame.LameMP3FileWriter mp3FileWriter = null;
            var format = new WaveFormat();
            byte[][] silence = new byte[][] { new byte[1], new byte[1], new byte[1] };

            try
            {

                mp3FileWriter = new NAudio.Lame.LameMP3FileWriter(outputFile, format, 128);
                silence = new byte[][] {
                    new byte[(format.AverageBytesPerSecond * 1)],
                    new byte[(format.AverageBytesPerSecond * 2)],
                    new byte[(format.AverageBytesPerSecond * 3)],
                };
                mp3FileWriter.Write(silence[1], 0, silence[1].Length);

                foreach (byte[] mp3 in mp3s)
                {
                    i++;

                    File.Delete("temp.wav");
                    File.Delete("temp2.wav");

                    using (var mp3Stream = new MemoryStream(mp3))
                    using (Mp3FileReader reader = new Mp3FileReader(mp3Stream))
                    {
                        WaveFileWriter.CreateWaveFile("temp.wav", reader);
                    }

                    using (WaveFileReader reader = new WaveFileReader("temp.wav"))
                    {
                        if (!reader.WaveFormat.Equals(format))
                        {
                            using (var conversionStream = new WaveFormatConversionStream(format, reader))
                            {
                                WaveFileWriter.CreateWaveFile("temp2.wav", conversionStream);
                            }
                            using (WaveFileReader reader2 = new WaveFileReader("temp2.wav"))
                            {
                                int read;
                                while ((read = reader2.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    mp3FileWriter.Write(buffer, 0, read);
                                }
                            }
                        }
                        else
                        {
                            int read;
                            while ((read = reader.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                mp3FileWriter.Write(buffer, 0, read);
                            }
                        }
                    }
                    mp3FileWriter.Write(silence[1], 0, silence[1].Length);
                }
                mp3FileWriter.Flush();
            }
            finally
            {
                File.Delete("temp.wav");
                File.Delete("temp2.wav");
                if (mp3FileWriter != null)
                {
                    mp3FileWriter.Dispose();
                }
            }
        }
Example #3
0
        private async Task ConvertFiles(Func <BackgroundTaskControl, Task> callBack, BackgroundTaskControl bgtc)
        {
            await Task.Delay(250); // give time for rendering changes

            WaveStream inputStream = null;

            for (int i = 0; i < selectedSongs.Count(); i++)
            {
                try
                {
                    if (selectedSongs[i].FilePath.EndsWith(".ogg"))
                    {
                        inputStream = new VorbisWaveReader(selectedSongs[i].FilePath);
                    }
                    else if (selectedSongs[i].FilePath.EndsWith(".flac"))
                    {
                        inputStream = new FlacReader(selectedSongs[i].FilePath);
                    }
                    else
                    {
                        inputStream = new AudioFileReader(selectedSongs[i].FilePath);
                    }

                    string selectedFileType = "";
                    Dispatcher.Invoke(() =>
                    {
                        selectedFileType                 = OutputFileTypeComboBox.SelectedItem as string;
                        WaitingLabel.Content             = $"Now converting {selectedSongs[i].Name} to {selectedFileType.Substring(selectedFileType.IndexOf("(") + 1, 4)}";
                        bgtc.BackgroundTaskLabel.Content = WaitingLabel.Content;
                    });
                    if (selectedFileType.EndsWith("(.mp3)"))
                    {
                        using (FileStream fileStream = File.Create($"{outputPath}/{selectedSongs[i].Name}.mp3"))
                            using (NAudio.Lame.LameMP3FileWriter writer = new NAudio.Lame.LameMP3FileWriter(fileStream, inputStream.WaveFormat, 320000))
                            {
                                byte[] buffer    = new byte[4096];
                                int    bytesRead = 0;
                                do
                                {
                                    bytesRead = inputStream.Read(buffer, 0, buffer.Length);
                                    writer.Write(buffer, 0, bytesRead);
                                } while (bytesRead > 0);
                            }

                        TagLib.File outputTags = TagLib.File.Create($"{outputPath}/{selectedSongs[i].Name}.mp3");
                        TagLib.File inputTags  = TagLib.File.Create(selectedSongs[i].FilePath);
                        outputTags.Tag.Album        = inputTags.Tag.Album;
                        outputTags.Tag.AlbumArtists = inputTags.Tag.AlbumArtists;
                        outputTags.Tag.Genres       = inputTags.Tag.Genres;
                        outputTags.Tag.Performers   = inputTags.Tag.Performers;
                        outputTags.Tag.Year         = inputTags.Tag.Year;
                        outputTags.Tag.Pictures     = inputTags.Tag.Pictures;
                        outputTags.Tag.Title        = inputTags.Tag.Title;
                        outputTags.Tag.Track        = inputTags.Tag.Track;
                        outputTags.Save();
                        inputTags.Dispose();
                        outputTags.Dispose();
                    }
                    else if (selectedFileType.EndsWith("(.wav)"))
                    {
                        using (FileStream fileStream = File.Create($"{outputPath}/{selectedSongs[i].Name}.wav"))
                            using (WaveFileWriter writer = new WaveFileWriter(fileStream, inputStream.WaveFormat))
                            {
                                byte[] buffer    = new byte[4096];
                                int    bytesRead = 0;
                                do
                                {
                                    bytesRead = inputStream.Read(buffer, 0, buffer.Length);
                                    writer.Write(buffer, 0, bytesRead);
                                } while (bytesRead > 0);
                            }

                        TagLib.File outputTags = TagLib.File.Create($"{outputPath}/{selectedSongs[i].Name}.wav");
                        TagLib.File inputTags  = TagLib.File.Create(selectedSongs[i].FilePath);
                        outputTags.Tag.Album        = inputTags.Tag.Album;
                        outputTags.Tag.AlbumArtists = inputTags.Tag.AlbumArtists;
                        outputTags.Tag.Genres       = inputTags.Tag.Genres;
                        outputTags.Tag.Performers   = inputTags.Tag.Performers;
                        outputTags.Tag.Year         = inputTags.Tag.Year;
                        outputTags.Tag.Pictures     = inputTags.Tag.Pictures;
                        outputTags.Tag.Title        = inputTags.Tag.Title;
                        outputTags.Tag.Track        = inputTags.Tag.Track;
                        outputTags.Save();
                        inputTags.Dispose();
                        outputTags.Dispose();
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show("Error converting " + selectedSongs[i].FilePath + ", message: " + e.Message);
                    await callBack(bgtc);

                    inputStream?.Close();
                    return;
                }
                finally
                {
                    inputStream?.Close();
                }
            }
            await callBack(bgtc);

            MessageBox.Show("File(s) successfully converted!");
        }
        private async Task ConvertFiles(Func <BackgroundTaskControl, Task> callBack, BackgroundTaskControl bgtc)
        {
            await Task.Delay(250); // give time for rendering changes

            WaveStream inputStream = null;

            for (int i = 0; i < filePaths.Count(); i++)
            {
                try
                {
                    if (filePaths[i].EndsWith(".ogg"))
                    {
                        inputStream = new VorbisWaveReader(filePaths[i]);
                    }
                    else if (filePaths[i].EndsWith(".flac"))
                    {
                        inputStream = new FlacReader(filePaths[i]);
                    }
                    else
                    {
                        inputStream = new AudioFileReader(filePaths[i]);
                    }

                    string selectedFileType = "";
                    Dispatcher.Invoke(() =>
                    {
                        selectedFileType     = OutputFileTypeComboBox.SelectedItem as string;
                        WaitingLabel.Content = $"Now converting {safeFileNames[i]} to {selectedFileType.Substring(selectedFileType.IndexOf("(")+1,4)}";
                        if (bgtc != null)
                        {
                            bgtc.BackgroundTaskLabel.Content = WaitingLabel.Content;
                        }
                    });
                    if (selectedFileType.EndsWith("(.mp3)"))
                    {
                        string monoStereoSelection = "";
                        Dispatcher.Invoke(() =>
                        {
                            monoStereoSelection = MSConvertComboBox.SelectedItem as string;
                        });
                        if (inputStream.WaveFormat.BitsPerSample == 16)
                        {
                            IWaveProvider provider = MonoStereoConvert16(inputStream, monoStereoSelection == "Mono");
                            using (FileStream fileStream = File.Create($"{outputPath}/{safeFileNames[i]}.mp3"))
                                using (NAudio.Lame.LameMP3FileWriter writer = new NAudio.Lame.LameMP3FileWriter(fileStream, provider.WaveFormat, 320000))
                                {
                                    byte[] buffer    = new byte[4096];
                                    int    bytesRead = 0;
                                    do
                                    {
                                        bytesRead = provider.Read(buffer, 0, buffer.Length);
                                        writer.Write(buffer, 0, bytesRead);
                                    } while (bytesRead > 0);
                                }
                        }
                        else if (inputStream.WaveFormat.BitsPerSample == 32)
                        {
                            ISampleProvider provider = MonoStereoConvert32(inputStream as ISampleProvider, monoStereoSelection == "Mono");
                            using (FileStream fileStream = File.Create($"{outputPath}/{safeFileNames[i]}.mp3"))
                                using (NAudio.Lame.LameMP3FileWriter writer = new NAudio.Lame.LameMP3FileWriter(fileStream, provider.WaveFormat, 320000))
                                {
                                    byte[] buffer    = new byte[4096];
                                    int    bytesRead = 0;
                                    do
                                    {
                                        var providerAsWave = provider.ToWaveProvider(); // need to write with bytes not floats
                                        bytesRead = providerAsWave.Read(buffer, 0, buffer.Length);
                                        writer.Write(buffer, 0, bytesRead);
                                    } while (bytesRead > 0);
                                }
                        }


                        TagLib.File outputTags = TagLib.File.Create($"{outputPath}//{safeFileNames[i]}.mp3");
                        TagLib.File inputTags  = TagLib.File.Create(filePaths[i]);
                        outputTags.Tag.Album        = inputTags.Tag.Album;
                        outputTags.Tag.AlbumArtists = inputTags.Tag.AlbumArtists;
                        outputTags.Tag.Genres       = inputTags.Tag.Genres;
                        outputTags.Tag.Performers   = inputTags.Tag.Performers;
                        outputTags.Tag.Year         = inputTags.Tag.Year;
                        outputTags.Tag.Pictures     = inputTags.Tag.Pictures;
                        outputTags.Tag.Title        = inputTags.Tag.Title;
                        outputTags.Tag.Track        = inputTags.Tag.Track;
                        outputTags.Save();
                        inputTags.Dispose();
                        outputTags.Dispose();
                    }
                    //else if (selectedFileType.EndsWith("(.wma)"))
                    //{
                    //    FileStream fileStream = File.Create($"c:/temp/conversiontest/{safeFileName}.wma");
                    //    fileStream.Close();
                    //    using (MediaFoundationEncoder writer = new MediaFoundationEncoder(new NAudio.MediaFoundation.MediaType(inputStream.WaveFormat)))
                    //    {
                    //        writer.Encode($"c:/temp/conversiontest/{safeFileName}.wma", inputStream);
                    //    }
                    //}
                    else if (selectedFileType.EndsWith("(.wav)"))
                    {
                        string monoStereoSelection = "";
                        Dispatcher.Invoke(() =>
                        {
                            monoStereoSelection = MSConvertComboBox.SelectedItem as string;
                        });
                        if (inputStream.WaveFormat.BitsPerSample == 16)
                        {
                            IWaveProvider provider = MonoStereoConvert16(inputStream, monoStereoSelection == "Mono");
                            using (FileStream fileStream = File.Create($"{outputPath}/{safeFileNames[i]}.wav"))
                                using (WaveFileWriter writer = new WaveFileWriter(fileStream, provider.WaveFormat))
                                {
                                    byte[] buffer    = new byte[4096];
                                    int    bytesRead = 0;
                                    do
                                    {
                                        bytesRead = provider.Read(buffer, 0, buffer.Length);
                                        writer.Write(buffer, 0, bytesRead);
                                    } while (bytesRead > 0);
                                }
                        }
                        else if (inputStream.WaveFormat.BitsPerSample == 32)
                        {
                            ISampleProvider provider = MonoStereoConvert32(inputStream as ISampleProvider, monoStereoSelection == "Mono");
                            using (FileStream fileStream = File.Create($"{outputPath}/{safeFileNames[i]}.wav"))
                                using (WaveFileWriter writer = new WaveFileWriter(fileStream, provider.WaveFormat))
                                {
                                    byte[] buffer    = new byte[4096];
                                    int    bytesRead = 0;
                                    do
                                    {
                                        var providerAsWave = provider.ToWaveProvider(); // need to write with bytes not floats
                                        bytesRead = providerAsWave.Read(buffer, 0, buffer.Length);
                                        writer.Write(buffer, 0, bytesRead);
                                    } while (bytesRead > 0);
                                }
                        }
                        TagLib.File outputTags = TagLib.File.Create($"{outputPath}/{safeFileNames[i]}.wav");
                        TagLib.File inputTags  = TagLib.File.Create(filePaths[i]);
                        outputTags.Tag.Album        = inputTags.Tag.Album;
                        outputTags.Tag.AlbumArtists = inputTags.Tag.AlbumArtists;
                        outputTags.Tag.Genres       = inputTags.Tag.Genres;
                        outputTags.Tag.Performers   = inputTags.Tag.Performers;
                        outputTags.Tag.Year         = inputTags.Tag.Year;
                        outputTags.Tag.Pictures     = inputTags.Tag.Pictures;
                        outputTags.Tag.Title        = inputTags.Tag.Title;
                        outputTags.Tag.Track        = inputTags.Tag.Track;
                        outputTags.Save();
                        inputTags.Dispose();
                        outputTags.Dispose();
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show("Error converting " + filePaths[i] + ", message: " + e.Message);
                    //just move onto the next song
                }
                finally
                {
                    (inputStream as WaveStream)?.Close();
                }
            }
            await callBack(bgtc);

            MessageBox.Show("File(s) successfully converted!");
        }
Example #5
0
 static void waveIn_DataAvailable(object sender, NAudio.Wave.WaveInEventArgs e)
 {
     waveFileWriter.Write(e.Buffer, 0, e.BytesRecorded);
 }