public static bool InputFieldTwoWay <T>(CompositeDisposable cd, IEngine engine, InputField mid, IWriteable <T> dst, Func <string, T> dstConverter, IReadable <T> src, Func <T, string> srcConverter) { if (!mid) { return(NotBinded()); } engine.Reader(cd, new object[] { src }, () => { if (Equals(dstConverter(mid.text), src.Read())) { return; } mid.text = srcConverter(src.Read()); }); UnityAction <string> action = text => { if (srcConverter(src.Read()) == text) { return; } dst.Write(dstConverter(text)); }; mid.onValueChanged.AddListener(action); cd.Add(new DisposableAction(() => mid.onValueChanged.RemoveListener(action))); return(true); }
public static bool Tabs <T>(CompositeDisposable cd, IEngine engine, Map map, string[] tabs, string[] toggles, IWriteable <T> dst, Func <string, T> dstConverter, IReadable <T> src, Func <T, string> srcConverter) { engine.Reader(cd, Dep.On(src), () => { string selected = srcConverter(src.Read()); for (int i = 0, n = tabs.Length; i < n; ++i) { // TODO Fade animation map.Get(tabs[i]).SetActive(tabs[i] == selected); } }); for (int i = 0, n = toggles.Length; i < n; ++i) { string tab = tabs[i]; string toggle = toggles[i]; ToggleIsOn(cd, engine, map.GetComponent <Toggle>(toggles[i]), src, t => srcConverter(t) == tab ); ToggleChange(cd, engine, map.GetComponent <Toggle>(toggles[i]), b => { if (b) { dst.Write(dstConverter(tab)); } } ); } return(true); }
/// Utility function to serialize a writeable directly in memory using a byte[] public static byte[] Ser_vec(IWriteable thing) { var stream = new MemoryStream(); Serialize(stream, thing); return(stream.ToArray()); }
/// <summary> /// Record sound made in Mic and save it to a wave file /// </summary> /// <param name="wavefile">name of the wave file with extension</param> public void CaptureMicToWave(string wavefile) { int i = 0; string extension = ".wav"; foreach (var device in WaveIn.Devices) { _waveIn = new WaveInEvent(new WaveFormat(44100, 16, device.Channels)); _waveIn.Device = i++; _waveIn.Initialize(); _waveIn.Start(); var waveInToSource = new SoundInSource(_waveIn); _source = waveInToSource; var notifyStream = new SingleBlockNotificationStream(_source); _source = notifyStream.ToWaveSource(16); _writerBuffer = new byte[_source.WaveFormat.BytesPerSecond]; wavefile = string.Format("{0}{1}{2}", wavefile.Remove(wavefile.LastIndexOf(extension) - (i > 1 ? 1 : 0)), i, extension); _writer = new WaveWriter(wavefile, _source.WaveFormat); waveInToSource.DataAvailable += (s, e) => { int read = 0; while ((read = _source.Read(_writerBuffer, 0, _writerBuffer.Length)) > 0) { _writer.Write(_writerBuffer, 0, read); } }; } }
public static Span <byte> AsSpan(this IWriteable w) { var s = new MemoryStream(); w.WriteTo(s); return(s.AsSpan()); }
public void WriteTo(IWriteable s) { byte[] b; // magic number "MThd" (0x4D546864) b = new byte[] { 0x4D, 0x54, 0x68, 0x64 }; s.Write(b, 0, b.Length); // Header Length 6 (0x00000006) b = new byte[] { 0x00, 0x00, 0x00, 0x06 }; s.Write(b, 0, b.Length); // format b = new byte[] { 0x00, 0x01 }; s.Write(b, 0, b.Length); // number of tracks short v = (short)Tracks.Count; b = new [] { (byte)((v >> 8) & 0xFF), (byte)(v & 0xFF) }; s.Write(b, 0, b.Length); v = MidiUtils.QuarterTime; b = new [] { (byte)((v >> 8) & 0xFF), (byte)(v & 0xFF) }; s.Write(b, 0, b.Length); for (int i = 0, j = Tracks.Count; i < j; i++) { Tracks[i].WriteTo(s); } }
internal static void WriteVariableInt(IWriteable s, int value) { var array = new byte[4]; var n = 0; do { array[n++] = (byte)(value & 0x7F & 0xFF); value >>= 7; } while (value > 0); while (n > 0) { n--; if (n > 0) { s.WriteByte((byte)(array[n] | 0x80)); } else { s.WriteByte(array[n]); } } }
public ClassicPlayer( GenieNanoCamera genieNanoCamera, MockCamera mockCamera, MotorController motorController, IWriteable <ClassicPlayerSettings> settings, IWriteable <ClassicImageProcessorSettings> imgProcSettings, ILogger <ClassicPlayer> logger, ILoggerFactory loggerFactory) { _settings = settings; _logger = logger; _imgProcessor = new ClassicImageProcessor(imgProcSettings); _motorController = motorController; var channels = new VideoChannel[] { new VideoChannel("Image", "Raw Image"), new VideoChannel("EdgeDetection", "Image after EdgeDetection"), }; _videoInterface = new VideoInterface(channels, loggerFactory, nameof(ClassicPlayer)); if (genieNanoCamera.PeripheralState == PeripheralState.Ready) { _camera = genieNanoCamera; } else { _camera = mockCamera; } }
protected override void OnOpen() { _validated = Context.QueryString["token"] == _token; if (!_validated) { Context.WebSocket.Close(4000); } _capture = new WasapiLoopbackCapture(0, new WaveFormat()); _capture.Initialize(); _capture.Start(); var wsStream = new WebSocketStream(this); Console.WriteLine($"Captured audio format: {_capture.WaveFormat}"); IWriteable encoder = null; switch (_format) { case AudioFormat.AAC: encoder = new AacEncoder(_capture.WaveFormat, wsStream, 128000, TranscodeContainerTypes.MFTranscodeContainerType_ADTS); break; case AudioFormat.MP3: encoder = MediaFoundationEncoder.CreateMP3Encoder(_capture.WaveFormat, wsStream, 320000); break; } _capture.DataAvailable += (sender, e) => { encoder?.Write(e.Data, e.Offset, e.ByteCount); }; }
/// <summary> /// Write the content of the specified <see cref="IWriteable"/> to a <see cref="string"/>. /// </summary> /// <param name='writeable'> /// The <see cref="IWriteable"/> that contains the data and knows how to encode it. /// </param> public static string Write(this IWriteable writeable) { using (StringWriter sw = new StringWriter()) { writeable.Write(sw); return(sw.GetStringBuilder().ToString()); } }
public void WriteTo(IWriteable s) { // build track data first var trackData = ByteBuffer.Empty(); var current = FirstEvent; int count = 0; while (current != null) { current.WriteTo(trackData); current = current.NextEvent; count++; } // magic number "MTrk" (0x4D54726B) var b = new byte[] { 0x4D, 0x54, 0x72, 0x6B }; s.Write(b, 0, b.Length); // size as integer var data = trackData.ToArray(); var l = data.Length; b = new[] { (byte)((l >> 24) & 0xFF), (byte)((l >> 16) & 0xFF), (byte)((l >> 8) & 0xFF), (byte)((l >> 0) & 0xFF) }; s.Write(b, 0, b.Length); s.Write(data, 0, data.Length); }
private void StartCapture() { if (SelectedDevice == null) { return; } if (CaptureMode == "Capture") { _soundIn = new WasapiCapture(); } _soundIn.Device = SelectedDevice; _soundIn.Initialize(); var soundInSource = new SoundInSource(_soundIn); var singleBlockNotificationStream = new SingleBlockNotificationStream(soundInSource.ToSampleSource()); _finalSource = singleBlockNotificationStream.ToWaveSource(); _writer = new WaveWriter("tmp.wav", _finalSource.WaveFormat); byte[] buffer = new byte[_finalSource.WaveFormat.BytesPerSecond / 2]; soundInSource.DataAvailable += (s, e) => { int read; while ((read = _finalSource.Read(buffer, 0, buffer.Length)) > 0) { _writer.Write(buffer, 0, read); } }; //singleBlockNotificationStream.SingleBlockRead += SingleBlockNotificationStreamOnSingleBlockRead; // visualization _soundIn.Start(); }
/// <summary> /// Create a new file based on the given filename and start recording to it. /// Filename must include its full path. /// </summary> /// <param name="fileName">The name of a file to be created. Include its full path</param> /// <param name="codec">The codec to record in</param> /// <param name="bitRate">The bitrate of the file</param> /// <param name="channels">The channels to record</param> public void StartCapture(string fileName, AvailableCodecs codec, int bitRate, Channels channels) { if (!ReadyToRecord()) { throw new NullReferenceException("There is no SoundInSource configured for the recorder."); } fileName = $"{fileName}.{codec.ToString().ToLower()}"; WaveFormat waveSource; switch (channels) { case Channels.Mono: waveSource = _soundInSource.ToMono().WaveFormat; break; case Channels.Stereo: waveSource = _soundInSource.ToStereo().WaveFormat; break; default: throw new ArgumentException("The selected channel option could not be found."); } switch (codec) { case AvailableCodecs.MP3: _writer = MediaFoundationEncoder.CreateMP3Encoder(waveSource, fileName, bitRate); break; case AvailableCodecs.AAC: _writer = MediaFoundationEncoder.CreateAACEncoder(waveSource, fileName, bitRate); break; case AvailableCodecs.WMA: _writer = MediaFoundationEncoder.CreateWMAEncoder(waveSource, fileName, bitRate); break; case AvailableCodecs.WAV: _writer = new WaveWriter(fileName, waveSource); break; default: throw new ArgumentException("The specified codec was not found."); } byte[] buffer = new byte[waveSource.BytesPerSecond]; _soundInSource.DataAvailable += (s, e) => { int read = _waveStream.Read(buffer, 0, buffer.Length); _writer.Write(buffer, 0, read); }; // Start recording _soundInSource.SoundIn.Start(); _state = RecordingState.Recording; }
public Spectrograph() { InitializeComponent(); _soundIn = new WasapiLoopbackCapture(); _soundIn.Initialize(); var soundInSource = new SoundInSource(_soundIn); var singleBlockNotificationStream = new SingleBlockNotificationStream(soundInSource); _source = singleBlockNotificationStream.ToWaveSource(); if (!Directory.Exists(_loopbackDir)) { Directory.CreateDirectory(_loopbackDir); } _writer = new WaveWriter(_loopbackDir + "/loopback.wav", _source.WaveFormat); byte[] buffer = new byte[_source.WaveFormat.BytesPerSecond / 2]; soundInSource.DataAvailable += (s, e) => { int read; while ((read = _source.Read(buffer, 0, buffer.Length)) > 0) { _writer.Write(buffer, 0, read); } }; _lineSpectrumProvider = new BasicSpectrumProvider(_source.WaveFormat.Channels, _source.WaveFormat.SampleRate, fftSize); _spectrogramProvider = new BasicSpectrumProvider(_source.WaveFormat.Channels, _source.WaveFormat.SampleRate, fftSize); singleBlockNotificationStream.SingleBlockRead += SingleBlockNotificationStream_SingleBlockRead; _soundIn.Start(); _lineSpectrum = new LineSpectrum(fftSize) { SpectrumProvider = _lineSpectrumProvider, UseAverage = true, BarCount = 22, BarSpacing = 1, IsXLogScale = true, ScalingStrategy = ScalingStrategy.Sqrt }; _oscilloscope = new Oscilloscope(); _spectrogram = new Spectrogram(fftSize) { SpectrumProvider = _spectrogramProvider, UseAverage = true, BarCount = (int)fftSize, BarSpacing = 0, IsXLogScale = true, ScalingStrategy = ScalingStrategy.Sqrt }; _keyboardVisualizer = new KeyboardVisualizer(); UpdateTimer.Start(); }
/// <summary> /// Export a LibLSD type as it was originally. /// </summary> /// <param name="original">The LibLSD type (MOM, TIX, TOD, etc).</param> /// <param name="filePath">The path to write the file to.</param> public void ExportOriginal(IWriteable original, string filePath) { Logger.Log()(LogLevel.INFO, $"Exporting original to: {filePath}"); using (BinaryWriter bw = new BinaryWriter(File.Open(filePath, FileMode.Create))) { original.Write(bw); } }
/// <summary> /// Export a LibLSD type as it was originally. /// </summary> /// <param name="original">The LibLSD type (MOM, TIX, TOD, etc).</param> /// <param name="filePath">The path to write the file to.</param> public void ExportOriginal(IWriteable original, string filePath) { Log.Information($"Exporting original to: {filePath}"); using (BinaryWriter bw = new BinaryWriter(File.Open(filePath, FileMode.Create))) { original.Write(bw); } }
public override void WriteTo(IWriteable s) { s.WriteByte(0xFF); s.WriteByte((byte)MetaStatus); var l = Data.Length; MidiFile.WriteVariableInt(s, l); s.Write(Data, 0, Data.Length); }
/// <summary> /// Stop the recording and reset the recorder for a new recording. /// </summary> public void StopCapture() { if (_soundInSource?.SoundIn != null) { _soundInSource.SoundIn.Stop(); // Clean up the file writer ((IDisposable)_writer)?.Dispose(); _writer = null; _state = RecordingState.Stopped; } }
/// <summary> /// Writes the midi file as binary into the given stream. /// </summary> /// <returns>The stream to write to.</returns> public void WriteTo(IWriteable s) { // magic number "MThd" (0x4D546864) var b = new byte[] { 0x4D, 0x54, 0x68, 0x64 }; s.Write(b, 0, b.Length); // Header Length 6 (0x00000006) b = new byte[] { 0x00, 0x00, 0x00, 0x06 }; s.Write(b, 0, b.Length); // format b = new byte[] { 0x00, 0x00 }; s.Write(b, 0, b.Length); // number of tracks short v = 1; b = new[] { (byte)((v >> 8) & 0xFF), (byte)(v & 0xFF) }; s.Write(b, 0, b.Length); v = MidiUtils.QuarterTime; b = new[] { (byte)((v >> 8) & 0xFF), (byte)(v & 0xFF) }; s.Write(b, 0, b.Length); // build track data first var trackData = ByteBuffer.Empty(); var previousTick = 0; foreach (var midiEvent in Events) { var delta = midiEvent.Tick - previousTick; WriteVariableInt(trackData, delta); midiEvent.WriteTo(trackData); previousTick = midiEvent.Tick; } // end of track // magic number "MTrk" (0x4D54726B) b = new byte[] { 0x4D, 0x54, 0x72, 0x6B }; s.Write(b, 0, b.Length); // size as integer var data = trackData.ToArray(); var l = data.Length; b = new[] { (byte)((l >> 24) & 0xFF), (byte)((l >> 16) & 0xFF), (byte)((l >> 8) & 0xFF), (byte)((l >> 0) & 0xFF) }; s.Write(b, 0, b.Length); s.Write(data, 0, data.Length); }
public override void WriteTo(IWriteable s) { s.WriteByte(0xFF); s.WriteByte((byte)MetaStatus); MidiFile.WriteVariableInt(s, 3); var b = new[] { (byte)((Value >> 16) & 0xFF), (byte)((Value >> 8) & 0xFF), (byte)((Value >> 0) & 0xFF) }; s.Write(b, 0, b.Length); }
public override void WriteTo(IWriteable s) { s.WriteByte(0xF0); var l = Data.Length + 2; s.WriteByte((byte)ManufacturerId); var b = new[] { (byte)((l >> 24) & 0xFF), (byte)((l >> 16) & 0xFF), (byte)((l >> 8) & 0xFF), (byte)(l & 0xFF) }; s.Write(b, 0, b.Length); s.WriteByte(0xF7); }
public static string WriteString(this IWriteable writeable) { string result; using (MemoryStream ms = new MemoryStream()) { writeable.Write(ms); using (MemoryStream ms2 = new MemoryStream(ms.ToArray())) { using (StreamReader tr = new StreamReader(ms2)) { result = tr.ReadToEnd(); } } } return(result); }
public Visualizer() { InitializeComponent(); _graphics = DrawPanel.CreateGraphics(); _graphics.SmoothingMode = SmoothingMode.AntiAlias; _graphics.CompositingQuality = CompositingQuality.AssumeLinear; _graphics.PixelOffsetMode = PixelOffsetMode.Default; _graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; _graphics.Clear(Color.Black); _oscilloscope = new Oscilloscope(); for (int i = 0; i < _pens.Length; i++) { _pens[i] = new Pen(Color.FromArgb(i, i, i)); } _fftProvider = new FftProvider(1, FftSize.Fft4096); _soundIn = new WasapiLoopbackCapture(); _soundIn.Initialize(); var soundInSource = new SoundInSource(_soundIn); var singleBlockNotificationStream = new SingleBlockNotificationStream(soundInSource); _source = singleBlockNotificationStream.ToWaveSource(); if (!Directory.Exists("%AppData%/Spectrograph")) { Directory.CreateDirectory("%AppData%/Spectrograph"); } _writer = new WaveWriter("%AppData%/Spectrograph/loopback.wav", _source.WaveFormat); byte[] buffer = new byte[_source.WaveFormat.BytesPerSecond / 2]; soundInSource.DataAvailable += (s, e) => { int read; while ((read = _source.Read(buffer, 0, buffer.Length)) > 0) { _writer.Write(buffer, 0, read); } }; singleBlockNotificationStream.SingleBlockRead += SingleBlockNotificationStreamOnSingleBlockRead; _soundIn.Start(); }
public static bool InputField <T>(CompositeDisposable cd, IEngine engine, InputField src, IWriteable <T> dst, Func <string, T> converter) { if (!src) { return(NotBinded()); } UnityAction <string> action = text => dst.Write(converter(text)); src.onValueChanged.AddListener(action); cd.Add(new DisposableAction(() => src.onValueChanged.RemoveListener(action))); return(true); }
private void InternalWriteTable <T>(IWriteable writer, IEnumerable <T> table, params Expression <Func <T, object> >[] selectors) where T : class { IntLine(); var datas = new List <Tabulate <T> >(); foreach (var selector in selectors) { datas.Add(new Tabulate <T>(GetPropertyName(selector), selector.Compile())); } foreach (var item in table) { foreach (var data in datas) { data.PushData(item); } } lock (_verou) { if (datas.Any(p => p.Hasdata)) { var hasdata = datas.Where(p => p.Hasdata).ToList(); if (true) //header option { var line = "|"; writer.Write("|"); foreach (var data in hasdata) { writer.Write(data.Name.PadLeft(data.MaxValue)); line = line + new string('-', data.MaxValue) + "|"; writer.Write("|"); } writer.WriteLine(); writer.WriteLine(line); } for (int i = 0; i < hasdata.Max(p => p.Values.Count); i++) { writer.Write("|"); foreach (var data in hasdata) { writer.Write(data.Values[i]?.PadLeft(data.MaxValue)); writer.Write("|"); } writer.WriteLine(); } } } }
public GenieNanoCamera( ILogger <GenieNanoCamera> logger, IWriteable <GenieNanoSettings> options) : base(logger) { _frameArrived = FrameArrived; _cameraConnected = CameraConnected; _cameraDisconnected = CameraDisconnected; _logger = logger; _options = options; _name = options?.Value.CameraName; CreateCamera(); _options?.RegisterChangeListener(ApplyOptions); }
public IReadable <Reactor.Buffer> Pipe(IWriteable <Reactor.Buffer> writeable) { this.OnData += data => { this.Pause(); writeable.Write(data, (exception0) => { if (exception0 != null) { if (this.OnError != null) { this.OnError(exception0); } return; } writeable.Flush((exception1) => { if (exception1 != null) { if (this.OnError != null) { this.OnError(exception1); } return; } this.Resume(); }); }); }; this.OnEnd += () => { writeable.End(); }; if (writeable is IReadable <Reactor.Buffer> ) { return(writeable as IReadable <Reactor.Buffer>); } return(null); }
private void WriteVariableInt(IWriteable s, int value) { var array = new byte[4]; var n = 0; do { array[n++] = (byte)((value & 0x7F) & 0xFF); value >>= 7; } while (value > 0); while (n > 0) { n--; if (n > 0) s.WriteByte((byte) (array[n] | 0x80)); else s.WriteByte(array[n]); } }
private void StartCapture(string fileName) { if (settingsForm.SelectedDevice == null) { return; } _soundIn = new WasapiLoopbackCapture(); _soundIn.Device = settingsForm.SelectedDevice; _soundIn.Initialize(); // Check file name availability, if not available add "_" while the name exists string finalName = Path.ChangeExtension(fileName, null); while (File.Exists(finalName + ".wav")) { finalName += "_"; } finalName += ".wav"; var soundInSource = new SoundInSource(_soundIn); var singleBlockNotificationStream = new SingleBlockNotificationStream(soundInSource.ToSampleSource()); _finalSource = singleBlockNotificationStream.ToWaveSource(); _writer = new WaveWriter(finalName, _finalSource.WaveFormat); byte[] buffer = new byte[_finalSource.WaveFormat.BytesPerSecond]; soundInSource.DataAvailable += (s, e) => { int read = _finalSource.Read(buffer, 0, buffer.Length); //while ((read = _finalSource.Read(buffer, 0, buffer.Length)) > 0) Causes stops in the music recording (very bad idea) _writer.Write(buffer, 0, read); }; singleBlockNotificationStream.SingleBlockRead += SingleBlockNotificationStreamOnSingleBlockRead; _soundIn.Start(); }
void StartRecordByCSCore() { GetFilePath(); _soundIn = new WasapiCapture(); _soundIn.Device = (MMDevice)listView1.SelectedItems[0].Tag; _soundIn.Initialize(); var soundInSource = new SoundInSource(_soundIn); var singleBlockNotificationStream = new SingleBlockNotificationStream(soundInSource.ToSampleSource()); _finalSource = singleBlockNotificationStream.ToWaveSource(); _writer = new WaveWriter(sDestinationFile, _finalSource.WaveFormat); byte[] buffer = new byte[_finalSource.WaveFormat.BytesPerSecond / 2]; soundInSource.DataAvailable += (s, e) => { int read; while ((read = _finalSource.Read(buffer, 0, buffer.Length)) > 0) { _writer.Write(buffer, 0, read); } }; _soundIn.Start(); }
/// <summary> /// Write an item. /// </summary> ///<param name="w">Item to write.</param> public void Write(IWriteable w) { //Write. w.Write(this); }
public static void Run(IReadable input, IWriteable output) { output.WriteOutput(Convert.ToBase64String(Encoding.ASCII.GetBytes(input.ReadInput()))); }
public void WriteTo(IWriteable s) { // build track data first var trackData = ByteBuffer.Empty(); var current = FirstEvent; int count = 0; while (current != null) { current.WriteTo(trackData); current = current.NextEvent; count++; } // magic number "MTrk" (0x4D54726B) var b = new byte[] { 0x4D, 0x54, 0x72, 0x6B }; s.Write(b, 0, b.Length); // size as integer var data = trackData.ToArray(); var l = data.Length; b = new[]{ (byte)((l >> 24) & 0xFF), (byte)((l >> 16) & 0xFF), (byte)((l >> 8) & 0xFF), (byte)((l >> 0) & 0xFF) }; s.Write(b, 0, b.Length); s.Write(data, 0, data.Length); }
public void WriteTo(IWriteable s) { s.Write(Data, 0, Data.Length); }
/// <summary> /// Stop recording of the Mic started by CaptureMicToWave /// </summary> public void UnCaptureMicToWave() { _waveIn.Stop(); _source.Dispose(); _waveIn.Dispose(); if (_writer is IDisposable) ((IDisposable)_writer).Dispose(); _waveIn = null; _source = null; _writer = null; }
public void WriteTo(IWriteable s) { WriteVariableInt(s, DeltaTicks); Message.WriteTo(s); }
private void StartCapture(string fileName) { if (SelectedDevice == null) return; if(CaptureMode == CaptureMode.Capture) _soundIn = new WasapiCapture(); else _soundIn = new WasapiLoopbackCapture(); _soundIn.Device = SelectedDevice; _soundIn.Initialize(); var soundInSource = new SoundInSource(_soundIn); var singleBlockNotificationStream = new SingleBlockNotificationStream(soundInSource.ToSampleSource()); _finalSource = singleBlockNotificationStream.ToWaveSource(); _writer = new WaveWriter(fileName, _finalSource.WaveFormat); byte[] buffer = new byte[_finalSource.WaveFormat.BytesPerSecond / 2]; soundInSource.DataAvailable += (s, e) => { int read; while((read = _finalSource.Read(buffer, 0, buffer.Length)) > 0) _writer.Write(buffer, 0, read); }; singleBlockNotificationStream.SingleBlockRead += SingleBlockNotificationStreamOnSingleBlockRead; _soundIn.Start(); }