Windows Phone: playing a recorded sound throws exception - windows-phone-8

I am using an AudioVideoCaptureDevice to record some sound from the microphone. I want to give the user feedback on what he recorded so I want to be able to play it.
When putting that sound into a Song and playing it via Microsoft.Xna.Framework.Media.MediaPlayer, I am getting an exception:
{System.InvalidOperationException: Song playback failed.
Please verify that the song is not DRM protected.
DRM protected songs are not supported for creator games.
---> System.InvalidOperationException: An unexpected error has occurred.
--- End of inner exception stack trace ---
at Microsoft.Xna.Framework.Media.MediaQueue.Play(Song song)}
Looking into the details of the song in the watch, the IsProtected() seems to cause issues. (If playback works, I get correctly that the song is not protected.) I am using AAC and ACM codecs, both give same results.
I can play the song after closing and opening the view again, but have not found any related initialization that would explain this.
I also tried copying the file, in case some process was still holding a lock on it, still, there is no improvement, same with isolated storage.
After not closing app but re-entering view the song plays without problems.
How can I directly play the recorded audio without any problems?

I used the AudioRecorder sample from http://independentinnovation.net/blogs/independentinnovation/archive/2012/12/11/Windows-Phone-8-Audio-Recording-using-Windows.Phone.Media.Capture.aspx .
(Note: right now this link is not working, domain expired.. anyway, I used someone else's code.)
It turns out, that in the Record() function, a stream is opened, that in the Stop() function is never properly flushed and disposed.
I don't understand how this could have caused the problem, since I did copy the resulting file, just to make sure that all handles are valid.
Still, old handling was definitely wrong and new handling is a lot cleaner, and, btw, works.
public async void StopRecording()
{
try
{
if (dev != null)
{
await dev.StopRecordingAsync();
dev = null;
// these 2 lines I had to add
await recordingStream.FlushAsync();
recordingStream.Dispose();
}
var length = new System.IO.FileInfo(fileName).Length;
System.Diagnostics.Debug.WriteLine("Recorded " + fileName + " with length " + length);
}
catch (System.Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}
edit: to give credits, I found the answer I used here http://www.postseek.com/meta/9fddd403d0cde523a542be42b7a4b057

Related

Reason for failure in MultipartObjectAssembler OCI object storage

I'm using MultipartObjectAssembler to upload data from a Database to OCI object storage.
Is there a way to know the reason for failure when using multipart upload?
When I try to commit assembler I'm getting IllegalStateException with the message "One or more parts were have not completed upload successfully".
I would like to know why any part got failed? I couldn't find a way to get this information from SDK.
try {
assembler.addPart(new ByteArrayInputStream(part, 0, length),
length,
null);
assembler.commit();
} catch (Exception e) {
assembler.abort();
throw new RuntimeException(e.getMessage());
}
Edit: I need to get an Exception thrown by a failed part and propagate the error message.
Is there a reason you are not using the UploadManager? It should do everything for you, including adding parts and committing. Here's an end-to-end example: https://github.com/oracle/oci-java-sdk/blob/master/bmc-examples/src/main/java/UploadObjectExample.java
If, for some reason, you cannot use UploadManager, please take a look at its source code nonetheless, since it demonstrates the intended usage of MultipartObjectAssembler: https://github.com/oracle/oci-java-sdk/blob/master/bmc-objectstorage/bmc-objectstorage-extensions/src/main/java/com/oracle/bmc/objectstorage/transfer/UploadManager.java#L175-L249
You create the MultipartObjectAssembler:
MultipartObjectAssembler assembler =
createAssembler(request, uploadRequest, executorServiceToUse);
You create a new request. This gives you back a MultipartManifest, which will later let you check if parts failed.
manifest =
assembler.newRequest(
request.getContentType(),
request.getContentLanguage(),
request.getContentEncoding(),
request.getOpcMeta());
Then you add all the parts:
assembler.addPart(
ProgressTrackingInputStreamFactory.create(
chunk, progressTrackerFactory.getProgressTracker()),
chunk.length(),
null);
Then you commit. This is where your code currently throws. I suspect not all parts have been added.
CommitMultipartUploadResponse response = assembler.commit();
If something goes wrong, check MultipartManifest.listCompletedParts(), MultipartManifest.listFailedParts(), and MultipartManifest.listInProgressParts(). The manifest should tell you what parts failed. Unfortunately not why; for that, you can enable ERROR level logging for com.oracle.bmc.objectstorage.transfer (for the class com.oracle.bmc.objectstorage.transfer.internal.MultipartTransferManager in particular).
If I have misunderstood something, please let me know. In that case, a larger, more complete code snippet would help me debug. Thanks!

Error -999 when loading multiple webViews

The iOS app I am making can have multiple webViews loading the same url at the same time. Resulting in this error:
Error Domain=NSURLErrorDomain Code=-999 "The operation couldn’t be completed.
(NSURLErrorDomain error -999.)" UserInfo=0x176b7bc0 {NSErrorFailingURLKey=https://example.com,
NSErrorFailingURLStringKey=https://example.com}
I read this happens when a new request is started before the old request has been completed. How do I prevent this from happening? Thanks
I spent weeks worrying about this error. I was getting it randomly while accessing web pages. In my case I put it down to pages being requested too quickly back to back as the web access was driven by a state machine in code and not by a user.
After much searching, in the end I found a few discussions which could not explain why the error was occuring, but it was felt that it was feature of UIWebView rather than something you should worry about. The guidance was to ignore it. I will see if I can find the article and update this answer later if I can find it.
I updated my code as follows, and so far have seen no ill effects at all since adding it. This would suggest it is almost a notification and anything which causes it seems to get corrected inside UIWebView. Hopefully this is the same in your case.
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
VSSLog(#"Entry: error = %#",error);
// Added this based on net advice. Its a bogus error.
if ([error code] == NSURLErrorCancelled) {
return;
}
... Normal error handling code for proper errors.
}
I am not one for out of sight out of mind, but this I believe is one of those cases where it is ok.
Finally if you are using iOS8 only, you could try moving to use the new WKWebView rather than UIWebView.
Use the delegate methods. Determine which view fired the method then fire the next if you're looking to run them sequentially.
- (void) webViewDidFinishLoad:(UIWebView *)webview{
if ( webview == self.wView1 )
{
// stuff
} else if ( webview == self.wView2 ) {
// stuff 2
}
}
UITableViewDelegate Protocol Reference

MvxDynamicImageHelper unreliable

I have an Mvx base iOS project which is having problems with image downloads.
I have a couple of screens which contain UICollectionViews and the UICollectionViewCells use MvxDynamicImageHelpers to set the Image of their UIImageViews to images hosted on the internet (Azure blob storage via Azure CDN in actual fact). I have noticed that the images sometimes do not appear and that this is more common on a slow connection and if I scroll through the whole UICollectionView while the images are loading - presumably as it initiates a large number of simultaneous downloads. Restarting the app causes some, but not all, of the images to be shown.
Looking in the Caches/Pictures.MvvmCross folder I see there are a number of files with .tmp extensions and some without .tmp extensions but a 0 byte file size. I presume that the .tmp files are the ones that are re-downloaded following an app restart and that an invalid in-memory cache entry is causing them not to be re-downloaded until this happens.
I have implemented my versions of MvxDownloadRequest and MvxHttpFileDownloader and registered my IMvxHttpFileDownloader. The only modification in MvxHttpFileDownloader is to use my MvxDownloadRequest instead of the standard Mvx one.
As far as I can see, there are no exceptions being thrown in MvxDownloadRequest.Start or MvxDownloadRequest.ProcessResponse and MvxDownloadRequest.FileDownloadFailed is not being called. Having replaced MvxDownloadRequest.Start with the following, all images are always downloaded and displayed successfully:
try
{
ThreadPool.QueueUserWorkItem((state) => {
try
{
var fileService = this.GetService<IMvxSimpleFileStoreService>();
var tempFilePath = DownloadPath + ".tmp";
var imageData = NSData.FromUrl(NSUrl.FromString(Url));
var image = UIImage.LoadFromData(imageData);
NSError nsError;
image.AsPNG().Save(tempFilePath, true, out nsError);
fileService.TryMove(tempFilePath, DownloadPath, true);
}
catch (Exception exception)
{
FireDownloadFailed(exception);
return;
}
FireDownloadComplete();
});
}
catch (Exception e)
{
FireDownloadFailed(e);
}
So, what could be causing the problems with the standard WebRequest which is not affecting the above version? I'm guessing it's something to with GC and will do further debugging when I get time, but this won't be fore a while unfortunately. Would be very much appreciated if someone can answer this or provide pointers for when I do look at it.
Thanks,
J
From the description of your investigations so far, it sounds like you have isolated the problem down to the level that httpwebrequest sometimes fails, but that the NSData methods are 100% reliable.
If this is the case, then it would suggest that the problem is somewhere in the xamarin.ios network stack or in the use of it.
It might be worth checking the xamarin bugzilla repository and also asking their support team if they are aware of any issues in this area. I believe they did make some announcements about changes to the iOS networking at evolve - see the CFNetworkHandler part late in the video and slides at http://xamarin.com/evolve/2013#session-b3mx6e6rmb - and there are worrying questions on here like iPhone app gets into a state where network requests never complete
Beyond that, I'd guess the first step in any debugging would be to isolate the issue in a simple test app - eg a simple app which just downloads one image at a time and which demonstrates a simple pass/fail for each technique. If you can replicate the issue in a small test app, then it'll be much quicker to work out what the issue is.

WebAPI and HTML5 SSE

was trying to encapsulate a partial view to show feedback that i can push back to the client.
This Article shows a method of pushing back data using HTML5 Server-Sent events (SSE).
I noticed that if i opened up several browser tabs and then closed one i got exceptions as the logic didn't remove the respective stream from the ConcurrentQueue. I amended the code as below
private static void TimerCallback(object state)
{
StreamWriter data;
Random randNum = new Random();
// foreach (var data in _streammessage)
for (int x = 0; x < _streammessage.Count; x++)
{
_streammessage.TryDequeue(out data);
data.WriteLine("data:" + randNum.Next(30, 100) + "\n");
try
{
data.Flush();
_streammessage.Enqueue(data);
}
catch (Exception ex)
{
// dont re-add the stream as an error ocurred presumable the client has lost connection
}
}
//To set timer with random interval
_timer.Value.Change(TimeSpan.FromMilliseconds(randNum.Next(1, 3) * 500), TimeSpan.FromMilliseconds(-1));
}
I also had to amend the OnStreamAvailable member as the framework syntax had changed to the second parameter being a HttpContent rather than HttpContentHeaders
public static void OnStreamAvailable(Stream stream, HttpContent headers, TransportContext context)
The problem now is i am still getting inconsistant behaviour if i add or remove clients i.e it times out when trying to initialise a new client. Does anyone have any ideas or more examples of using SSE with WinAPI and the correct "framework of methods" to handle disconnected clients
Cheers
Tim
This article is actually an adaptation of my original article from May - http://www.strathweb.com/2012/05/native-html5-push-notifications-with-asp-net-web-api-and-knockout-js/ (notice even variable names and port numbers are the same :-).
It is a very valid point that you are raising, and detecting a broken connection is something that's not very easy with this setup. The main reason is that while ASP.NET (the host) allows you to check a broken connection, there is no notification mechanism between ASP.NET (host) and Web API informing about that.
That is why in order to detect a broken connection (disconnected client) you should really try writing to the stream, and catch any error - this would mean the client has been disconnected.
I asked the same question to Brad Wilson/Marcin Dobosz/Damien Edwards at aspconf, and Damien suggested using HttpContext.Current.Response.IsClientConnected - so basically bypassing Web API and obtaining the connectivity info from the underlying host directly (however there is still a race condition involved anyway). That is really .NET 4. He also pointed an interesting way in which this problem could be avoided in .NET 4.5 using an async cancellation token. Frankly, I have never got around to test it, but perhaps this is something you should explore.
You can see their response to this problem in this video - http://channel9.msdn.com/Events/aspConf/aspConf/Ask-The-Experts - fast forward to 48:00

AS3 Shared Object slows swf down and makes webpage unressponsive

I have a swf that I would like to cookie to control the frame the user see's depending on whether it is a first time site visit or returned visit. My code is below - it works, it doesn't bring back any out messages however when I load the swf into my site that uses this technique the page becomes extremely slow and unresponsive - can anyone help out with any reasons why this may occur?
var my_so:SharedObject = SharedObject.getLocal("visited", "/");
if (my_so.data.newVisitor != undefined) {
//object exists: return user
this.gotoAndPlay(2);
} else {
//object doesn't exist: new user
my_so.data.newVisitor = "no";
this.gotoAndStop(1);
}
Many thanks in advance
Rachel
SharedObjects in general are extremely slow in Flash. That being said, there is no reason why it should be slowing down your entire site after it has been used.
When writing to a SO, you have to use flush() to tell Flash to actually write the data.
my_so.data.newVisitor = "no";
// Write the data to disk
my_so.flush();
Another thing to try would be to actively close the connection after you are done with it. So after the else statement you would add:
// Close the connection
my_so.close();
// Clear pointer for GC
my_so = null;
If that doesn't work, the next steps would be to put trace statements in and around the SOs and make sure they aren't being accessed while the program is running.