I have search all over SO and on google.
Im trying to find a example of how I can stream internet radio (mp3) from a Windows Store App.
All the examples I found are small pieces of code that doesn't work.
Can someone explain or show code on how exactly I should do.
I have been trying mediaelement and some others.
I tried this
public async void Play()
{
Uri bla = new Uri(string.Format("http://live-icy.gss.dr.dk/A/A04H.mp3.m3u"), UriKind.Absolute);
var uriStreamReference = RandomAccessStreamReference.CreateFromUri(bla);
var uriStream = await uriStreamReference.OpenReadAsync();
nm.SetSource(uriStream, "audio/mp4");
}
Hope someone can help
I know this is old, however I have a working example.
InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
Uri uri = new Uri("http://live-icy.gss.dr.dk/A/A04H.mp3.m3u");
HttpClient hc = new HttpClient();
HttpResponseMessage msg = await hc.GetAsync(uri);
await RandomAccessStream.CopyAsync(await msg.Content.ReadAsInputStreamAsync(), stream);
stream.Seek(0);
myMediaElement.SetSource(stream, msg.Content.Headers.ContentType.ToString());
You must remember to call Dispose() on your InMemoryRandomAccessStream and HttpClient when you are sure you have finished with them. Otherwise you will most likely end up with a memory leak.
Related
I have tried to create a simple console application.
We have a call system from 8x8 that provide a web streaming API but their documentation is very limited and nothing in C#.
The api service streams call statuses in near real time and I would like to get that 'stream' and be able to read and process it in realtime if possible. The response or Content Type is 'text/html'. But the actual body of the response can be declared as json - sample below:
{"Interaction":{"attachedData":{"attachedDatum":[{"attachedDataKey":"#pri","attachedDataValue":100},{"attachedDataKey":"callingName","attachedDataValue":999999999999},{"attachedDataKey":"cha","attachedDataValue":99999999999},{"attachedDataKey":"cnt","attachedDataValue":0},{"attachedDataKey":"con","attachedDataValue":0},{"attachedDataKey":"med","attachedDataValue":"T"},{"attachedDataKey":"pho","attachedDataValue":9999999999},{"attachedDataKey":"phoneNum","attachedDataValue":9999999999},{"attachedDataKey":"tok","attachedDataValue":999999999}]},"event":"InteractionCreated","inboundChannelid":9999999999,"interactionEventTS":9999999,"interactionGUID":"int-15b875d0da2-DJOJkDhDsrh3AIaFP8VkICv9t-phone-01-testist","resourceType":0}}
I have seen several posts concerning httpClient and the GetAsync methods but none of these appear to work as they appear to be for calls when a response is made, not something that constantly has a response.
Using fiddler for the call it does not appear to close so the stream is constantly running, so fiddler does not display any data until a separate user or instance connects.
When I use a browser the content is 'streamed' to the page and updates automatically and shows all the content (as above).
The api contains authentication so when another client connects and retrieves data the connected client closes and finally I am able to see the data that was gathering.
This is the code so and does return the big stream when another client connects but ideally I want a real time response and appears to just get stuck in the GETASYNC method:
var response = await client.GetAsync(address, HttpCompletionOption.ResponseHeadersRead);
if (response.IsSuccessStatusCode)
{
var responseContent = response.Content;
string responseString = await responseContent.ReadAsStringAsync();
Console.WriteLine(responseString);
}
Hopefully that's enough information for one of you clever people to help me in my predicament.
I was also having an issue consuming their streaming API and the examples I found that worked with the Twitter and CouchBase streaming API's did not work with 8x8. Both Twitter and CouchBase send line terminators in their pushes so the solution relied on ReadLine to pull in the feed. Since 8x8 does not send terminators you'll need to use ReadBlock or better ReadBlockAsync.
The following code shows how to connect using credentials and consume their feed:
private static async Task StreamAsync(string url, string username, string password)
{
var handler = new HttpClientHandler()
{
Credentials = new NetworkCredential {UserName = username, Password = password},
PreAuthenticate = true
};
// Client can also be singleton
using (var client = new HttpClient(handler))
{
client.Timeout = TimeSpan.FromMilliseconds(Timeout.Infinite);
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Connection.Add("keep-alive");
using (var response = await client.SendAsync(
request,
HttpCompletionOption.ResponseHeadersRead))
{
using (var body = await response.Content.ReadAsStreamAsync())
{
using (var reader = new StreamReader(body))
{
while (!reader.EndOfStream)
{
var buffer = new char[1024];
await reader.ReadBlockAsync(buffer, 0, buffer.Length);
Console.WriteLine(new string(buffer));
}
}
}
}
}
}
So currently I get a list of images with ID's. When the user then clicks on it, it downloads and displays the image. Everything works, I just need a progress bar to show where it is currently at.
Current code:
var values = new Dictionary<string, string>
{
{ "myPost", "Data" },
};
var client = new System.Net.Http.HttpClient();
var content = new FormUrlEncodedContent(values);
client.DefaultRequestHeaders.Add("test", "header");
var response = await client.PostAsync("myScript.php", content);
var responseString = await response.Content.ReadAsStringAsync();
Since you are using UWP. I would suggest you use the HttpClient provided in Windows.Web.Http. This has post/put and get methods which also provides progress.
See HttpClient for more details specifically HttpProgress in HttpClient.
Hope this helps!
I have the following piece of code (WPF, Windows Phone 8.1):
HttpClient client = new HttpClient();
var httpResult = client.GetAsync(feed.Url, ct);
string feedData = await httpResult.Result.Content.ReadAsStringAsync();
var sf = new SyndicationFeed();
sf.Load(feedData);
I'm trying to debug this code. However, after the line:
string feedData = await httpResult.Result.Content.ReadAsStringAsync();
debugger seems to let application run on its own and never reaches the next line. Why is that? Am I doing something wrong?
Depending on if you are calling result or wait on the task somewhere upstream, this can result in a deadlock as noted in Stephen Cleary's blog post.
Mitigate this by awaiting the client.GetAsync() and use ConfigureAwait where possible to minimize chances of deadlocks:
HttpClient client = new HttpClient();
var httpResult = await client.GetAsync(feed.Url, ct).ConfigureAwait(false);
string feedData = await httpResult.Content.ReadAsStringAsync().ConfigureAwait(false);
var sf = new SyndicationFeed();
sf.Load(feedData)
I need to upload a File , process it and then download the processed file within the same POST request.
I didn't find a lot of documentation about Web API covering my requirement, so I've come up with a solution based on different post's found on the net.
My final solution looks like that:
public HttpResponseMessage PostFile(string fileName)
{
try
{
var task = Request.Content.ReadAsStreamAsync();
task.Wait();
var requestStream = task.Result;
var tempFile = System.Web.HttpContext.Current.Server.MapPath(string.Format("~/App_Data/{0}", fileName));
var steam = File.Create(tempFile);
requestStream.CopyTo(steam);
steam.Close();
requestStream.Close();
var modifiedStream = DoStuffToFile(tempFile);
var response = new HttpResponseMessage();
response.Content = new StreamContent(modifiedStream);
response.StatusCode = HttpStatusCode.Created;
return response;
}
catch
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
}
As I have no experience in Web API, I would like to know if this piece of code is ok,
or if I will run into problems?
Edit:
The code works as expected. I'm just not sure if it can cause any problems or side effects for exmaple because I forgot to do something that might be considered by the Web API. Or is it ok that I post a file and send another one back with the response?
Code is also simplified to keep it compact(no check for duplicate files, no cleanup of old files, etc)
I'm using the following code to download an image from a url
HttpClient client = new HttpClient();
var stream = await client.GetStreamAsync(new Uri("<your url>"));
var file = await KnownFolders.PictureLibrary.CreateFileAsync("myfile.png");
using (var targetStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
using (stream)
await stream.CopyToAsync(targetStream.AsStreamForWrite());
}
several users have reported that it doesn't always download the entire image. That they sometimes get partial images and the rest is just garbage.
Is there any reason for this?
Thanks!
I would suggest trying the WebClient class with the DownloadData or DownloadDataAsync method.
File.WriteAllBytes("myfile.png",
new WebClient().DownloadData("<your url>"));
edit If the stream is giving you trouble you could use the byte array response instead. Your "using" statement with async code inside may be causing it to dispose early, perhaps?
var httpClient = new HttpClient();
var data = await httpClient.GetByteArrayAsync(new Uri("<Your URI>"));
var file = await KnownFolders.PictureLibrary.CreateFileAsync("myfile.png");
var targetStream = await file.OpenAsync(FileAccessMode.ReadWrite)
await targetStream.AsStreamForWrite().WriteAsync(data, 0, data.Length);
targetStream.FlushAsync().Wait();
targetStream.Close();
BackgroundDownloader is the easiest way to download a file.
using Windows.Storage;
public async Task DownloadPhoto(Uri uri)
{
var folder = ApplicationData.Current.LocalFolder;
var photoFile = await folder.CreateFileAsync("photo.jpg", CreationCollisionOption.ReplaceExisting);
var downloader = new Windows.Networking.BackgroundTransfer.BackgroundDownloader();
var dl = downloader.CreateDownload(uri, photoFile);
await dl.StartAsync();
}
If your using HttpClient then if your image is larger than 64K it will error out. You will have to set the httpClient.MaxResponseContentBufferSize to something larger.
See the MSDN Quick Start where they set the max-buffer-size to 256K.
http://msdn.microsoft.com/en-us/library/windows/apps/xaml/JJ152726(v=win.10).aspx
Personally though, I use the BackgroundDownloader.