C# - Amazon Lex chatbot voice input [duplicate] - c#

I have the chatbot client running with text but would now like to change it to voice but I am unsure of how to get the stream from the mic for post. For recording audio I am using NAudio but when sending the memory stream I get an error stating
System.IO.IOException: Cannot close stream until all bytes are
written.
Here is my code:
private void recordAudio()
{
if (memoryStream == null)
memoryStream = new MemoryStream();
sourceStream = new NAudio.Wave.WaveIn();
sourceStream.WaveFormat = new NAudio.Wave.WaveFormat(16000, 1);
waveIn = new NAudio.Wave.WaveInProvider(sourceStream);
waveWriter = new WaveFileWriter(new IgnoreDisposeStream(memoryStream), waveIn.WaveFormat);
sourceStream.DataAvailable += new EventHandler<NAudio.Wave.WaveInEventArgs>(sourceStream_DataAvailable);
buff = new BufferedWaveProvider(waveIn.WaveFormat);
sourceStream.StartRecording();
mytimer.Enabled = true;
}
private void sourceStream_DataAvailable(object sender, NAudio.Wave.WaveInEventArgs e)
{
buff.AddSamples(e.Buffer, 0, e.BytesRecorded);
Console.WriteLine("test");
}
void mytimer_Tick(object sender, EventArgs e)
{
if (sourceStream != null)
{
sourceStream.StopRecording();
waveWriter.Flush();
var amazonLexClient = new AmazonLexClient(Amazon.RegionEndpoint.USEast1);
var amazonPostRequest = new Amazon.Lex.Model.PostContentRequest();
var amazonPostResponse = new Amazon.Lex.Model.PostContentResponse();
amazonPostRequest.BotAlias = "voiceBot";
amazonPostRequest.BotName = "voiceBot";
amazonPostRequest.ContentType = "audio/l16; rate=16000; channels=1";
amazonPostRequest.UserId = "user";
amazonPostRequest.InputStream = memoryStream;
amazonPostRequest.UserId = "test";
try
{
amazonPostResponse = amazonLexClient.PostContent(amazonPostRequest);
Console.WriteLine("Got a response");
}
catch (Exception w)
{
Console.WriteLine("{0} Exception caught.", e);
Console.WriteLine(w.Message);
}

You have to set the Position of your MemoryStream to 0 before you pass it to the post request.
memoryStream.Position = 0;

Related

How receive bitmap's continuously from android on C# Socket?

I'm working in a remote administration tool to my own use and the project is stopped because a error on receiver function on Server side that is this.:
Arithmetic operation resulted in an overflow. (Adding integers)
in this line:
var imageData = new byte[length];
void server_Received(Listener l, Info i, string received) {
string[] cmd = received.Split('|');
switch (cmd[1])
{
case "PRINT":
//MessageBox.Show("print");
Thread threadPrint;
threadPrint = new Thread(() =>
{
var lengthData = new byte[4];
var lengthBytesRead = 0;
while (lengthBytesRead < lengthData.Length)
{
var read = i.sock.Receive(lengthData, lengthBytesRead, lengthData.Length - lengthBytesRead, SocketFlags.None);
if (read == 0) return;
lengthBytesRead += read;
}
var length = BitConverter.ToInt32(lengthData, 0);
var imageData = new byte[length];
var imageBytesRead = 0;
while (imageBytesRead < imageData.Length)
{
var read = i.sock.Receive(imageData, imageBytesRead, imageData.Length - imageBytesRead, SocketFlags.None);
if (read == 0) return;
imageBytesRead += read;
}
using (var stream = new MemoryStream(imageData))
{
var bitmap = new Bitmap(stream);
Invoke(new ImageCompleteDelegate(ImageComplete), new object[] { bitmap });
}
});
threadPrint.Start();
break;
}
}
the code to receiver i taked from this reference (see Client code) and was adapted to my need like you can see above.
Here is how i'm sending the bitmap on android (Java):
try {
dos = new DataOutputStream(SocketBackgroundService.xclientSocket.getOutputStream());
PrintWriter out = new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(dos)
)
);
out.println("|PRINT|");
out.flush();
dos.writeInt(array.length);
dos.write(array, 0, array.length);
dos.flush();
} catch (IOException e) {
e.printStackTrace();
}
Then, i want know what can be done to solve this trouble?
Thanks in advance.
The solution was insert:
Array.Reverse(lengthData);
before of:
var length = BitConverter.ToInt32(lengthData, 0);

WP8 take picture with Nokia Imaging API (real time filter) and save to IsolatedStorage

I followed the examples here: http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj662940%28v=vs.105%29.aspx
I made the live preview and stuff work, but how can I take a picture? This is what i tried:
private PhotoCaptureDevice _photoCaptureDevice = null;
string strImageName = "IG_Temp";
private NokiaImagingSDKEffects _cameraEffect = null;
private MediaElement _mediaElement = null;
private CameraStreamSource _cameraStreamSource = null;
private Semaphore _cameraSemaphore = new Semaphore(1, 1);
MediaLibrary library = new MediaLibrary();
private async void ShutterButton_Click(object sender, RoutedEventArgs e)
{
if (_cameraSemaphore.WaitOne(100))
{
await _photoCaptureDevice.FocusAsync();
_cameraSemaphore.Release();
CameraCaptureSequence seq = _photoCaptureDevice.CreateCaptureSequence(1);
await seq.StartCaptureAsync();
MemoryStream captureStream1 = new MemoryStream();
// Assign the capture stream.
seq.Frames[0].CaptureStream = captureStream1.AsOutputStream();
try
{
// Set the position of the stream back to start
captureStream1.Seek(0, SeekOrigin.Begin);
// Save photo as JPEG to the local folder.
using (IsolatedStorageFile isStore = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream targetStream = isStore.OpenFile(strImageName, FileMode.Create, FileAccess.Write))
{
// Initialize the buffer for 4KB disk pages.
byte[] readBuffer = new byte[4096];
int bytesRead = -1;
// Copy the image to the local folder.
while ((bytesRead = captureStream1.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
targetStream.Write(readBuffer, 0, bytesRead);
}
}
}
}
finally
{
// Close image stream
captureStream1.Close();
}
// Navigate to the next page
Dispatcher.BeginInvoke(() =>
{
NavigationService.Navigate(new Uri("/Edit.xaml?name=" + strImageName, UriKind.Relative));
});
}
}
But I will get an error:
System.InvalidOperationException
in line: await seq.StartCaptureAsync();
What am I doing wrong?

Uploading an image to FTP server on windows phone

Please Help! I've tried everything, i dont know what else to do. I just want to upload an image that the user chooses from their library to my websever.
I already have a code that uses webclient to upload to a url.
private void OnChoosePicturel(object sender, RoutedEventArgs e)
{
PhotoChooserTask task = new PhotoChooserTask();
task.Completed += task_Completed;
task.Show();
}
private void task_Completed(object sender, PhotoResult e)
{
if (e.TaskResult != TaskResult.OK)
return;
const int BLOCK_SIZE = 4096;
Uri uri = new Uri("URL");
WebClient wc = new WebClient();
NetworkCredential g = new NetworkCredential();
g.UserName = "USERNAME";
g.Password = "PASSWORD";
wc.Credentials = g;
wc.AllowReadStreamBuffering = true;
wc.AllowWriteStreamBuffering = true;
try
{
// what to do when write stream is open
wc.OpenWriteCompleted += (s, args) =>
{
using (BinaryReader br = new BinaryReader(e.ChosenPhoto))
{
using (BinaryWriter bw = new BinaryWriter(args.Result))
{
long bCount = 0;
long fileSize = e.ChosenPhoto.Length;
byte[] bytes = new byte[BLOCK_SIZE];
do
{
bytes = br.ReadBytes(BLOCK_SIZE);
bCount += bytes.Length;
bw.Write(bytes);
} while (bCount < fileSize);
}
}
};
}
catch(Exception t)
{
}
// what to do when writing is complete
wc.WriteStreamClosed += (s, args) =>
{
MessageBox.Show("Send Complete");
};
// Write to the WebClient
wc.OpenWriteAsync(uri, "STOR");
}
The problem is , the webclient class only works for "http" urls, but i need to connect and upload the file to an "ftp" url. How do i do this? Ive tried EVERYTHING. Nothing works.

Web Service returned error : Not Found

The web service i am using returned web exception. Service is called from Silverlight application. Basically i am trying to convert eps file into png . On localhost everything is working well but when i deployed on web server i am getting this error.
Silverlight Code is --
private void btnUploadImage_Click(object sender, RoutedEventArgs e)
{
string fileextn = string.Empty;
OpenFileDialog openDialog = new OpenFileDialog();
if (openDialog.ShowDialog() == true)
{
try
{
string fileExtension = openDialog.File.Extension.ToString();
if (fileExtension.Contains("jpeg") || fileExtension.Contains("jpg") || fileExtension.Contains("png") || fileExtension.Contains("tif") || fileExtension.Contains("tiff") || fileExtension.Contains("bmp") || fileExtension.Contains("gif"))
{
using (Stream stream = openDialog.File.OpenRead())
{
HtmlPage.Window.Invoke("showProcessingAndBlockUI");
// Don't allow really big files (more than 2 MB).
if (stream.Length < 5 * 1024 * 1025)
{
MemoryStream tempStream = new MemoryStream();
byte[] data = new byte[stream.Length];
stream.Position = 0;
stream.Read(data, 0, (int)stream.Length);
tempStream.Write(data, 0, (int)stream.Length);
stream.Close();
ProductConfiguratorServiceClient pcs = new ProductConfiguratorServiceClient();
string virtualpath = HelperClass.GetVirtual();
pcs.Endpoint.Address = new System.ServiceModel.EndpointAddress(virtualpath + "/Services/ProductConfiguratorService.svc/basic");
pcs.GetFormattedImageCompleted += new EventHandler<GetFormattedImageCompletedEventArgs>(pcs_GetFormattedImageCompleted);
pcs.GetFormattedImageAsync(data);
pcs.CloseAsync();
tempStream.Close();
}
else
{
MessageBox.Show("Files must be less than 5 MB.");
}
}
}
else if (openDialog.File.Extension.Contains("eps"))
{
HtmlPage.Window.Invoke("showProcessingAndBlockUI");
using (Stream stream = openDialog.File.OpenRead())
{
if (stream.Length < 5 * 1024 * 1025)
{
MemoryStream tempStream = new MemoryStream();
byte[] data = new byte[stream.Length];
stream.Position = 0;
stream.Read(data, 0, (int)stream.Length);
tempStream.Write(data, 0, (int)stream.Length);
stream.Close();
ProductConfiguratorServiceClient pcs = new ProductConfiguratorServiceClient();
string virtualpath = HelperClass.GetVirtual();
pcs.Endpoint.Address = new System.ServiceModel.EndpointAddress(virtualpath + "/Services/ProductConfiguratorService.svc/basic");
pcs.GetEpsFileIntoPngCompleted += new EventHandler<GetEpsFileIntoPngCompletedEventArgs>(pcs_GetEpsFileIntoPngCompleted);
pcs.GetEpsFileIntoPngAsync(data);
tempStream.Close();
}
else
{
MessageBox.Show("Files must be less than 5 MB.");
}
}
}
else
{
MessageBox.Show("Please Check the Image Format.");
}
}
catch (Exception)
{
HtmlPage.Window.Invoke("hideBlockUI");
MessageBox.Show("Somr Error Occured, Please Try Again Later .");
}
}
}
void pcs_GetEpsFileIntoPngCompleted(object sender, GetEpsFileIntoPngCompletedEventArgs e)
{
busi.CurrentlySelectedOverlayImage.UploadedImageStream = e.Result;
busi.CurrentlySelectedOverlayImage.ImageFileType = "png";
RefreshStatus();
busi.CurrentlySelectedOverlayImageChanged = true;
HtmlPage.Window.Invoke("hideBlockUI");
}
void pcs_GetFormattedImageCompleted(object sender, GetFormattedImageCompletedEventArgs e)
{
try
{
if (e.Error != null)
{
MessageBox.Show(e.Error.ToString());
}
else
{
busi.CurrentlySelectedOverlayImage.UploadedImageStream = e.Result;
busi.CurrentlySelectedOverlayImage.ImageFileType = "jpeg";
RefreshStatus();
busi.CurrentlySelectedOverlayImageChanged = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
//throw new NotImplementedException();
}
Error is at System.Net.Browser.BrowserHttpWebRequest.
Please assist me whether what kind of problem is this?
It could have something to do with this line.
pcs.Endpoint.Address = new System.ServiceModel.EndpointAddress(virtualpath +
You are missing the rest of it.
Pretty sure this is a compile error though.
So either this error is getting eaten and the generic one is popping up or you have some other issue along with this.

Accessing the header in OpenReadCompleted Method on windows phone 8

I have an app that downloads an image to the phone and depending on the image category it will assign it to a news feed. I am using this function:
private static void DownloadImage(string furl, string ids)
{
// Connect Again to the API
WebClient client = new WebClient();
client.Headers["NewsID"] = ids;
string url = "www.xxx.com/image/xyz";
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(new Uri(url));
}
private static void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (e.Error == null && !e.Cancelled)
{
Stream reply = null;
StreamReader s = null;
// i am not able to read the sender who is a webclient to retrieve the information it is always skipping it
WebClient wcd = sender as WebClient;
reply = (Stream)e.Result;
s = new StreamReader(reply);
//Console.WriteLine(s.ReadToEnd());
s.Close();
reply.Close();
if (!myIsolatedStorage.DirectoryExists("ImageCache"))
{
myIsolatedStorage.CreateDirectory("ImageCache");
}
//try
//{//((MS.Internal.InternalMemoryStream)(e.Result)).FinalUri.Segments[2]
var graphImage = e.Result;
Random rand = new Random();
string fileName = string.Format("ImageCache/{0}.jpg", rand.Next());
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(fileName);
BitmapImage image = new BitmapImage();
image.SetSource(e.Result);
WriteableBitmap wb = new WriteableBitmap(image);
// Encode WriteableBitmap object to a JPEG stream.
Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
fileStream.Close();
//}
//catch (IsolatedStorageException ex)
//{
//IsolatedStorageException
//Exception handle appropriately for your app
//}
}
}
}
In the OpenReadComplete function which I'm using to download the image, I want to get the newsID from the header, and then assign it to the image before saving it into the database. I can't seem to access the header. Is this possible?
I think you can read it with sender.
WebClient c = (WebClient)sender;
string id = c.Headers["NewsID"];

Categories

Resources