playing a single audio file on windows phone - windows-phone-8

I use this code for playing single mp3 audio file and i used MediaElement:
Uri Path = new Uri("AudioFiles/music.mp3", UriKind.Relative);
SoundPlayer.Source = Path;
SoundPlayer.Play();
but i got this error :
An exception of type 'System.ArgumentException' occurred in mscorlib.ni.dll but was not handled in user code
Additional information: The given System.Uri cannot be converted into a Windows.Foundation.Uri.
what is wrong with that ?
Thanks

Depending on the location of your file, you may need a different Uri scheme. Try:
SoundPlayer.Source = new Uri(#"ms-appdata:///local/AudioFiles/music.mp3"); // if your file is in IsolatedStorage
SoundPlayer.Source = new Uri(#"ms-appx:///AudioFiles/music.mp3"); // if your file is a Build-in content
Note also that you don't need SoundPlayer.Play() if SoundPlayer.Autoplay is set to true (default setting). In case it's false - you will have to start to play manually in MediaOpened event not just after setting the Source.

Uri Path = new Uri("/AudioFiles/music.mp3", UriKind.Relative);
You are forgetting a "/" before AudioFiles.

Related

onActivityResult crashes when custom location for video (MediaStore.EXTRA_OUTPUT, URI) is set

So this is my setup for the 'intent':
Intent cameraACTION_VIDEO_CAPTURE = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
tempUri = accessLocalStorage.getThisAppsStorageUriPath();
//Crashed for tempUri = "/data/user/0/hardy.android.go/app_files/test.mp4"
//Crashed for tempUri = "/data/user/0/hardy.android.go/app_files/"
cameraACTION_VIDEO_CAPTURE.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
cameraACTION_VIDEO_CAPTURE.setFlags(cameraACTION_VIDEO_CAPTURE.getFlags() | Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivityForResult(cameraACTION_VIDEO_CAPTURE,
Integer.parseInt( DataModel.SETVIDEORECORDING.toString()));
Video intent starts as expected and crashes once I finish recording - it doesn't even make it to 'onActivityResult'. Error is:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
Don't know why there is a Bitmap floating around in there?
Anywayz, so in an attempt to try and pinpoint the issue, I comment out the following and go again:
cameraACTION_VIDEO_CAPTURE.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
and it works :( - video is stored here:
/storage/emulated/0/DCIM/Camera/VID_20181004_213440310_HDR.mp4
Ok, I have a partial answer. In terms of the application not crashing, I made progress by using FileProvider to generate the Uri.
tempUri = FileProvider.getUriForFile(
context,
BuildConfig.APPLICATION_ID + ".provider",
new File(accessLocalStorage.getThisAppsStorageUriPath().getPath())
);
However, the video File saved at the path in the Uri was of size/length 0 () and I didn't have time to work through this and so, this story ends here :( - hope this is of some help for others!

Multipart/related upload using BackgroundUploader in Windows 8.1

I want to upload a file using Multipart/related Content-Type via BackgroundUploader in windows 8.1
My code is as follows
BackgroundUploader uploader = new BackgroundUploader();
uploader.SetRequestHeader("Content-Type", "multipart/related; boundary=foo_bar_baz");
uploader.Method = "POST";
// Create upload content
List<BackgroundTransferContentPart> parts = new List<BackgroundTransferContentPart>();
// File metadata
var part = new BackgroundTransferContentPart();
part.SetHeader("Content-Type", "text/plain");
part.SetText(file.DisplayName);
parts.Add(part);
// File
// Here file is of type StorageFile
part = new BackgroundTransferContentPart();
part.SetHeader("Content-Type", file.ContentType);
part.SetFile(file);
parts.Add(part);
UploadOperation upload = await uploader.CreateUploadAsync(new Uri("upload_url",UriKind.Absolute), parts);
await upload.StartAsync().AsTask(cts.token); // cts is CancellationTokenSource
However, when I run this code I get an Exception saying
WinRT information: 'boundary': If the 'Content-Type' header is set,
the boundary cannot be empty and must match the boundary set in the
'Content-Type' header.
What is wrong/missing in my code?
If you use the CreateUploadAsync with four parameters then the following might be helpful:
var uploader = new BackgroundUploader();
uploader.SetRequestHeader("Content-Type", "multipart/form-data; charset=utf-8; boundary=0xKhTmLbOuNdArY-3770FB3C-534D-4E6B-9BE0-392FDA960F7B");
var upload = await uploader.CreateUploadAsync(uri, parts, "form-data", "0xKhTmLbOuNdArY-3770FB3C-534D-4E6B-9BE0-392FDA960F7B");
await upload.StartAsync();
Set the boundary in the "SetRequestHeader" without "" (quotes).
Set the same boundary later as the last parameter of CreateUploadAsync.
If you are passing a list of content parts, you don't need to set the Conent-Type header. It's set automatically.
However if you insist in doing so, try:
uploader.SetRequestHeader(
"Content-Type",
"multipart/form-data; boundary=\"foo_bar_baz\"");
UPDATE:
Try using the CreateUploadAsync overload that takes four parameters, where the fourth parameter is the boundary. See here: http://msdn.microsoft.com/en-us/library/ie/hh923975

as3 selecting a file dynamically

i need to select a video file and convert it to a byte array. the file i am trying to select has been recorded by the cameraUi interface. i can get the path to the file using
fileName = media.file.url;
readFileIntoByteArray(filePath, inBytes);
when i am passing it into the byte array i need to select directory first and then pass in the the rest of the path.
private function readFileIntoByteArray(fileName:String, data:ByteArray):void
{
var inFile:File = File.userDirectory;
inFile = inFile.resolvePath(fileName);
trace (inFile.url);
inStream.open(inFile , FileMode.READ);
inStream.readBytes(data);
}
this leads to duplication of the first part of the path.
i want to keep this dynamic as it will be run on different devices. i hard coded the file into the the variables section of flash debugger and it worked also i get an error if i leave out file.userDirectory
thanks in advance any help would be appreciated
You should always use File.applicationStorageDirectory instead of File.userDirectory. Due to security risk will vary to vary different device. File.applicationStorageDirectory will work any device.
Robust way of working with filepath
var firstPartPath:String = File.applicationStorageDirectory.nativePath;
var fullPath:String = File.applicationStorageDirectory.resolvePath("fileName.jpg").nativePath;
var expectedPath:String = fullPath.replace(firstPartPath,""); // "/fileName.jpg"
Here expectedPath value you should pass around your project instead of hard code value like c:\users\XXXX\ and save into database also use expectedPath value.
For latter access file just pass only expectedPath.
var inFile:File = File.applicationStorageDirectory.resolvePath(expectedPath);
Needn't worry about forward and backword slashes. File resolvePath() take care for you.
private function readFileIntoByteArray(fileName:String, data:ByteArray):void
{
var inFile:File = File.applicationStorageDirectory.resolvePath(fileName);
trace (inFile.url);
trace (inFile.nativePath);
trace (inFile.exists); //if file present true else false.
inStream.open(inFile , FileMode.READ);
inStream.readBytes(data);
}

AS3 SWFs Loading External Files; Change default location

If I have a SWF and an XML file sitting in the same folder, is there a way to get the loader to use the location of the SWF as its starting point for loading the external file (as opposed to the HTML file upon which the SWF plays)? We are copying a group of web sites and some of the paths have unique page codes, but if the SWFs would just look in their own folder they would run fine. :)
Thank you!
Chris
Could try this.
var base:String = unescape( LoaderInfo( this.root.loaderInfo ).url ); // url of SWF
// now we need to remove the SWF name from the url
var lastSlash:uint = Math.max( this.base.lastIndexOf( "\\" ), this.base.lastIndexOf( "/" ) );
return( base.substr( 0, lastSlash + 1 ) );
That will take the url of the SWF, loop through it and find the last "\" or "/" to determine where the swf file name starts, and set the base equal to the path of the SWF.
And then change all relative URLRequests from
var url:URLRequest = new URLRequest( "assets/blah/blah/img.png" );
to
var url:URLRequest = new URLRequest( base + "assets/blah/blah/img.png" );
This would be something I would add as a static property of your application class so that you are only accessing a string and not doing any casting or unicode escaping or anything repeatedly. Just run it once at start up and throw it as a static var because it will never change.
(I did test this and it works, at least locally. I see no reason why it would behave any differently with a URL from the web, however)

Flash Builder will not read local JSON file . .

So I've tried to build a small utility to view the contents of a JSON file in an easy-to-understand manner (for non-tech people).
I have Googled far and wide, high and low, but every example that shows how to consume a JSON file in Flash Builder uses the HTTP service, pointing to a file on the web.
Here I am, sitting in front of my MacBook, wondering why I can't make this work. In the documentation I've found (sort of relating to this issue), they always show Windows examples, and they seem to work fine:
C://me/projects/json/my_json.json
Perhaps I'm completely missing the obvious, but is this possible on a Mac as well?
I've tried
file:///Users/me/projects/json/my_json.json
That doesn't work. I've tried some "resolve to path" syntax, but the HTTP service does not seem to allow for anything but file paths in quotes.
Would anyone be able to pint me in the right direction?
Use the File API. It's really easy, here's a quick code sample:
// Get a File reference, starting on the desktop.
// If you have a specific file you want to open you could do this:
// var file:File = File.desktopDirectory.resolvePath("myfile.json")
// Then skip directly to readFile()
var file:File = File.desktopDirectory;
// Add a listener for when the user selects a file
file.addEventListener(Event.SELECT, onSelect);
// Add a listener for when the user cancels selecting a file
file.addEventListener(Event.CANCEL, onCancel);
// This will restrict the file open dialog such that you
// can only open .json files
var filter:FileFilter = new FileFilter("JSON Files", "*.json");
// Open the file browse dialog
file.browseForOpen("Open a file", [filter]);
// Select event handler
private function onSelect(e:Event):void
{
// Remove listeners on e.currentTarget
// ...
// Cast to File
var selectedFile:File = e.currentTarget as File;
readFile(selectedFile);
}
private function onCancel(e:Event):void
{
// Remove listeners on e.currentTarget
// ...
}
private function readFile(file:File):void
{
// Read file
var fs:FileStream = new FileStream();
fs.open(selectedFile, FileMode.READ);
var contents:String = fs.readUTFBytes(selectedFile.size);
fs.close()
// Parse your JSON for display or whatever you need it for
parseJSON(contents);
}
You hinted at this in your post about examples being for Windows and you being on a Mac but I'll state it explicitly here: you should always use the File API because it is cross platform. This code will work equally well on Windows and Mac.