using System.IO;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using NAudio.CoreAudioApi;
using NAudio.Wave;
using WebSocketSharp;
namespace GameStream.Client;
///
/// Interaction logic for MainWindow.xaml
///
public partial class MainWindow : Window
{
private WebSocket? _wsStream;
private WebSocket? _wsSettings;
private WebSocket? _wsInput;
private WebSocket? _wsAudio;
code
Assistant
User
а в чем проблема то может быть??
Assistant
private BufferedWaveProvider? _bufferedWaveProvider;
private WaveOut _waveOut;
private VolumeSampleProvider _volumeProvider;
public MainWindow()
{
InitializeComponent();
ConnectToServer();
MouseMove += MainWindow_MouseMove;
MouseDown += MainWindow_MouseDown;
MouseUp += MainWindow_MouseUp;
KeyDown += MainWindow_KeyDown;
KeyUp += MainWindow_KeyUp;
Closed += OnClosed;
RenderCursorCheckBox.Checked += (s, e) => UpdateStreamSettings(true);
RenderCursorCheckBox.Unchecked += (s, e) => UpdateStreamSettings(false);
DebugPanelCheckBox.Checked += (s, e) => ToggleDebugPanel(true);
DebugPanelCheckBox.Unchecked += (s, e) => ToggleDebugPanel(false);
BlockInputCheckBox.Checked += (s, e) => ToggleBlockInput(true);
BlockInputCheckBox.Unchecked += (s, e) => ToggleBlockInput(false);
}
private void ToggleDebugPanel(bool b)
{
DebugTextBlock.Visibility = b ? Visibility.Visible : Visibility.Collapsed;
}
private void UpdateStreamSettings(bool b)
{
Send("RENDER_WITH_CURSOR", RenderCursorCheckBox.IsChecked);
}
private void ToggleBlockInput(bool b)
{
Send("BLOCK_INPUT", BlockInputCheckBox.IsChecked);
}
private void MainWindow_MouseMove(object sender, MouseEventArgs e)
{
if (_wsInput == null || !_wsInput.IsAlive) return;
var position = e.GetPosition(this);
var message = $"MOUSE_MOVE:{position.X}:{position.Y}";
_wsInput.Send(message);
}
private void MainWindow_MouseDown(object sender, MouseButtonEventArgs e)
{
if (_wsInput == null || !_wsInput.IsAlive) return;
var button = e.ChangedButton.ToString();
var message = $"MOUSE_DOWN:{button}";
_wsInput.Send(message);
}
private void MainWindow_MouseUp(object sender, MouseButtonEventArgs e)
{
if (_wsInput == null || !_wsInput.IsAlive) return;
var button = e.ChangedButton.ToString();
var message = $"MOUSE_UP:{button}";
_wsInput.Send(message);
}
private void MainWindow_KeyDown(object sender, KeyEventArgs e)
{
if (_wsInput == null || !_wsInput.IsAlive) return;
var message = $"KEY_DOWN:{e.Key}";
_wsInput.Send(message);
}
private void MainWindow_KeyUp(object sender, KeyEventArgs e)
{
if (_wsInput == null || !_wsInput.IsAlive) return;
var message = $"KEY_UP:{e.Key}";
_wsInput.Send(message);
}
private void ConnectToServer()
{
_wsStream = new WebSocket("ws://127.0.0.1:8080/stream");
_wsStream.OnMessage += (sender, e) => { Application.Current.Dispatcher.Invoke(() => UpdateImage(e.RawData)); };
_wsStream.Connect();
_wsInput = new WebSocket("ws://127.0.0.1:8080/input");
_wsInput.Connect();
_wsSettings = new WebSocket("ws://127.0.0.1:8080/settings");
_wsSettings.Connect();
_wsAudio = new WebSocket("ws://127.0.0.1:8080/audio");
_wsAudio.OnMessage += (sender, e) => ReceiveAudioStream(e.RawData);
_wsAudio.Connect();
SetupAudioPlayback();
UpdateDebugMessage($"1: {RenderCursorCheckBox.IsChecked}, 2: {BlockInputCheckBox.IsChecked}");
Send("RENDER_WITH_CURSOR", RenderCursorCheckBox.IsChecked);
Send("BLOCK_INPUT", BlockInputCheckBox.IsChecked);
}
private void SetupAudioPlayback()
{
var enumerator = new MMDeviceEnumerator();
var defaultDevice = enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
var mixFormat = defaultDevice.AudioClient.MixFormat;
_bufferedWaveProvider = new BufferedWaveProvider(new WaveFormat(mixFormat.SampleRate, 16, mixFormat.Channels));
var sampleProvider = _bufferedWaveProvider.ToSampleProvider();
_volumeProvider = new VolumeSampleProvider(sampleProvider);
_volumeProvider.Volume = 0.1f;
_waveOut = new WaveOut();
_waveOut.Init(_volumeProvider);
_waveOut.Play();
}
private void ReceiveAudioStream(byte[] audioData)
{
_bufferedWaveProvider?.AddSamples(audioData, 0, audioData.Length);
}
private void Send<T>(string id, T value)
{
_wsSettings?.Send($"{id}:{value}");
}
private void UpdateStatusMessage(string message)
{
StatusMessage.Text = message;
}
private void UpdateDebugMessage(string message)
{
DebugTextBlock.Text = message;
}
private void UpdateImage(byte[] data)
{
using var ms = new MemoryStream(data);
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = ms;
bitmap.EndInit();
StreamImage.Source = bitmap;
}
private void OnClosed(object? sender, EventArgs e)
{
_wsStream?.Close();
_wsInput?.Close();
_wsSettings?.Close();
_wsAudio?.Close();
_waveOut?.Dispose();
}
}
почему звуК дико фонит?
using NAudio.Wave;
using WebSocketSharp;
using WebSocketSharp.Server;
namespace GameStream.Server;
public class AudioStreamer : WebSocketBehavior
{
private WasapiLoopbackCapture? _waveIn;
private BufferedWaveProvider? _waveProvider;
private MemoryStream? _audioStream;
If you're experiencing distorted or noisy audio (indicated as "фонит" in your query) in a project using NAudio for playback and WebSocket for streaming, the issue could arise from multiple sources. Here are some steps you can take to address and potentially fix the problem:
Potential Causes and Solutions
Bitrate or Sample Rate Mismatch:
Verify that the sample rate and format of the audio being captured and played back are consistent. Mismatches can cause audio distortion.
Check the WasapiLoopbackCapture settings to ensure they match your playback settings.
Buffer Size and Latency:
Adjust the buffer size in BufferedWaveProvider. If the buffer is too small, it may underrun, causing distortion. Conversely, if it's too large, it can introduce latency.
Ensure your playback buffer size in WaveOut matches the BufferedWaveProvider if required.
Network Latency or Packet Loss:
Audio distortion can occur due to packet loss or high latency over WebSockets. This is more a streaming issue rather than an audio processing one.
Ensure the network connection is stable. You might consider implementing error correction or packet retransmission to handle packet loss gracefully.
Volume and Clipping:
You are using a VolumeSampleProvider to manage audio volume. Check that the volume settings are not causing clipping (values greater than 1.0).
You have set Volume = 0.1f, which is low, so this might not be the issue, but you can experiment with it.
Audio Data Handling:
Ensure that the entire audio byte array is properly captured and sent over WebSocket without clipping the data.
Validate that data is sent and received in the correct sequence without loss or corruption.
Concurrency Issues:
Concurrent access to shared resources, like buffers or memory streams, can lead to unexpected behavior. Ensure thread safety where necessary.
Audio Format Mismatch:
Double-check that WaveFormat used in transmission matches the buffer and output format exactly. Any deviation here can introduce noise.
Debugging Steps
Log and Test Formats: Add logging to determine the exact formats being used for both capture and playback.
Check Audio Encodings: Confirm that you are not inadvertently changing or encoding/decoding audio incorrectly.
Minimal Example: Try isolating the problem by writing a minimal example that just captures and plays back audio without streaming to see where the issue might lie.
Testing with Local Playback: Test the captured audio by writing it to a file or playing back locally, bypassing WebSockets, to ensure the capture side setup is correct.
With these steps, adjust settings, and test systematically to identify what might be causing the audio issues in your application.
Исходя из вашего кода, проблема искажения (или "фона") звука может быть вызвана несколькими возможными причинами. Давайте разберемся, где может возникнуть ошибка и как ее можно исправить:
Несоответствие частоты дискретизации или формата:
Важно убедиться, что частота дискретизации и формат аудиоданных, полученных с помощью WasapiLoopbackCapture, совпадают с теми, которые вы используете для воспроизведения на клиентской стороне. Любое несоответствие может привести к искажениям звука.
Размер буфера и задержка:
При использовании BufferedWaveProvider важно правильно настроить размер буфера. Если он слишком мал, это может вызвать разрывы и искажения звука, а если слишком велик — увеличить задержку.
Проверьте, соответствует ли размер буфера на WaveOut размеру в BufferedWaveProvider.
Потери данных при передаче:
Особенно важно в случае использования WebSocket, чтобы данные не терялись или искажались при передаче. Высокая задержка или потеря пакетов может привести к искаженному звуку.
Убедитесь, что ваше подключение к сети стабильное, и рассмотрите возможность добавления механизмов коррекции ошибок или повтора пакетов.
Проблемы с уровнем громкости и клиппингом:
Вы устанавливаете низкий уровень громкости Volume = 0.1f. Убедитесь, что уменьшение громкости не приводит к изменению динамических свойств сигнала, но это вряд ли причина искажений. Однако высокий уровень громкости может вызвать клиппинг.
Неправильная обработка аудиоданных:
Проверьте, что весь массив аудиобайтов правильно захватывается и передается через WebSocket. Обрыв данных может привести к искажениям.
Убедитесь, что данные отправляются и принимаются в правильной последовательности без потерь или искажений.
Проблемы с многопоточностью:
Если общие ресурсы, такие как буферы или потоки памяти, используются одновременно из нескольких потоков, это может привести к некорректной работе. Убедитесь в потокобезопасности вашего кода там, где это необходимо.
Чтобы диагностировать и исправить проблему:
Журналы и тестирование форматов: Добавьте логирование, чтобы определить точные форматы захвата и воспроизведения.
Локальная проверка: Воспроизводите захваченное аудио локально (без передачи через сеть) для проверки корретности захвата.
Изолированное тестирование: Создайте минимальный пример, который только захватывает и воспроизводит аудио, чтобы проверить базовые настройки, минуя этап передачи.
Осмотрев эти аспекты и внесенные изменения, возможно, удастся определить и устранить причину искажения звука в вашем приложении.