コード例 #1
0
        public void SaveData()
        {
            // TODO: Add support for other formats (see: OutputFormat)

            byte[] dataA, dataB;

            if (storeInMemoryUntilSave)
            {
                dataA = (currentFile == 0 ? channelMemoryB : channelMemoryA).ToArray();
                dataB = (currentFile == 1 ? channelMemoryB : channelMemoryA).ToArray();
            }
            else
            {
                var bytesA = Utility.ReadToEnd((currentFile == 0) ? channelStreamB : channelStreamA);
                var bytesB = Utility.ReadToEnd((currentFile == 1) ? channelStreamB : channelStreamA);

                dataA = bytesA.Skip(44).ToArray();
                dataB = bytesB.Skip(44).ToArray();
            }

            var saveDirectory = Config.SavePath.FullName + "/" + channelName + "/";

            if (!Directory.Exists(saveDirectory))
            {
                Directory.CreateDirectory(saveDirectory);
            }
            using (var writer = new WaveWriter(saveDirectory + DateTime.Now.ToString(Config.SaveNameFormat) + ".wav", channelCapture.WaveFormat)) {
                writer.Write(dataA, 0, dataA.Length);
                writer.Write(dataB, 0, dataB.Length);
            }
        }
コード例 #2
0
 /// <summary>
 /// データ wave の書き込み。
 /// </summary>
 /// <param name="filename">ファイル名</param>
 public void WirteData(string filename)
 {
     using (WaveWriter writer = new WaveWriter(filename, this.data.Header))
     {
         writer.Write(this.data.TimeL, this.data.TimeR);
     }
 }
コード例 #3
0
 public void WriteSamplesToFile(float[] samples, int sampleRate, string destination)
 {
     var waveWriter = new WaveWriter(
         destination, BassConstants.NumberOfChannels, sampleRate, BitsPerSample, true);
     waveWriter.Write(samples, samples.Length * FloatLength);
     waveWriter.Close();
 }
コード例 #4
0
        /// <summary>
        /// Save float buffer as ieefloat wave file
        /// </summary>
        /// <param name="buffer">float array</param>
        /// <param name="outFileName">filename</param>
        /// <param name="targetSampleRate">target samplerate </param>
        public void SaveFile(float[] buffer, string outFileName, int targetSampleRate)
        {
            WaveWriter writer = new WaveWriter(outFileName, 1, targetSampleRate, 32, true);

            writer.Write(buffer, buffer.Length << 2);
            writer.Close();
        }
コード例 #5
0
        private void WriteSamplesToWavFile(string pathToFile, int sampleRate, int channels, float[] samples)
        {
            WaveWriter waveWriter = new WaveWriter(pathToFile, channels, sampleRate, 8 * 4, true);

            waveWriter.Write(samples, samples.Length * 4);
            waveWriter.Close();
        }
コード例 #6
0
ファイル: Program.cs プロジェクト: nikkei00/LessonBell63
        static void Main(string[] args)
        {
            using (var wasapiCapture = new WasapiLoopbackCapture())
            {
                wasapiCapture.Initialize();
                var wasapiCaptureSource = new SoundInSource(wasapiCapture);
                using (var stereoSource = wasapiCaptureSource.ToStereo())
                {
                    //using (var writer = MediaFoundationEncoder.CreateWMAEncoder(stereoSource.WaveFormat, "output.wma"))
                    using (var writer = new WaveWriter("output.wav", stereoSource.WaveFormat))
                    {
                        byte[] buffer = new byte[stereoSource.WaveFormat.BytesPerSecond];
                        wasapiCaptureSource.DataAvailable += (s, e) =>
                        {
                            int read = stereoSource.Read(buffer, 0, buffer.Length);
                            writer.Write(buffer, 0, read);
                        };

                        wasapiCapture.Start();

                        Console.ReadKey();

                        wasapiCapture.Stop();
                    }
                }
            }
        }
コード例 #7
0
        public void CSCoreAudioRecording()
        {
            using (capture = new WasapiLoopbackCapture())
            {
                aTimer          = new Timer();
                aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); //jak czas minie, wyłącz nagrywanie
                aTimer.Interval = 8000;                                  //czas nagrywania

                //inicjalizacja urządzenia do nagrywania
                capture.Initialize();

                using (writer = new WaveWriter("dump.wav", capture.WaveFormat))
                {
                    capture.DataAvailable += (s, e) =>
                    {
                        //save the recorded audio
                        writer.Write(e.Data, e.Offset, e.ByteCount);
                    };
                    //start recording
                    capture.Start();
                    aTimer.Enabled = true;
                    Console.WriteLine("Rozpoczęto nagrywanie.");
                    Console.ReadKey();
                }
            }
        }
コード例 #8
0
        private void StartRecord()
        {
            using (WasapiCapture capture = new WasapiLoopbackCapture())
            {
                //if nessesary, you can choose a device here
                //to do so, simply set the device property of the capture to any MMDevice
                //to choose a device, take a look at the sample here: http://cscore.codeplex.com/

                //initialize the selected device for recording
                capture.Initialize();

                //create a wavewriter to write the data to
                using (var stream = new FileStream("dump.wav", FileMode.CreateNew))
                {
                    using (var w = new WaveWriter(stream, capture.WaveFormat))
                    {
                        //setup an eventhandler to receive the recorded data
                        capture.DataAvailable += (s, args) =>
                        {
                            //save the recorded audio
                            w.Write(args.Data, args.Offset, args.ByteCount);
                        };

                        //start recording
                        capture.Start();

                        SpinWait.SpinUntil(() => !_recording);

                        //stop recording
                        capture.Stop();
                    }
                    stream.Flush(true);
                }
            }
        }
コード例 #9
0
        /// <summary>
        /// Writes all audio data of the <paramref name="source" /> to the <paramref name="stream" />.
        /// </summary>
        /// <param name="source">Source which provides the audio data to write to the <paramref name="stream" />.</param>
        /// <param name="stream"><see cref="Stream" /> to store the audio data in.</param>
        /// <exception cref="System.ArgumentNullException">
        /// source
        /// or
        /// stream
        /// </exception>
        /// <exception cref="System.ArgumentException">Stream is not writeable.;stream</exception>
        public static void WriteToWaveStream(this IWaveSource source, Stream stream)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            if (!stream.CanWrite)
            {
                throw new ArgumentException("Stream is not writeable.", "stream");
            }

            using (var writer = new WaveWriter(stream, source.WaveFormat))
            {
                int read;
                var buffer = new byte[source.WaveFormat.BytesPerSecond];
                while ((read = source.Read(buffer, 0, buffer.Length)) > 0)
                {
                    writer.Write(buffer, 0, read);
                }
            }
        }
コード例 #10
0
        public void Test16BitSingleChannelRoundTrip()
        {
            const int    samplesPerSecond = 44_100;
            const double delta            = 1.0 / samplesPerSecond;

            Func <double, double> func = (double t) => Math.Cos(2.0 * Math.PI * t);

            short[] data = new short[samplesPerSecond];
            for (int i = 0; i < samplesPerSecond; ++i)
            {
                data[i] = (short)(short.MaxValue * func(i * delta));
            }

            using var ms = new MemoryStream();
            var writer = new WaveWriter(ms, samplesPerSecond);

            writer.Write(data.Length, data);

            ms.Position = 0;

            var reader = new WaveReader(ms);

            Assert.AreEqual(reader.Format.Channels, 1);
            Assert.AreEqual(reader.Format.SamplesPerSecond, samplesPerSecond);
            Assert.AreEqual(reader.Format.BitsPerSample, 16);

            var channel = reader.GetChannelInt16(0);
            int h       = 0;
            var e       = channel.GetEnumerator();

            while (e.MoveNext())
            {
                Assert.AreEqual(data[h++], e.Current, $"Index: {h}");
            }
        }
コード例 #11
0
        internal static void RecordToWav(string fileName)
        {
            using (WasapiCapture capture = new WasapiLoopbackCapture())
            {
                //if nessesary, you can choose a device here
                //to do so, simply set the device property of the capture to any MMDevice
                //to choose a device, take a look at the sample here: http://cscore.codeplex.com/

                //initialize the selected device for recording
                capture.Initialize();

                //create a wavewriter to write the data to
                using (WaveWriter w = new WaveWriter(fileName, capture.WaveFormat))
                {
                    //setup an eventhandler to receive the recorded data
                    capture.DataAvailable += (s, e) =>
                    {
                        //save the recorded audio
                        w.Write(e.Data, e.Offset, e.ByteCount);
                        Console.Write(".");
                    };

                    //start recording
                    capture.Start();

                    Console.ReadKey();

                    //stop recording
                    capture.Stop();
                }
            }
        }
コード例 #12
0
        /// <summary>
        ///   Recode the file
        /// </summary>
        /// <param name = "fileName">Initial file</param>
        /// <param name = "outFileName">Target file</param>
        /// <param name = "targetSampleRate">Target sample rate</param>
        public void RecodeTheFile(string fileName, string outFileName, int targetSampleRate)
        {
            int      stream = Un4seen.Bass.Bass.BASS_StreamCreateFile(fileName, 0, 0, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_MONO | BASSFlag.BASS_SAMPLE_FLOAT);
            TAG_INFO tags   = new TAG_INFO();

            BassTags.BASS_TAG_GetFromFile(stream, tags);
            int mixerStream = BassMix.BASS_Mixer_StreamCreate(targetSampleRate, 1, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_MONO | BASSFlag.BASS_SAMPLE_FLOAT);

            if (BassMix.BASS_Mixer_StreamAddChannel(mixerStream, stream, BASSFlag.BASS_MIXER_FILTER))
            {
                WaveWriter waveWriter = new WaveWriter(outFileName, mixerStream, true);
                const int  length     = 5512 * 10 * 4;
                float[]    buffer     = new float[length];
                while (true)
                {
                    int bytesRead = Un4seen.Bass.Bass.BASS_ChannelGetData(mixerStream, buffer, length);
                    if (bytesRead == 0)
                    {
                        break;
                    }
                    waveWriter.Write(buffer, bytesRead);
                }
                waveWriter.Close();
            }
            else
            {
                throw new Exception(Un4seen.Bass.Bass.BASS_ErrorGetCode().ToString());
            }
        }
コード例 #13
0
        private void OnDatAvailable(object sender, DataAvailableEventArgs e)
        {
            //register an event handler for the DataAvailable event of
            //the soundInSource
            //Important: use the DataAvailable of the SoundInSource
            //If you use the DataAvailable event of the ISoundIn itself
            //the data recorded by that event might won't be available at the
            //soundInSource yet

            _logger.Debug($"Audio data available - Bytes: {e.ByteCount} Format: {e.Format}");
            //read data from the converedSource
            //important: don't use the e.Data here
            //the e.Data contains the raw data provided by the
            //soundInSource which won't have your target format
            byte[] buffer = new byte[_convertedSource.WaveFormat.BytesPerSecond / 2];
            int    read;

            //keep reading as long as we still get some data
            //if you're using such a loop, make sure that soundInSource.FillWithZeros is set to false
            while ((read = _convertedSource.Read(buffer, 0, buffer.Length)) > 0)
            {
                //write the read data to a file
                // ReSharper disable once AccessToDisposedClosure
                _waveWriter.Write(buffer, 0, read);
            }
        }
コード例 #14
0
 public void WriteWaveData(object sender, DataReadEventArgs ea)
 {
     if (writer != null)
     {
         writer.Write(ea.Data, 0, (int)ea.DataSize);
     }
 }
コード例 #15
0
    public NaudioDemo()
    {
        using (WasapiCapture capture = new WasapiLoopbackCapture()) {
            //if nessesary, you can choose a device here
            //to do so, simply set the device property of the capture to any MMDevice
            //to choose a device, take a look at the sample here: http://cscore.codeplex.com/

            //initialize the selected device for recording
            capture.Initialize();

            //create a wavewriter to write the data to
            using (WaveWriter w = new WaveWriter("dump.wav", capture.WaveFormat)) {
                //setup an eventhandler to receive the recorded data
                capture.DataAvailable += (s, e) =>
                {
                    //save the recorded audio
                    w.Write(e.Data, e.Offset, e.ByteCount);
                };

                //start recording
                capture.Start();

                Thread.Sleep(1000);

                //stop recording
                capture.Stop();
            }
        }
    }
コード例 #16
0
ファイル: MainForm.cs プロジェクト: weespin/Shockzam-BROKEN
        public async Task <MemoryStream> GetLoopbackAudio(int ms)
        {
            var Stream = new MemoryStream();

            using (WasapiCapture virtualaudiodev =
                       new WasapiLoopbackCapture())
            {
                virtualaudiodev.Initialize();
                var soundInSource = new SoundInSource(virtualaudiodev)
                {
                    FillWithZeros = false
                };
                var convertedSource = soundInSource.ChangeSampleRate(44100).ToSampleSource().ToWaveSource(16);
                using (convertedSource = convertedSource.ToMono())
                {
                    using (var waveWriter = new WaveWriter(Stream, convertedSource.WaveFormat))
                    {
                        soundInSource.DataAvailable += (s, e) =>
                        {
                            var buffer = new byte[convertedSource.WaveFormat.BytesPerSecond / 2];
                            int read;
                            while ((read = convertedSource.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                waveWriter.Write(buffer, 0, read);
                            }
                        };
                        virtualaudiodev.Start();
                        Thread.Sleep(ms);
                        virtualaudiodev.Stop();
                    }
                }
            }

            return(Stream);
        }
コード例 #17
0
        public void WriteSamplesToFile(float[] samples, int sampleRate, string destination)
        {
            var waveWriter = new WaveWriter(destination, BassConstants.NumberOfChannels, sampleRate, BitsPerSample, true);

            waveWriter.Write(samples, samples.Length * FloatLength);
            waveWriter.Close();
        }
コード例 #18
0
        public void WriteSamplesToWaveFile(string pathToFile, float[] samples, int sampleRate)
        {
            const int BitsPerSample = 4 * 8;
            var       waveWriter    = new WaveWriter(pathToFile, BassConstants.NumberOfChannels, sampleRate, BitsPerSample, true);

            waveWriter.Write(samples, samples.Length * 4);
            waveWriter.Close();
        }
コード例 #19
0
        public static int Capture(string output_file, int time)
        {
            int sampleRate    = 48000;
            int bitsPerSample = 24;


            //create a new soundIn instance
            using (WasapiCapture soundIn = new WasapiLoopbackCapture())
            {
                //initialize the soundIn instance
                soundIn.Initialize();

                //create a SoundSource around the the soundIn instance
                SoundInSource soundInSource = new SoundInSource(soundIn)
                {
                    FillWithZeros = false
                };

                //create a source, that converts the data provided by the soundInSource to any other format
                IWaveSource convertedSource = soundInSource
                                              .ChangeSampleRate(sampleRate) // sample rate
                                              .ToSampleSource()
                                              .ToWaveSource(bitsPerSample); //bits per sample

                //channels...
                using (convertedSource = convertedSource.ToStereo())
                {
                    //create a new wavefile
                    using (WaveWriter waveWriter = new WaveWriter(output_file, convertedSource.WaveFormat))
                    {
                        //register an event handler for the DataAvailable event of the soundInSource
                        soundInSource.DataAvailable += (s, e) =>
                        {
                            //read data from the converedSource
                            byte[] buffer = new byte[convertedSource.WaveFormat.BytesPerSecond / 2];
                            int    read;

                            //keep reading as long as we still get some data
                            while ((read = convertedSource.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                //write the read data to a file
                                waveWriter.Write(buffer, 0, read);
                            }
                        };

                        //start recording
                        soundIn.Start();

                        //delay and keep recording
                        Thread.Sleep(time);

                        //stop recording
                        soundIn.Stop();
                    }
                }
            }
            return(0);
        }
コード例 #20
0
 /// <summary>
 /// Read Decode Chunk
 /// </summary>
 private void ReadDecodeChunk()
 {
     try {
         Model.ReadDecodeResult = _mp3Stream.Read(Model.Bytes, (int)Model.NumBytesRead, Model.ChunkSize); // Read Decode Result
         _writer.Write(Model.Bytes, Model.ChunkSize);                                                     // Writer Write
     } catch {
         throw;
     }
 }
コード例 #21
0
 /// <summary>
 /// Read Decode Chunk
 /// </summary>
 private void ReadDecodeChunk()
 {
     try {
         _readDecodeResult = _mp3Stream.Read(_bytes, (int)_numBytesRead, _chunkSize); // Read Decode Result
         _writer.Write(_bytes, _chunkSize);                                           // Writer Write
     } catch {
         throw;
     }
 }
コード例 #22
0
    /// <summary>
    /// Write captured Audio to file
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void WriteAudio(object sender, DataAvailableEventArgs e)
    {
        if (audioFile == null)
        {
            return;
        }

        audioFile.Write(e.Data, 0, e.ByteCount);
        //audioFile.flu();
    }
コード例 #23
0
        public MainForm()
        {
            InitializeComponent();

            recordTime = new TimeSpan();

            writeEvent = new EventHandler <DataAvailableEventArgs>((s, e) =>
            {
                writer.Write(e.Data, e.Offset, e.ByteCount);
            });
        }
コード例 #24
0
        private void StartRec(string path)
        {
            form2.Opacity = .1;

            //form2.Hide();

            if (_isRecording == false)
            {
                this.SetScreenArea();

                this.SetVisible(true);

                this._frameCount        = 0;
                this.fps                = 10;
                this.tb_SaveFolder.Text = path;
                fullName                = string.Format(@"{0}\{1}", path, DateTime.Now.ToString("MM_dd_HH_mm_ss"));
                if (checkBox2.Checked)
                {
                    fullName += "_News";
                }
                //string fullName2 = string.Format(@"{0}\{1}_{2}.wav", path, Environment.UserName.ToUpper(), DateTime.Now.ToString("d_MMM_yyyy_HH_mm_ssff"));
                // Save File option
                _writer.Open(
                    fullName + ".avi",
                    this._width,
                    this._height,
                    fps,
                    (VideoCodec)cb_VideoCodec.SelectedValue,
                    (int)(BitRate)this.cb_BitRate.SelectedValue);

                // Start main work
                this.StartRecord();
                this._isRecording = true;
                if (checkBox1.Checked == true)
                {
                    //start audio

                    //wri = new LameMP3FileWriter(@"C:\Temp\test_output.mp3", waveIn.WaveFormat, 32);
                    // wri = new LameMP3FileWriter(fullName + ".wav", waveIn.WaveFormat, 32);

                    capture = new CSCore.SoundIn.WasapiLoopbackCapture();
                    capture.Initialize();
                    w = new WaveWriter(fullName + ".wav", capture.WaveFormat);
                    //setup an eventhandler to receive the recorded data
                    capture.DataAvailable += (s, capData) =>
                    {
                        //save the recorded audio
                        w.Write(capData.Data, capData.Offset, capData.ByteCount);
                    };
                    //start recording
                    capture.Start();
                }
            }
        }
コード例 #25
0
        public MainForm()
        {
            InitializeComponent();

            recordTime = new TimeSpan();
            time       = new System.DateTime(0);
            //streamBuffer = new MemoryStream();
            //streamReader = new WaveFileReader(streamBuffer);
            //sampleRate = 100000;

            writeEvent = new EventHandler <DataAvailableEventArgs>((s, e) =>
            {
                //Console.Write("Timestamp: ");
                //Console.Write(currTime.Ticks);
                //Console.Write(" ");


                //byte[] mybyte = Encoding.UTF8.GetBytes("hello");
                //sw.Write("hello");


                //Console.Write("\n");

                //buffer.Read(e.Data, e.Offset, e.ByteCount);
                writer.Write(e.Data, e.Offset, e.ByteCount);
                //writer.Write(e.ByteCount);
                //Console.WriteLine(e.ByteCount);
                //sw.WriteLine("timestamp: " + time.Ticks);
                time = time.AddTicks(1);
                //resampler = new DmoResampler(capture, 10000);

                //resampler = new DmoResampler(streamReader, 10000);

                //resampler.WriteToWaveStream(sw);


                for (int i = 0; i < e.ByteCount; i += 8)
                {
                    //Console.Write(BitConverter.ToSingle(e.Data, i) + " ");
                    //writer.WriteSample(BitConverter.ToSingle(e.Data, i));

                    /*sw.WriteLine(BitConverter.ToInt32(e.Data, i)
                     + "\t" + BitConverter.ToInt32(e.Data, i + 4));*/

                    /*Console.WriteLine(e.Data[i] + " "
                     + e.Data[i + 1] + " "
                     + e.Data[i + 2] + " "
                     + e.Data[i + 3]);*/
                }
                //sw.WriteLine("\n");

                Console.WriteLine(e.ByteCount);
            });
        }
コード例 #26
0
        public static async Task RecordSample()
        {
            //create a new soundIn instance
            var soundIn = new WasapiCapture();

            //optional: set some properties
            //soundIn.Device = ...
            //...
            soundIn.Device = new DeviceService().InputDevices().First();
            soundIn.Initialize();

            var waveWriter = new WaveWriter(@"C:\Users\Cedric Lampron\Desktop\Test Record\dump.wav", soundIn.WaveFormat);;

            await Task.Run(() =>
            {
                //create a SoundSource around the the soundIn instance
                //this SoundSource will provide data, captured by the soundIn instance
                var soundInSource = new SoundInSource(soundIn)
                {
                    FillWithZeros = false
                };

                //create a source, that converts the data provided by the
                //soundInSource to any other format
                //in this case the "Fluent"-extension methods are being used
                IWaveSource convertedSource = soundInSource
                                              .ToStereo()             //2 channels (for example)
                                              .ChangeSampleRate(8000) // 8kHz sample rate
                                              .ToSampleSource()
                                              .ToWaveSource(16);      //16 bit pcm

                //register an event handler for the DataAvailable event of
                //the soundInSource
                //Important: use the DataAvailable of the SoundInSource
                //If you use the DataAvailable event of the ISoundIn itself
                //the data recorded by that event might won't be available at the
                //soundInSource yet
                soundInSource.DataAvailable += (s, e) =>
                {
                    waveWriter.Write(e.Data, e.Offset, e.ByteCount);
                };

                //we've set everything we need -> start capturing data
                soundIn.Start();
            });

            await Task.Delay(5000);

            soundIn.Stop();
            waveWriter.Dispose();
            waveWriter = null;
            soundIn.Dispose();
            soundIn = null;
        }
コード例 #27
0
ファイル: AudioData.cs プロジェクト: gitter-badger/dEngine
        /// <inheritdoc />
        protected override void BeforeSerialization()
        {
            base.BeforeSerialization();

            var outputStream = new MemoryStream();
            var encoder      = new WaveWriter(outputStream, AudioSource.WaveFormat);

            var buffer = AudioSource.ToByteArray();

            encoder.Write(buffer, 0, buffer.Length);
            _bytes = outputStream.ToArray();
        }
コード例 #28
0
ファイル: Form1.cs プロジェクト: pjvermun/SpotifyRipper-
 private void startRecording(string name)
 {
     capture = new WasapiLoopbackCapture();
     capture.Initialize();
     //var writer = MediaFoundationEncoder.CreateMP3Encoder(capture.WaveFormat, name + ".mp3", 320000);
     writer = new WaveWriter("./recorded/" + name + ".wav", capture.WaveFormat);
     capture.DataAvailable += (s, capData) =>
     {
         writer.Write(capData.Data, capData.Offset, capData.ByteCount);
     };
     capture.Start();
 }
コード例 #29
0
    IEnumerator SaveWAVRoutine(Stream fileStream, bool normalize)
    {
        playback.Stop( );
        playback.psg.audioSource.enabled = false;
        playback.follow     = false;
        data.currentPattern = 0;

        m_OperationInProgress = true;

        BinaryWriter bw = new BinaryWriter(fileStream);

        playback.Play(true, true);

        List <double> samples = new List <double> ( );

        int c = 0;

        while (playback.isPlaying)
        {
            playback.psg.ManualClock( );

            double left, right;
            playback.psg.chip.Render(out left, out right);
            samples.Add(left);
            samples.Add(right);

            m_Progress = playback.songProgress * 100;

            c++;
            if (c > 44100)
            {
                c = 0;
                yield return(null);
            }
        }

        m_Progress = 100;
        yield return(null);

        WaveWriter.Write(bw, samples.ToArray( ), 2, ( uint )AudioSettings.outputSampleRate, 16, normalize);

        m_OperationInProgress = false;

        playback.psg.audioSource.enabled = true;
        playback.psg.enabled             = false;
        playback.psg.enabled             = true;
        playback.follow = true;
        playback.Stop( );

        m_Progress = 100;
        yield return(null);
    }
コード例 #30
0
        public static void StartRecording(String fileName, int bitRate = 192000)
        {
            capture = new WasapiLoopbackCapture();

            capture.Initialize();

            wasapiCaptureSource = new SoundInSource(capture);
            stereoSource        = wasapiCaptureSource.ToStereo();

            switch (System.IO.Path.GetExtension(fileName))
            {
            case ".mp3":
                encoderWriter = MediaFoundationEncoder.CreateMP3Encoder(stereoSource.WaveFormat, fileName, bitRate);
                writerType    = WriterType.EncoderWriter;
                break;

            case ".wma":
                encoderWriter = MediaFoundationEncoder.CreateWMAEncoder(stereoSource.WaveFormat, fileName, bitRate);
                writerType    = WriterType.EncoderWriter;
                break;

            case ".aac":
                encoderWriter = MediaFoundationEncoder.CreateAACEncoder(stereoSource.WaveFormat, fileName, bitRate);
                writerType    = WriterType.EncoderWriter;
                break;

            case ".wav":
                waveWriter = new WaveWriter(fileName, capture.WaveFormat);
                writerType = WriterType.WaveWriter;
                break;
            }

            switch (writerType)
            {
            case WriterType.EncoderWriter:
                capture.DataAvailable += (s, e) =>
                {
                    encoderWriter.Write(e.Data, e.Offset, e.ByteCount);
                };
                break;

            case WriterType.WaveWriter:
                capture.DataAvailable += (s, e) =>
                {
                    waveWriter.Write(e.Data, e.Offset, e.ByteCount);
                };
                break;
            }

            // Start recording
            capture.Start();
        }
コード例 #31
0
        void OnData(object sender, DataAvailableEventArgs e)
        {
            _tracker.OnData(e.Format.BytesToMilliseconds(e.ByteCount));

            if (_writer != null)
            {
                if (_recordStartTime == 0)
                {
                    _recordStartTime = _tracker.CurrentTimeAtBeginningOfLastRecordedSample;
                }
                lock (_writer) _writer.Write(e.Data, 0, e.ByteCount);
            }
        }
コード例 #32
0
 private void SaveSegment(int segCount, Array testbuf)
 {
     var writer =
         new WaveWriter(
             File.Create(Path.Combine(segmentsFolder,
                                      string.Format("Segment_{0}.wav", segCount.ToString("D3")))),
             new WaveFormatEx(waveOutSamplesPerSecond, 16, 1));
     writer.Write((short[]) testbuf);
     writer.Close();
 }
コード例 #33
0
        public float[] RecordFromMicrophoneToFile(string pathToFile, int sampleRate, int secondsToRecord)
        {
            int stream = Bass.BASS_RecordStart(sampleRate, 1, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_MONO | BASSFlag.BASS_SAMPLE_FLOAT, null, IntPtr.Zero);

            if (stream == 0)
            {
                throw new Exception(Bass.BASS_ErrorGetCode().ToString());
            }

            int mixerStream = BassMix.BASS_Mixer_StreamCreate(sampleRate, 1, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_MONO | BASSFlag.BASS_SAMPLE_FLOAT);
            if (mixerStream == 0)
            {
                throw new Exception(Bass.BASS_ErrorGetCode().ToString());
            }

            if (!BassMix.BASS_Mixer_StreamAddChannel(mixerStream, stream, BASSFlag.BASS_MIXER_FILTER))
            {
                throw new Exception(Bass.BASS_ErrorGetCode().ToString());
            }

            float[] samples = ReadSamplesFromContinuousMixedStream(sampleRate, secondsToRecord, mixerStream);
            using (WaveWriter waveWriter = new WaveWriter(pathToFile, mixerStream, true))
            {
                waveWriter.Write(samples, samples.Length);
                waveWriter.Close();
            }

            Bass.BASS_StreamFree(mixerStream);
            Bass.BASS_StreamFree(stream);

            return samples;
        }
コード例 #34
0
ファイル: BassProxy.cs プロジェクト: remy22/AudioVSTToolbox
 /// <summary>
 ///   Recode the file
 /// </summary>
 /// <param name = "fileName">Initial file</param>
 /// <param name = "outFileName">Target file</param>
 /// <param name = "targetSampleRate">Target sample rate</param>
 public void RecodeTheFile(string fileName, string outFileName, int targetSampleRate)
 {
     int stream = Un4seen.Bass.Bass.BASS_StreamCreateFile(fileName, 0, 0, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_MONO | BASSFlag.BASS_SAMPLE_FLOAT);
     TAG_INFO tags = new TAG_INFO();
     BassTags.BASS_TAG_GetFromFile(stream, tags);
     int mixerStream = BassMix.BASS_Mixer_StreamCreate(targetSampleRate, 1, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_MONO | BASSFlag.BASS_SAMPLE_FLOAT);
     if (BassMix.BASS_Mixer_StreamAddChannel(mixerStream, stream, BASSFlag.BASS_MIXER_FILTER))
     {
         WaveWriter waveWriter = new WaveWriter(outFileName, mixerStream, true);
         const int length = 5512*10*4;
         float[] buffer = new float[length];
         while (true)
         {
             int bytesRead = Un4seen.Bass.Bass.BASS_ChannelGetData(mixerStream, buffer, length);
             if (bytesRead == 0)
                 break;
             waveWriter.Write(buffer, bytesRead);
         }
         waveWriter.Close();
     }
     else
         throw new Exception(Un4seen.Bass.Bass.BASS_ErrorGetCode().ToString());
 }
コード例 #35
0
        public void RecodeFileToMonoWave(string pathToFile, string outputPathToFile, int targetSampleRate)
        {
            int stream = Bass.BASS_StreamCreateFile(pathToFile, 0, 0, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_MONO | BASSFlag.BASS_SAMPLE_FLOAT);
            TAG_INFO tags = new TAG_INFO();
            BassTags.BASS_TAG_GetFromFile(stream, tags);
            int mixerStream = BassMix.BASS_Mixer_StreamCreate(targetSampleRate, 1, BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_MONO | BASSFlag.BASS_SAMPLE_FLOAT);
            if (!BassMix.BASS_Mixer_StreamAddChannel(mixerStream, stream, BASSFlag.BASS_MIXER_FILTER))
            {
                throw new Exception(Bass.BASS_ErrorGetCode().ToString());
            }

            WaveWriter waveWriter = new WaveWriter(outputPathToFile, mixerStream, true);
            const int Length = 5512 * 10 * 4;
            float[] buffer = new float[Length];
            while (true)
            {
                int bytesRead = Bass.BASS_ChannelGetData(mixerStream, buffer, Length);
                if (bytesRead == 0)
                {
                    break;
                }

                waveWriter.Write(buffer, bytesRead);
            }

            waveWriter.Close();
        }
コード例 #36
0
		/// <summary>
		/// Save float buffer as ieefloat wave file
		/// </summary>
		/// <param name="buffer">float array</param>
		/// <param name="outFileName">filename</param>
		/// <param name="targetSampleRate">target samplerate </param>
		public void SaveFile(float[] buffer, string outFileName, int targetSampleRate) {
			WaveWriter writer = new WaveWriter(outFileName, 1, targetSampleRate, 32, true);
			writer.Write(buffer, buffer.Length << 2);
			writer.Close();
		}
コード例 #37
0
 public void WriteSamplesToWaveFile(string pathToFile, float[] samples, int sampleRate)
 {
     const int BitsPerSample = 4 * 8;
     var waveWriter = new WaveWriter(pathToFile, BassConstants.NumberOfChannels, sampleRate, BitsPerSample, true);
     waveWriter.Write(samples, samples.Length * 4);
     waveWriter.Close();
 }
コード例 #38
0
        public bool SliceSample()
        {
            Stop();
            int stream = Bass.BASS_StreamCreateFile(filePath, 0, 0, BASSFlag.BASS_SAMPLE_MONO | BASSFlag.BASS_STREAM_DECODE);

            long tLength = Bass.BASS_ChannelGetLength(stream);
            double seconds = (SelectionEnd - SelectionBegin).TotalSeconds;

            /* byte lengths */

            int boffset = (int)Bass.BASS_ChannelSeconds2Bytes(stream, SelectionBegin.TotalSeconds);
            int blength = (int)Bass.BASS_ChannelSeconds2Bytes(stream, seconds);

            Bass.BASS_ChannelSetPosition(stream, boffset, BASSMode.BASS_POS_BYTES);

            BASS_CHANNELINFO info = new BASS_CHANNELINFO();
            Bass.BASS_ChannelGetInfo(stream, info);
            // create the sample
            short[] data = new short[blength]; //, putdata = new byte[blength];
            Bass.BASS_ChannelGetData(stream, data, blength);

            string f = filePath.Substring(0, filePath.LastIndexOf("\\") + 1) + "temp.wav";

            WaveWriter w = new WaveWriter(f, stream, 16, true);
            w.Write(data, blength);
            w.Close();

            return OpenFile(f);
        }