I implemented audio implementation and added looping property also. But the audio Plays a two times only and after that audio doesn't play. Here I attached a code I implemented. Kindly help how to fix. Thanks for advance
namespace Com.Audio.Droid
{
public class AudioService : IAudio
{
public AudioService()
{
}
public void PlayAudioFile(string fileName)
{
var player = new MediaPlayer();
var fd = global::Android.App.Application.Context.Assets.OpenFd("siren.wav");
player.Prepared += (s, e) =>
{
player.Start();
};
player.SetDataSource(fd.FileDescriptor, fd.StartOffset, fd.Length);
player.Looping = true;
player.Prepare();
}
public void PauseAudioFile(string fileName)
{
Device.BeginInvokeOnMainThread(() =>
{
var player = new MediaPlayer();
var fd = global::Android.App.Application.Context.Assets.OpenFd("siren.wav");
player.Prepared += (s, e) =>
{
player.Stop();
player.Release();
player.Dispose();
};
player.SetDataSource(fd.FileDescriptor, fd.StartOffset, fd.Length);
player.Prepare();
});
}
}
}
And in iOS the audio play a only one second. It's doesn't play the audio file entirely
namespace com.Audio.ios
{
public class AudioService : IAudio
{
public AudioService()
{
}
public void PlayAudioFile(string fileName)
{
string sFilePath = NSBundle.MainBundle.PathForResource(Path.GetFileNameWithoutExtension("siren"), Path.GetExtension("siren.wav"));
var url = NSUrl.FromString(sFilePath);
var _player = AVAudioPlayer.FromUrl(url);
_player.FinishedPlaying += (object sender, AVStatusEventArgs e) =>
{
_player = null;
};
_player.NumberOfLoops = -1;
_player.Play();
}
public void PauseAudioFile(string fileName)
{
string sFilePath = NSBundle.MainBundle.PathForResource(Path.GetFileNameWithoutExtension("siren"), Path.GetExtension("siren.wav"));
var url = NSUrl.FromString(sFilePath);
var _player = AVAudioPlayer.FromUrl(url);
_player.FinishedPlaying += (object sender, AVStatusEventArgs e) =>
{
_player = null;
};
_player.Stop();
}
}
}
For Android
You need a hook way to implement a loopMediaPlayer, that is creating a new player when the audio is finished.
Refer to : https://stackoverflow.com/a/29883923/8187800 .
For iOS
Due to ARC , probably AVAudioPlayer is released after calling dependency service , to solved it you can try to make _player as global variable .
Refer to
https://stackoverflow.com/a/8415802/8187800 .
Related
I am using a Dependency service to pick a photo from the gallery. and I want to show the path when the user selects an image from their phone in a Label.
I have read too many logs but not getting the proper results.
I want it like this:
Now the selected image is displayed properly but what I don't get is how to display the path of the selected image.
Please suggest me how to do it for both android and ios.
Note: I'm using Dependency service for it so I don't want third-party plugins.
I hope I will get a better solution for this.
Thanks in advance.
Creating the interface in forms
namespace xxx
{
public interface IPhotoPickerService
{
Task<Dictionary<string,Stream>> GetImageStreamAsync();
}
}
in iOS
[assembly: Dependency (typeof (PhotoPickerService))]
namespace xxx.iOS
{
public class PhotoPickerService : IPhotoPickerService
{
TaskCompletionSource<Dictionary<string, Stream>> taskCompletionSource;
UIImagePickerController imagePicker;
Task<Dictionary<string, Stream>> IPhotoPickerService.GetImageStreamAsync()
{
// Create and define UIImagePickerController
imagePicker = new UIImagePickerController
{
SourceType = UIImagePickerControllerSourceType.PhotoLibrary,
MediaTypes = UIImagePickerController.AvailableMediaTypes(UIImagePickerControllerSourceType.PhotoLibrary)
};
// Set event handlers
imagePicker.FinishedPickingMedia += OnImagePickerFinishedPickingMedia;
imagePicker.Canceled += OnImagePickerCancelled;
// Present UIImagePickerController;
UIWindow window = UIApplication.SharedApplication.KeyWindow;
var viewController = window.RootViewController;
viewController.PresentModalViewController(imagePicker, true);
// Return Task object
taskCompletionSource = new TaskCompletionSource<Dictionary<string, Stream>>();
return taskCompletionSource.Task;
}
void OnImagePickerFinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs args)
{
UIImage image = args.EditedImage ?? args.OriginalImage;
if (image != null)
{
// Convert UIImage to .NET Stream object
NSData data;
if (args.ReferenceUrl.PathExtension.Equals("PNG") || args.ReferenceUrl.PathExtension.Equals("png"))
{
data = image.AsPNG();
}
else
{
data = image.AsJPEG(1);
}
Stream stream = data.AsStream();
UnregisterEventHandlers();
Dictionary<string, Stream> dic = new Dictionary<string, Stream>();
dic.Add(args.ImageUrl.ToString(), stream);
// Set the Stream as the completion of the Task
taskCompletionSource.SetResult(dic);
}
else
{
UnregisterEventHandlers();
taskCompletionSource.SetResult(null);
}
imagePicker.DismissModalViewController(true);
}
void OnImagePickerCancelled(object sender, EventArgs args)
{
UnregisterEventHandlers();
taskCompletionSource.SetResult(null);
imagePicker.DismissModalViewController(true);
}
void UnregisterEventHandlers()
{
imagePicker.FinishedPickingMedia -= OnImagePickerFinishedPickingMedia;
imagePicker.Canceled -= OnImagePickerCancelled;
}
}
}
in Android
in MainActivity
public class MainActivity : FormsAppCompatActivity
{
...
// Field, property, and method for Picture Picker
public static readonly int PickImageId = 1000;
public TaskCompletionSource<Dictionary<string,Stream>> PickImageTaskCompletionSource { set; get; }
protected override void OnActivityResult(int requestCode, Result resultCode, Intent intent)
{
base.OnActivityResult(requestCode, resultCode, intent);
if (requestCode == PickImageId)
{
if ((resultCode == Result.Ok) && (intent != null))
{
Android.Net.Uri uri = intent.Data;
Stream stream = ContentResolver.OpenInputStream(uri);
Dictionary<string, Stream> dic = new Dictionary<string, Stream>();
dic.Add(uri.ToString(), stream);
// Set the Stream as the completion of the Task
PickImageTaskCompletionSource.SetResult(dic);
}
else
{
PickImageTaskCompletionSource.SetResult(null);
}
}
}
}
[assembly: Dependency(typeof(PhotoPickerService))]
namespace xxx.Droid
{
public class PhotoPickerService : IPhotoPickerService
{
public Task<Dictionary<string,Stream>> GetImageStreamAsync()
{
// Define the Intent for getting images
Intent intent = new Intent();
intent.SetType("image/*");
intent.SetAction(Intent.ActionGetContent);
// Start the picture-picker activity (resumes in MainActivity.cs)
MainActivity.Instance.StartActivityForResult(
Intent.CreateChooser(intent, "Select Picture"),
MainActivity.PickImageId);
// Save the TaskCompletionSource object as a MainActivity property
MainActivity.Instance.PickImageTaskCompletionSource = new TaskCompletionSource<Dictionary<string,Stream>>();
// Return Task object
return MainActivity.Instance.PickImageTaskCompletionSource.Task;
}
}
}
invoke it
Dictionary<string, Stream> dic = await DependencyService.Get<IPhotoPickerService>().GetImageStreamAsync();
Stream stream;
string path;
foreach ( KeyValuePair<string, Stream> currentImage in dic )
{
stream = currentImage.Value;
path = currentImage.Key;
label.Text = path;
if (stream != null)
{
image.Source = ImageSource.FromStream(() => stream);
}
}
Update
If you want to get the path , you could invoke
Dictionary<string, Stream> dic = new Dictionary<string, Stream>();
dic.Add(uri.Path, stream);
Hi i implemented the xamarin video player which is described the following link https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/custom-renderer/video-player/
i am downloading videos through code to the documents folder of the application which has a path like this
[/Users/vaibhavjain/Library/Developer/CoreSimulator/Devices/{GUID}/data/Containers/Data/Application/{GUID}/Documents/MediaDocuments/Nature1.mp4]
now i checked that videos are downloaded correctly to this path but when i am passing this path as source to the video player above it is not able to play it
my guess is that the player is not able to reach the path or it is expecting a relative path but i am unable to find any example of the type of path i should provide.
here is the code for custom Renderer on ios
public class VideoPlayerRenderer : ViewRenderer<VideoPlayer, UIView>
{
AVPlayer player;
AVPlayerItem playerItem;
AVPlayerViewController _playerViewController; // solely for ViewController property
public override UIViewController ViewController => _playerViewController;
protected override void OnElementChanged(ElementChangedEventArgs<VideoPlayer> args)
{
base.OnElementChanged(args);
if (args.NewElement != null)
{
if (Control == null)
{
// Create AVPlayerViewController
_playerViewController = new AVPlayerViewController();
// Set Player property to AVPlayer
player = new AVPlayer();
_playerViewController.Player = player;
var x = _playerViewController.View;
// Use the View from the controller as the native control
SetNativeControl(_playerViewController.View);
}
SetAreTransportControlsEnabled();
SetSource();
args.NewElement.UpdateStatus += OnUpdateStatus;
args.NewElement.PlayRequested += OnPlayRequested;
args.NewElement.PauseRequested += OnPauseRequested;
args.NewElement.StopRequested += OnStopRequested;
}
if (args.OldElement != null)
{
args.OldElement.UpdateStatus -= OnUpdateStatus;
args.OldElement.PlayRequested -= OnPlayRequested;
args.OldElement.PauseRequested -= OnPauseRequested;
args.OldElement.StopRequested -= OnStopRequested;
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (player != null)
{
player.ReplaceCurrentItemWithPlayerItem(null);
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs args)
{
base.OnElementPropertyChanged(sender, args);
if (args.PropertyName == VideoPlayer.AreTransportControlsEnabledProperty.PropertyName)
{
SetAreTransportControlsEnabled();
}
else if (args.PropertyName == VideoPlayer.SourceProperty.PropertyName)
{
SetSource();
}
else if (args.PropertyName == VideoPlayer.PositionProperty.PropertyName)
{
TimeSpan controlPosition = ConvertTime(player.CurrentTime);
if (Math.Abs((controlPosition - Element.Position).TotalSeconds) > 1)
{
player.Seek(CMTime.FromSeconds(Element.Position.TotalSeconds, 1));
}
}
}
void SetAreTransportControlsEnabled()
{
((AVPlayerViewController)ViewController).ShowsPlaybackControls = Element.AreTransportControlsEnabled;
}
void SetSource()
{
AVAsset asset = null;
if (Element.Source is UriVideoSource)
{
string uri = (Element.Source as UriVideoSource).Uri;
if (!String.IsNullOrWhiteSpace(uri))
{
asset = AVAsset.FromUrl(new NSUrl(uri));
}
}
else if (Element.Source is FileVideoSource)
{
string uri = (Element.Source as FileVideoSource).File;
if (!String.IsNullOrWhiteSpace(uri))
{
asset = AVAsset.FromUrl(NSUrl.CreateFileUrl(uri, null));
}
}
else if (Element.Source is ResourceVideoSource)
{
string path = (Element.Source as ResourceVideoSource).Path;
if (!String.IsNullOrWhiteSpace(path))
{
string directory = Path.GetDirectoryName(path);
string filename = Path.GetFileNameWithoutExtension(path);
string extension = Path.GetExtension(path).Substring(1);
NSUrl url = NSBundle.MainBundle.GetUrlForResource(filename, extension, directory);
asset = AVAsset.FromUrl(url);
}
}
if (asset != null)
{
playerItem = new AVPlayerItem(asset);
}
else
{
playerItem = null;
}
player.ReplaceCurrentItemWithPlayerItem(playerItem);
if (playerItem != null && Element.AutoPlay)
{
player.Play();
}
}
// Event handler to update status
void OnUpdateStatus(object sender, EventArgs args)
{
VideoStatus videoStatus = VideoStatus.NotReady;
switch (player.Status)
{
case AVPlayerStatus.ReadyToPlay:
switch (player.TimeControlStatus)
{
case AVPlayerTimeControlStatus.Playing:
videoStatus = VideoStatus.Playing;
break;
case AVPlayerTimeControlStatus.Paused:
videoStatus = VideoStatus.Paused;
break;
}
break;
}
((IVideoPlayerController)Element).Status = videoStatus;
if (playerItem != null)
{
((IVideoPlayerController)Element).Duration = ConvertTime(playerItem.Duration);
((IElementController)Element).SetValueFromRenderer(VideoPlayer.PositionProperty, ConvertTime(playerItem.CurrentTime));
}
}
TimeSpan ConvertTime(CMTime cmTime)
{
return TimeSpan.FromSeconds(Double.IsNaN(cmTime.Seconds) ? 0 : cmTime.Seconds);
}
// Event handlers to implement methods
void OnPlayRequested(object sender, EventArgs args)
{
player.Play();
}
void OnPauseRequested(object sender, EventArgs args)
{
player.Pause();
}
void OnStopRequested(object sender, EventArgs args)
{
player.Pause();
player.Seek(new CMTime(0, 1));
}
}
I don't see your code and can't know what is your problem. I would show you how to make it work about play a local video stored in the document folder:
In xamarin.forms:
public class MyVideoView : View
{
}
And in xaml, simply use this MyVideoView :
<StackLayout>
<!-- Place new controls here -->
<local:MyVideoView HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" />
</StackLayout>
In the iOS project, the custom renderer should be:
public class VideoPlayerRenderer : ViewRenderer
{
AVPlayer player;
AVPlayerItem playerItem;
AVPlayerViewController _playerViewController; // solely for ViewController property
public override UIViewController ViewController => _playerViewController;
protected override void OnElementChanged(ElementChangedEventArgs<View> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
if (Control == null)
{
// Create AVPlayerViewController
_playerViewController = new AVPlayerViewController();
var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var path = Path.Combine(documents, "iOSApiVideo.mp4");
NSUrl url = NSUrl.CreateFileUrl(path, null);
//if you put your video in the project directly use below code
//NSUrl url = NSBundle.MainBundle.GetUrlForResource("iOSApiVideo", "mp4");
// Set Player property to AVPlayer
player = new AVPlayer(url);
_playerViewController.Player = player;
// Use the View from the controller as the native control
SetNativeControl(_playerViewController.View);
player.Play();
}
}
}
}
Replace the path with your own path there and it will work.
Note:
Doesn't work
NSUrl url = new NSUrl(path);
Work
NSUrl url = NSUrl.CreateFileUrl(path, null);
I am posting the final answer because i ended up using Jack's answer to modify my customRenderer.
so i changed this condition in the SetSource() function in custom Renderer
else if (Element.Source is FileVideoSource)
{
string uri = (Element.Source as FileVideoSource).File;
if (!String.IsNullOrWhiteSpace(uri))
{
var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var path = Path.Combine(documents, uri);
NSUrl url = NSUrl.CreateFileUrl(path, null);
asset = AVAsset.FromUrl(url);
}
}
the only change is now i am getting the path inside customRenderer and only passing fileName as the parameter from ViewModel. earlier it was full path like [/Users/vaibhavjain/Library/Developer/CoreSimulator/Devices/{GUID}/data/Containers/Data/Application/{GUID}/Documents/MediaDocuments/Nature1.mp4]
I trying to scan QR-codes in my app. It works sometimes and sometimes not. The feeling is that it doesn't work when something is loading on another thread. For example, if I press the scan button when nearby stores still are loading. Often it works if I wait.
The video capture is working because I will see the preview.
Here is my code:
private bool resultFound;
public ScannerView()
{
InitializeComponent();
On<Xamarin.Forms.PlatformConfiguration.iOS>().SetUseSafeArea(false);
view = new UIView();
ScannerArea.Children.Add(view);
}
void HandleAVRequestAccessStatus(bool accessGranted)
{
if (!accessGranted)
{
MainThread.BeginInvokeOnMainThread(async () =>
{
await NavigationHelper.Current.CloseModalAsync();
});
}
metadataOutput = new AVCaptureMetadataOutput();
var metadataDelegate = new MetadataOutputDelegate();
metadataOutput.SetDelegate(metadataDelegate, DispatchQueue.MainQueue);
session = new AVCaptureSession();
camera = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video).First();
input = AVCaptureDeviceInput.FromDevice(camera);
session.AddInput(input);
session.AddOutput(metadataOutput);
metadataOutput.MetadataObjectTypes = AVMetadataObjectType.QRCode | AVMetadataObjectType.EAN8Code | AVMetadataObjectType.EAN13Code;
metadataDelegate.MetadataFound += MetadataDelegate_MetadataFound;
camera.LockForConfiguration(out var error);
camera.VideoZoomFactor = 2;
camera.UnlockForConfiguration();
layer = new AVCaptureVideoPreviewLayer(session);
layer.VideoGravity = AVLayerVideoGravity.ResizeAspectFill;
layer.MasksToBounds = true;
layer.Frame = UIApplication.SharedApplication.KeyWindow.RootViewController.View.Bounds;
view.Layer.AddSublayer(layer);
session.StartRunning();
}
protected override void OnAppearing()
{
base.OnAppearing();
var status = AVCaptureDevice.GetAuthorizationStatus(AVMediaType.Video);
if (status != AVAuthorizationStatus.Authorized)
{
MainThread.BeginInvokeOnMainThread(() =>
{
AVCaptureDevice.RequestAccessForMediaType(AVMediaType.Video, HandleAVRequestAccessStatus);
});
return;
}
HandleAVRequestAccessStatus(true);
}
protected override void OnDisappearing()
{
base.OnDisappearing();
session.StopRunning();
session.RemoveInput(input);
session = null;
}
void Handle_Clicked(object sender, System.EventArgs e)
{
NavigationHelper.Current.CloseModalAsync();
}
void MetadataDelegate_MetadataFound(object sender, AVMetadataMachineReadableCodeObject e)
{
if (resultFound)
{
return;
}
resultFound = true;
var text = e.StringValue;
Device.BeginInvokeOnMainThread(async () =>
{
Vibration.Vibrate(100);
await NavigationHelper.Current.CloseModalAsync();
TinyPubSub.Publish(NavigationParameter.ToString(), text);
});
}
}
public class MetadataOutputDelegate : AVCaptureMetadataOutputObjectsDelegate
{
public override void DidOutputMetadataObjects(AVCaptureMetadataOutput captureOutput, AVMetadataObject[] metadataObjects, AVCaptureConnection connection)
{
foreach (var m in metadataObjects)
{
if (m is AVMetadataMachineReadableCodeObject)
{
MetadataFound(this, m as AVMetadataMachineReadableCodeObject);
}
}
}
public event EventHandler<AVMetadataMachineReadableCodeObject> MetadataFound = delegate { };
}
I'm using Xamarin forms and writing a dependency service for the following objectives :
Open iOS files app. (UIDocumentPickerViewController )
Select any kind of a document.
Copy that document into my application Documents directory. (For app access)
Show that document into my application by storing its path into my SQLite DB.
What I am trying to do here is call the Files app from my application on an Entry click and the click event seems to be working well my dependency service calls perfectly but now when I try to use the UIDocumentPickerViewController I am unable to get View controller context in my dependency service to call the PresentViewController method. Now I know about the xamarin forms context but I don't know if it will work here and I don't even know if it would be a smart idea to use it as it has already been marked as obsolete and since I am not from the iOS background, I don't know what would be the right solution for it.
My code is as follows :
public class DocumentPickerRenderer : IDocumentPicker
{
public object PickFile()
{
var docPicker = new UIDocumentPickerViewController(new string[] { UTType.Data, UTType.Content }, UIDocumentPickerMode.Import);
docPicker.WasCancelled += (sender, wasCancelledArgs) =>
{
};
docPicker.DidPickDocumentAtUrls += (object sender, UIDocumentPickedAtUrlsEventArgs e) =>
{
Console.WriteLine("url = {0}", e.Urls[0].AbsoluteString);
//bool success = await MoveFileToApp(didPickDocArgs.Url);
var success = true;
string filename = e.Urls[0].LastPathComponent;
string msg = success ? string.Format("Successfully imported file '{0}'", filename) : string.Format("Failed to import file '{0}'", filename);
var alertController = UIAlertController.Create("import", msg, UIAlertControllerStyle.Alert);
var okButton = UIAlertAction.Create("OK", UIAlertActionStyle.Default, (obj) =>
{
alertController.DismissViewController(true, null);
});
alertController.AddAction(okButton);
PresentViewController(alertController, true, null);
};
PresentViewController(docPicker, true, null);
}
}
My questions:
Is my methodology correct for picking files?
what will be the object that I will be getting as a callback from a file selection and how will I get the callback?
Is there any other way or something available for xamarin forms, some guide or something that allows me to pick documents from my native file systems and gives a brief on how to handle it in both ios and android?
Hello Guys, You can use following code for picking any type of documents to mention in code using iOS Devices-
use follwing interface:
public interface IMedia
{
Task<string> OpenDocument();
}
public Task<string> OpenDocument()
{
var task = new TaskCompletionSource<string>();
try
{
OpenDoc(GetController(), (obj) =>
{
if (obj == null)
{
task.SetResult(null);
return;
}
var aa = obj.AbsoluteUrl;
task.SetResult(aa.Path);
});
}
catch (Exception ex)
{
task.SetException(ex);
}
return task.Task;
}
static Action<NSUrl> _callbackDoc;
public static void OpenDoc(UIViewController parent, Action<NSUrl> callback)
{
_callbackDoc = callback;
var version = UIDevice.CurrentDevice.SystemVersion;
int verNum = 0;
Int32.TryParse(version.Substring(0, 2), out verNum);
var allowedUTIs = new string[]
{
UTType.UTF8PlainText,
UTType.PlainText,
UTType.RTF,
UTType.PNG,
UTType.Text,
UTType.PDF,
UTType.Image,
UTType.Spreadsheet,
"com.microsoft.word.doc",
"org.openxmlformats.wordprocessingml.document",
"com.microsoft.powerpoint.ppt",
"org.openxmlformats.spreadsheetml.sheet",
"org.openxmlformats.presentationml.presentation",
"com.microsoft.excel.xls",
};
// Display the picker
var pickerMenu = new UIDocumentMenuViewController(allowedUTIs, UIDocumentPickerMode.Import);
pickerMenu.DidPickDocumentPicker += (sender, args) =>
{
if (verNum < 11)
{
args.DocumentPicker.DidPickDocument += (sndr, pArgs) =>
{
UIApplication.SharedApplication.OpenUrl(pArgs.Url);
pArgs.Url.StopAccessingSecurityScopedResource();
var cb = _callbackDoc;
_callbackDoc = null;
pickerMenu.DismissModalViewController(true);
cb(pArgs.Url.AbsoluteUrl);
};
}
else
{
args.DocumentPicker.DidPickDocumentAtUrls += (sndr, pArgs) =>
{
UIApplication.SharedApplication.OpenUrl(pArgs.Urls[0]);
pArgs.Urls[0].StopAccessingSecurityScopedResource();
var cb = _callbackDoc;
_callbackDoc = null;
pickerMenu.DismissModalViewController(true);
cb(pArgs.Urls[0].AbsoluteUrl);
};
}
// Display the document picker
parent.PresentViewController(args.DocumentPicker, true, null);
};
pickerMenu.ModalPresentationStyle = UIModalPresentationStyle.Popover;
parent.PresentViewController(pickerMenu, true, null);
UIPopoverPresentationController presentationPopover = pickerMenu.PopoverPresentationController;
if (presentationPopover != null)
{
presentationPopover.SourceView = parent.View;
presentationPopover.PermittedArrowDirections = UIPopoverArrowDirection.Down;
}
}
Now you need to call using following code:
var filePath = await DependencyService.Get<IMedia>().OpenDocument();
For pick document in Android, you can use following code
public class IntentHelper
{
public const int DocPicker = 101;
static Action<string> _callback;
public static async void ActivityResult(int requestCode, Result resultCode, Intent data)
{ if (requestCode == RequestCodes.DocPicker)
{
if (data.Data == null)
{
_callback(null);
}
else
{
var destFilePath = FilePath.GetPath(CurrentActivity, data.Data);
_callback(destFilePath);
}
}
}
public static Activity CurrentActivity
{
get
{
return (Xamarin.Forms.Forms.Context as MainActivity);
}
}
public static void OpenDocPicker(Action<string> callback)
{
_callback = callback;
var intent = new Intent(Intent.ActionOpenDocument);
intent.AddCategory(Intent.CategoryOpenable);
intent.SetType("*/*");
CurrentActivity.StartActivityForResult(intent, RequestCodes.DocPicker);
}
}
For pick document in Android, you can use following code:
public class IntentHelper
{
public const int DocPicker = 101;
static Action<string> _callback;
public static async void ActivityResult(int requestCode, Result resultCode, Intent data)
{
if (requestCode == RequestCodes.DocPicker)
{
if (data.Data == null)
{
_callback(null);
}
else
{
var destFilePath = FilePath.GetPath(CurrentActivity, data.Data);
_callback(destFilePath);
}
}
}
public static Activity CurrentActivity
{
get
{
return (Xamarin.Forms.Forms.Context as MainActivity);
}
}
public static void OpenDocPicker(Action<string> callback)
{
_callback = callback;
var intent = new Intent(Intent.ActionOpenDocument);
intent.AddCategory(Intent.CategoryOpenable);
intent.SetType("*/*");
CurrentActivity.StartActivityForResult(intent, RequestCodes.DocPicker);
}
}
Use below code to access the helper class: public class Media:
IMedia {
public Task<string> OpenDocument() {
var task = new TaskCompletionSource<string>();
try {
IntentHelper.OpenDocPicker((path) => { task.SetResult(path); });
} catch (Exception ex) {
task.SetResult(null);
}
return task.Task;
}
}
Since I was looking for UIDocumentPickerViewController and not UIDocumentMenuViewController the other answer was not what I was looking for :
So this is how I ended up doing it:
Calling the document picker:
var docPicker = new UIDocumentPickerViewController(new string[]
{ UTType.Data, UTType.Content }, UIDocumentPickerMode.Import);
docPicker.WasCancelled += DocPicker_WasCancelled;
docPicker.DidPickDocumentAtUrls += DocPicker_DidPickDocumentAtUrls;
docPicker.DidPickDocument += DocPicker_DidPickDocument;
var _currentViewController = GetCurrentUIController();
if (_currentViewController != null)
_currentViewController.PresentViewController(docPicker, true, null);
Where GetCurrentUIController is the function to get the current UI controller something like this :
public UIViewController GetCurrentUIController()
{
UIViewController viewController;
var window = UIApplication.SharedApplication.KeyWindow;
if (window == null)
{
return null;
}
if (window.RootViewController.PresentedViewController == null)
{
window = UIApplication.SharedApplication.Windows
.First(i => i.RootViewController != null &&
i.RootViewController.GetType().FullName
.Contains(typeof(Xamarin.Forms.Platform.iOS.Platform).FullName));
}
viewController = window.RootViewController;
while (viewController.PresentedViewController != null)
{
viewController = viewController.PresentedViewController;
}
return viewController;
}
For below iOS 11 i added the DidPickDocument event:
private void DocPicker_DidPickDocument(object sender, UIDocumentPickedEventArgs e)
{
try
{
NSUrl filePath = e.Url.AbsoluteUrl;
//This is the url for your document and you can use it as you please.
}
catch (Exception ex)
{
}
}
For above iOS 11 you use the DidPickDocumentUrls since multipick is supported there :
private void DocPicker_DidPickDocumentAtUrls(object sender, UIDocumentPickedAtUrlsEventArgs e)
{
try
{
List<NSUrl> filePath = e.Urls.ToList().Select(y => y.AbsoluteUrl).ToList();
//returns the list of images selected
}
catch (Exception ex)
{
AppLogger.LogException(ex);
}
}
Hi Developers,
If we save the recorded voice as a mp3 file. we get the error while opening the file as Windows Media Player cannot play the file. The Player might not support the file type or might not support the codec that was used to compress the file.
Please Give a Solution to overcome this Issue ....
Here is My Source code
namespace Windows_Phone_Audio_Recorder
{
public partial class MainPage : PhoneApplicationPage
{
MemoryStream m_msAudio = new MemoryStream();
Microphone m_micDevice = Microphone.Default;
byte[] m_baBuffer;
SoundEffect m_sePlayBack;
ViewModel vm = new ViewModel();
long m_lDuration = 0;
bool m_bStart = false;
bool m_bPlay = false;
private DispatcherTimer m_dispatcherTimer;
public MainPage()
{
InitializeComponent();
SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;
DataContext = vm;
m_dispatcherTimer = new DispatcherTimer();
m_dispatcherTimer.Interval = TimeSpan.FromTicks(10000);
m_dispatcherTimer.Tick += frameworkDispatcherTimer_Tick;
m_dispatcherTimer.Start();
FrameworkDispatcher.Update();
//icBar.ItemsSource = vm.AudioData;
}
void frameworkDispatcherTimer_Tick(object sender, EventArgs e)
{
FrameworkDispatcher.Update();
}
private void btnStart_Click(object sender, RoutedEventArgs e)
{
m_bStart = true;
tbData.Text = "00:00:00";
m_lDuration = 0;
m_micDevice.BufferDuration = TimeSpan.FromMilliseconds(1000);
m_baBuffer = new byte[m_micDevice.GetSampleSizeInBytes(m_micDevice.BufferDuration)];
//m_micDevice.BufferReady += new EventHandler(m_Microphone_BufferReady);
m_micDevice.BufferReady += new EventHandler<EventArgs>(m_Microphone_BufferReady);
m_micDevice.Start();
}
void m_Microphone_BufferReady(object sender, EventArgs e)
{
m_micDevice.GetData(m_baBuffer);
Dispatcher.BeginInvoke(()=>
{
vm.LoadAudioData(m_baBuffer);
m_lDuration++;
TimeSpan tsTemp = new TimeSpan(m_lDuration * 10000000);
tbData.Text = tsTemp.Hours.ToString().PadLeft(2, '0') + ":" + tsTemp.Minutes.ToString().PadLeft(2, '0') + ":" + tsTemp.Seconds.ToString().PadLeft(2, '0');
}
);
//this.Dispatcher.BeginInvoke(new Action(() => vm.LoadAudioData(m_baBuffer)));
//this.Dispatcher.BeginInvoke(new Action(() => tbData.Text = m_baBuffer[0].ToString() + m_baBuffer[1].ToString() + m_baBuffer[2].ToString() + m_baBuffer[3].ToString()));
m_msAudio.Write(m_baBuffer,0, m_baBuffer.Length);
}
private void btnStop_Click(object sender, RoutedEventArgs e)
{
if (m_bStart)
{
m_bStart = false;
m_micDevice.Stop();
ProgressPopup.IsOpen = true;
}
if (m_bPlay)
{
m_bPlay = false;
m_sePlayBack.Dispose();
}
}
private void btnPlay_Click(object sender, RoutedEventArgs e)
{
m_bPlay = true;
m_sePlayBack = new SoundEffect(m_msAudio.ToArray(), m_micDevice.SampleRate, AudioChannels.Mono);
m_sePlayBack.Play();
}
private void btnSave_Click(object sender, RoutedEventArgs e)
{
if (txtAudio.Text != "")
{
IsolatedStorageFile isfData = IsolatedStorageFile.GetUserStoreForApplication();
string strSource = txtAudio.Text + ".wav";
int nIndex = 0;
while (isfData.FileExists(txtAudio.Text))
{
strSource = txtAudio.Text + nIndex.ToString().PadLeft(2, '0') + ".wav";
}
IsolatedStorageFileStream isfStream = new IsolatedStorageFileStream(strSource, FileMode.Create, IsolatedStorageFile.GetUserStoreForApplication());
isfStream.Write(m_msAudio.ToArray(), 0, m_msAudio.ToArray().Length);
isfStream.Close();
}
this.Dispatcher.BeginInvoke(new Action(() => ProgressPopup.IsOpen = false));
}
}
}
DotNet Weblineindia
my Source Code For UPLOADING A AUDIO TO PHP SERVER:
public void UploadAudio()
{
try
{
if (m_msAudio != null)
{
var fileUploadUrl = "uploadurl";
var client = new HttpClient();
m_msAudio.Position = 0;
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(new StreamContent(m_msAudio), "uploaded_file", strFileName);
// upload the file sending the form info and ensure a result.it will throw an exception if the service doesn't return a valid successful status code
client.PostAsync(fileUploadUrl, content)
.ContinueWith((postTask) =>
{
try
{
postTask.Result.EnsureSuccessStatusCode();
var respo = postTask.Result.Content.ReadAsStringAsync();
string[] splitChar = respo.Result.Split('"');
FilePath = splitChar[3].ToString();
Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/VoiceSlider.xaml?FName=" + strFileName, UriKind.Relative)));
}
catch (Exception ex)
{
// Logger.Log.WriteToLogger(ex.Message);
MessageBox.Show("voice not uploaded" + ex.Message);
}
});
}
}
catch (Exception ex)
{
//Logger.Log.WriteToLogger(ex.Message + "Error occured while uploading image to server");
}
}
First of all Windows Phone does not allow to record .mp3 files. So, the .mp3 file that you are saving will not be played by Windows Phone player.
Have a look at this. This demo is working fine for recording .wav file.
If you wish to save other formats like .aac,.amr then user AudioVideoCaptureDevice class.