AVAudioplayer initialize component throws a null exception - ios

string mediafile;
mediafile=Constants.AudioLink;
NSUrl url1=new NSUrl(mediafile);
var audioplayer=AVAudioPlayer.FromUrl(url1);
URL is getting link correctly but audio player getting value null. It throws an exception below:
Could not initialize an instance of the type 'AVFoundation.AVAudioPlayer': the native 'initWithContentsOfURL:error:' method returned nil.
It is possible to ignore this condition by setting : MonoTouch.ObjCRuntime.Class.ThrowOnInitFailure to false
What can i do, Please give me the solution.

These is a really quick example of loading/playing an .mp3 file that has a build type of BundledResource (I dropped into the Resources folder of the project) and thus is placed in the app's root directory).
I do a quick check via AudioToolbox.AudioSource.Open to make sure the file exists, can be read, and is a valid media file type so I know that AVAudioPlayer will not throw a fatal error trying to load it.
AVAudioPlayer player; // Class level object ref
partial void playButtonTouch (UIButton sender)
{
if (player != null && player.Playing)
player.Stop ();
else {
var mp3File = "WildTurkeysEN-US.mp3";
var mp3URL = new NSUrl (mp3File);
Console.WriteLine (mp3URL.AbsoluteUrl);
var mp3 = AudioToolbox.AudioSource.Open (mp3URL, AudioFilePermission.Read, AudioFileType.MP3);
if (mp3 != null) {
Console.WriteLine (mp3.EstimatedDuration);
player = AVAudioPlayer.FromUrl (mp3URL);
player.Play ();
} else {
Console.WriteLine ( "File could not be loaded: {0}", mp3URL.FilePathUrl );
}
}
}

Related

Xamarin iOS ALAssetsLibrary WriteVideoToSavedPhotosAlbum doesn't save to library

I am writing an iOS application using Xamarin and am having an issue getting videos to save to my photo library. I am using the WriteVideoToSavedPhotosAlbum method of the ALAssetsLibrary (code below), but the video is never saved. I do no receive an error, but I also do not receive an asset URL in the completion block either.
Does anyone have any idea what could be going on here?
var url = NSUrl.FromFilename (this.FilePath);
ALAssetsLibrary library = new ALAssetsLibrary ();
library.WriteVideoToSavedPhotosAlbum (url, delegate(NSUrl u, NSError e)
{
if (e != null)
{
new UIAlertView ("Error", "Unable to save video to library", null, "Ok").Show();
}
});
One thing to note is the FilePath value is a video stored in the applications document directory.
Thanks
One thing to note is the FilePath value is a video stored in the applications document directory? What you are looking for exactly? as WriteVideoToSavedPhotosAlbum is use to store video capture using camera because directly we can not get its url so we have to store video or image captured using camera to device first then we can get its url and other information using ALAssetsLibrary
I have done like this and its working for me hope this might help you:
ALAssetsLibrary library = new ALAssetsLibrary();
library.WriteImageToSavedPhotosAlbum(originalImage.CGImage, meta, (assetUrl, error) =>
{
library.AssetForUrl(assetUrl, delegate (ALAsset asset)
{
ALAssetRepresentation representation = asset.DefaultRepresentation;
if (representation != null)
{
string fileName = representation.Filename != null ? representation.Filename : string.Empty;
var filePath = assetUrl.ToString();
var extension = filePath.Split('.')[1].ToLower();
var mimeData = string.Format("image/{0}", extension);
var mimeType = mimeData.Split('?')[0].ToLower();
var documentName = assetUrl.Path.ToString().Split('/')[1];
}
}, delegate (NSError err) {
Console.WriteLine("User denied access to photo Library... {0}", err);
});
});

Exception when trying to load .mp3 file in Phaser

I am trying to load a very short .mp3 file in my preload() function like this:
game.load.audio('sword', '$assetPath/swordraw.mp3', true);
As soon as this code gets executed, it crashes with the error
Breaking on exception: Invalid arguments(s)
pointing to a console.warn in Phaser's Loader's fileError function which is as below:
fileError(int index) {
this._fileList[index]['loaded'] = true;
this._fileList[index]['error'] = true;
this.onFileError.dispatch([this._fileList[index]['key'], this._fileList[index]]);
window.console.warn("Phaser.Loader error loading file: "
+ this._fileList[index]['key'] + ' from URL ' + this._fileList[index]['url']);
this.nextFile(index, false);
}
Through the debugger of DartEditor I have seen that for some reason _fileList[10]['url'] (URL for audio file) is picked up as being null here, and that is the cause of the exception (can't concat. null to a string) but why is url null?
I've checked the obvious: the file name is correct and assetPath is certainly initialised correctly since all the other files (which are images) before this load fine. So this seems like an audio file issue of some kind but I can't see what the problem is.
Oh, seems like I found the offender here... https://github.com/playif/play_phaser/blob/ae6a08e5a6eb159149fac01e5831fd8572223a44/lib/loader/loader.dart#L1447
When the Loader is setting up stuff about a newly added file it calls this getAudioUrl if the file is an audio file...
getAudioURL(urls) {
//String extension;
if (urls is String) {
urls = [urls];
}
for (var i = 0; i < urls.length; i++) {
var url = urls[i];
//extension = urls[i].toLowerCase();
//extension = extension.substr((Math.max(0, extension.lastIndexOf(".")) || Infinity) + 1);
if (this.game.device.canPlayAudio(url.split('.').last)) {
//return urls[i];
return url;
}
}
return null;
}
...and as you may gather from the above, the method will return null seemingly if the device cannot play the the type of file supplied. So then, Dartium can't play .mp3s?

Error handling in Dart with throw catch. (Catch doesn't seem to execute)

I'm trying out Dart for the first time and I can't get the error handling to work for me. Here's some information about it.
Resources:
Gist with HTML, CSS and Dart: gist.github.com/enjikaka/8164610
ZIP with the project: ge.tt/6StW4cB1/v/0?c
JavaScript version on CodePen: codepen.io/enjikaka/pen/giurk
How I want it:
Making an instance of MinecraftSkin should throw an StateError if the image source returns a 403 error code. The exception should be handled in the generateHead() function where the instance of MineCraft skin is attempted to be made.
How it is:
If an image representing the skin of a MineCraft player does not exist (when the image source does not exist and returns 403) the code stops on line 22 (onError; where I throw the StateError) and prints to console "Breaking on exception: Bad state: User has no skin".
However, in the catch on generateHead, nothing gets executed. It doesn't print the StateError message when I prompt it to, neither does it insert the StateError message to the selected element in the DOM.
Code
import 'dart:html';
class MinecraftSkin {
String user;
CanvasElement ce = new CanvasElement();
void _generateCanvas(Event e) {
CanvasRenderingContext2D ctx = ce.getContext('2d');
ctx.imageSmoothingEnabled = false;
ctx.drawImageScaledFromSource((e.target as ImageElement),8,8,8,8,0,0,ce.width,ce.height);
}
CanvasImageSource getHead() => ce;
String name() => user;
MinecraftSkin(String minecraftUser, num size) {
user = (minecraftUser == null) ? 'Notch' : minecraftUser;
ce.width = size;
ce.height = size;
ImageElement img = new ImageElement()
..onLoad.listen(_generateCanvas)
..onError.listen((_) => throw new StateError('User has no skin'));
img.src = "http://s3.amazonaws.com/MinecraftSkins/"+user+".png";
}
}
void generateHead(Event e) {
MinecraftSkin ms;
try {
ms = new MinecraftSkin((querySelector('#userName') as InputElement).value, 128);
} on StateError catch(se) {
print(se.message);
querySelector('#status').text = se.message;
}
CanvasElement cems = ms.getHead();
cems.id = "mc" + ms.name();
cems.title = "mc" + ms.name();
document.body.append(cems);
querySelector('#status').text = "Got head!";
}
void main() {
querySelector('#generateHead').onClick.listen(generateHead);
}
Thanks in advance!
Sincerely, Jeremy
The image listeners (onLoad, onError) are asynchronous. The MincraftSkin instantiation is completed without any errors, and only after the image resource is loaded or an error is received, is the StateError thrown, probably several hundred milliseconds later. The constructor does not wait around to see if the image will properly load or not.

an exception is occurred while play an audio in blackberry

try {
Player p = javax.microedition.media.Manager.createPlayer("abc.mp3");
p.realize();
VolumeControl volume = (VolumeControl)p.getControl("VolumeControl");
volume.setLevel(30);
p.prefetch();
p.start();
} catch(MediaException me) {
Dialog.alert(me.toString());
} catch(IOException ioe) {
Dialog.alert(ioe.toString());
}
I used above code to play an audio in blackberry. But it gives an exception error as mentioned in below.
javax.microedition.media.MediaException
If you look at the BlackBerry API docs, you see that for the version of createPlayer() that you use:
MediaException - Thrown if a Player cannot be created for the given locator.
It also says:
locator - A locator string in URI syntax that describes the media content.
Your locator ("abc.mp3") doesn't look like it's in URI syntax. You could try changing that, to something like "file:///SDCard/some-folder/abc.mp3".
Or, if the mp3 file is an app resource, I usually use this code:
try {
java.io.InputStream is = getClass().getResourceAsStream("/sounds/abc.mp3");
javax.microedition.media.Player p =
javax.microedition.media.Manager.createPlayer(is, "audio/mpeg");
p.realize();
// get volume control for player and set volume to max
VolumeControl vc = (VolumeControl) p.getControl("VolumeControl");
if (vc != null) {
vc.setLevel(100);
}
// the player can start with the smallest latency
p.prefetch();
// non-blocking start
p.start();
} catch (javax.microedition.media.MediaException me) {
// do something?
} catch (java.io.IOException ioe) {
// do something?
} catch (java.lang.NullPointerException npe) {
// this happened on Tours without mp3 bugfix
}

FileIOException: File already exists error on blackberry

i get thumbnail image using fileconnection.
I get image using thread constructor. I pass the url and get image.
If the two image url are same , i got exception "FileIOException: File already exists "
My code is here.,
FileConnection fConn = null;
try
{
String fileString = MD5.encodeStringMD5(url);
fConn = (FileConnection) Connector.open(fileTempPath+fileString+".png");
if(!fConn.exists())
{
fConn.create();
GetImageFromURL(url,fConn,id);
}
else
{
GetImageFromFolder(fConn, id);
}
fConn.close();
}
catch (Exception e)
{
System.out.println("------"+e);
}
If the urls are differ. No problem occur. But if two or three url r same , Only one image only stored and load on screen. others same url not displaying.
After stored on device memory, its loadding all image.
The Exception throws in this line - "fConn.create();"
Before creating a new file, try to open a file with the same name/path. If it already exists remove it.
If file already exits then do like this:
if(!fConn.exists())
{
fConn.create();
GetImageFromURL(url,fConn,id);
}
else
{
fConn.truncate();//it removes the data in that file;
GetImageFromFolder(url,fConn, id);
}

Resources