The code shown below, which plays an audio file, runs fine within my WPF application. But when I execute the same code within a Windows 8.1 app, I am not getting any exceptions but I am also receiving no sound. Can anyone help?
private void myMediaElement_MediaOpened(object sender, RoutedEventArgs e)
{
myMediaElement.Source =
new Uri(#"C:\Users\Soph\Music\Addicted.mp3", UriKind.Absolute);
myMediaElement.Play();
}
private void btn1_Click(object sender, RoutedEventArgs e)
{
myMediaElement_MediaOpened(sender,e);
}
EDIT:
I have added per the advice the mediaFailed event (followed from http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.mediaelement.mediafailed)
private string GetHresultFromErrorMessage(ExceptionRoutedEventArgs e)
{
String hr = String.Empty;
String token = "HRESULT - ";
const int hrLength = 10; // eg "0xFFFFFFFF"
int tokenPos = e.ErrorMessage.IndexOf(token, StringComparison.Ordinal);
if (tokenPos != -1)
{
hr = e.ErrorMessage.Substring(tokenPos + token.Length, hrLength);
}
return hr;
}
private void mycontrol_MediaFailed(object sender, ExceptionRoutedEventArgs e)
{
// get HRESULT from event args
string hr = GetHresultFromErrorMessage(e);
// Handle media failed event appropriately
}
Then i tried to debug this:
Name Value Type
this {PracMEWindowsApp.MainPage} PracMEWindowsApp.MainPage
e {Windows.UI.Xaml.ExceptionRoutedEventArgs} Windows.UI.Xaml.ExceptionRoutedEventArgs
hr "0x80070003" string
token "HRESULT - " string
tokenPos 40 int
hrLength 10 int
What is this hr capturing ? Why is my file not played ?
To access the Music library specify the Music Library capability in app manifest. It is also good practice to always handle the MediaFailed event.
HRESULT 0x80070003 is "Directory Not Found". That would suggest that the media element doesn't like something about the file path. If you get HRESULT 0x80070005 (Access Denied), then it's probably a permissions-related thing.
Windows Store app does not have access to files in local file system, it runs in a sandboxed environment and only has access to its own data folder, a path like C:\Users\Soph\Music\Addicted.mp3 is unrecognizable.
There are several ways in which you can play the media file.
a.Specify the Music Library capability in Package.appxmanifest (this is required), and then
private async void btn1_Click(object sender, RoutedEventArgs e)
{
var file = await Windows.Storage.KnownFolders.MusicLibrary.GetFileAsync("Addicted.mp3");
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
myMediaElement.SetSource(stream, file.ContentType);
}
or
b. use FileOpenPicker, choose the song manually, you can access any .mp3 file in the file system.
private async void btn1_Click(object sender, RoutedEventArgs e)
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.FileTypeFilter.Add(".mp3");
openPicker.SuggestedStartLocation = PickerLocationId.MusicLibrary;
var file = await openPicker.PickSingleFileAsync();
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
myMediaElement.SetSource(stream, file.ContentType);
}
or
c. Add Addicted.mp3 to your project, and then
Uri uri = new Uri("ms-appx:///Addicted.mp3");
myMediaElement.Source = uri;
you can also set it in XAML
<MediaElement x:Name="myMediaElement" Source="Addicted.mp3" />
Related
I want to create a wpf application for rtsp. I have tried vlclib and followed all the instruction, so dont get any issue but is does not play video.The following is the code for playing the youtube video
VlcContext.LibVlcDllsPath = "C:\Program Files (x86)\VideoLAN\VLC\";
VlcContext.LibVlcPluginsPath = "C:\\Program Files (x86)\\VideoLAN\\VLC\\plugins\\";
private void buttonRtsp_Click(object sender, RoutedEventArgs e)
{
myVlcControl.Stop();
if (myVlcControl.Media != null)
{
myVlcControl.Media.ParsedChanged -= MediaOnParsedChanged;
}
textBlockOpen.Visibility = Visibility.Collapsed;
myVlcControl.Media = new LocationMedia("https://www.youtube.com/watch?v=PxrnoGyBw4E");
myVlcControl.Media.ParsedChanged += MediaOnParsedChanged;
myVlcControl.Play();
}
I've built an app that can read video files from an USB drive and switch between them using physical buttons. The app works well for a while, but after a while the device (DragonBoard 410c, latest Windows Insider Preview Build 15051) crashes due to the fact that all memory has been consumed by the app.
Looking at the processes in the device portal, I can see the "Working Set" memory jump each time I switch a video file while the "Private Working Set" roughly stays the same (around 30MB).
Here's how I load the video file:
C#
private IReadOnlyList<StorageFile> _videofiles
// list all available video files
public void Init(){
var queryOptions = new QueryOptions();
queryOptions.FolderDepth = depth;
foreach (var fileType in fileTypes)
{
queryOptions.FileTypeFilter.Add(fileType);
}
var query = KnownFolders.RemovableDevices.CreateFileQueryWithOptions(queryOptions);
_videofiles = await query.GetFilesAsync();
}
private async void SelectVideo(int videoId)
{
StorageFile videofile = _videofiles.Where(x => x.DisplayName == videoId.ToString()).FirstOrDefault();
if (videofile != null)
{
Debug.WriteLine($"Video {videofile.DisplayName} was selected");
var stream = await videofile.OpenAsync(FileAccessMode.Read);
VideoPlayer.SetSource(stream, videofile.FileType);
}
}
// since the button interrupt is not on the UI thread, SelectVideo() is called like this
private async void SelectVideoMarshalled(int videoId)
{
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
SelectVideo(videoId);
});
}
XAML
<ContentControl x:Name="VideoPlayer" Content="{x:Bind ViewModel.VideoPlayer, Mode=OneWay}"/>
I have tried running GC.Collect() manually in several places, but no luck yet. Any ideas?
Since you have a StorageFile object, I recommend using the Source property and the file's Path instead of SetSource and opening the Stream manually.
Additionally, you should always null out the MediaElement when you're done with it (best done in OnNavigatingFrom).
Here's your code, simplified:
private void SelectVideo(string videoId)
{
var videofile = _videofiles.FirstOrDefault(x => x.DisplayName == videoId.ToString());
if (videofile == null) return;
Debug.WriteLine($"Video {videofile.DisplayName} was selected");
VideoPlayer.Source = new Uri(videofile.Path);
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
VideoPlayer.Stop();
VideoPlayer.Source = null;
base.OnNavigatedFrom(e);
}
I also have a side comment, you can x:Bind event handlers to the ViewModel.
For example, if your video file list is a ListView of string:
public void VideosListView_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e?.AddedItems?.Count > 0)
{
var fileDisplayName = e.AddedItems.FirstOrDefault() as string;
if (!string.IsNullOrEmpty(fileDisplayName))
SelectVideo(fileDisplayName);
}
}
Notice I only need to change the method signature to public and then in the XAML you can do this:
<ListView ItemsSource="{x:Bind ViewModel.VideoFiles, Mode=OneTime}"
SelectionChanged="{x:Bind ViewModel.VideosListView_OnSelectionChanged}"/>
No need to marshal back to the UI thread :)
Lastly, you can check out the demo here on GitHub where I've implemented something similar to this.
Turns out my code was fine after all. I had a Windows Update stuck / failing several times which I didn't notice.
When the update finally completed successfully the memory leaks were gone.
Yes there are many similar questions but none of them address my unique situation.
There is a separate c++ process writing the file using c++ printf and fprintf.
filename i am trying to watch is info_20160525.log
My fileSystemWatcher in winform C# application gets notification when the writer process writes to the file AND I physically access the file i-e F5 the folder or have it open in textpad and click the opened file or right click the file but I never get any event notification when I dont physically interact with the file.
Also, when I shutdown the writer application I do get the notification.
Here is my code.
public bool StartUp(string fullfilepath, int linenumber)
{
if (!File.Exists(fullfilepath))
return false;
if (!LogClass.CheckPathExists(m_applicationPath))
return false;
try
{
FileInfo info = new FileInfo(fullfilepath);
m_filename = fullfilepath;
m_fileWatcher = new FileSystemWatcher(info.DirectoryName, info.Name);
m_fileWatcher.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.LastAccess
| NotifyFilters.LastWrite | NotifyFilters.Size ;
m_fileWatcher.Changed += m_fileWatcher_Changed;
m_fileWatcher.Error += m_fileWatcher_Error;
m_fileWatcher.Created += m_fileWatcher_Created;
m_fileWatcher.Deleted += m_fileWatcher_Deleted;
m_fileWatcher.Disposed += m_fileWatcher_Disposed;
m_fileWatcher.Renamed += m_fileWatcher_Renamed;
m_linesRead = linenumber;
m_fileWatcher.EnableRaisingEvents = true;
}
catch(Exception e)
{
LogClass.LogError(e, "Trouble accessing the file" + fullfilepath, m_applicationPath);
}
return true;
}
These are the handlers. I have breakpoints in each one of them but I never get a trigger unless ofcourse I physically interact with the file.
void m_fileWatcher_Renamed(object sender, RenamedEventArgs e)
{
string S = "";
}
void m_fileWatcher_Disposed(object sender, EventArgs e)
{
string S = "";
}
void m_fileWatcher_Deleted(object sender, FileSystemEventArgs e)
{
string S = "";
}
void m_fileWatcher_Created(object sender, FileSystemEventArgs e)
{
string S = "";
}
void m_fileWatcher_Error(object sender, ErrorEventArgs e)
{
string S = "";
}
void m_fileWatcher_Changed(object sender, FileSystemEventArgs args)
{
if (args.ChangeType == WatcherChangeTypes.Changed)
{
while (ParseFile(args.FullPath))
{
}
}
}
I bet this thread has your answer --> FileSystemWatcher changed event (for “LastWrite”) is unreliable
The FileSystemWatcher uses an update to the LastWrite attribute of a file to fire events, however, the LastWrite is not updated in real time and should not be relied upon as trigger for an event.
If you have enough time and resources on your hands then you probably want to look into File System Filters and the simpler approach of a Filter Manager and Minifilter Driver. It is driver type development, however, it is a sure file way to accomplish your objective.
It is dug down a little deeper by system policy but gives you a wide array of events to latch onto. If I was doing this for anything like pci compliance or similar tasks then I would not use the FileSystemWatcher.
Make sure you set IncludeSubdirectories to true.
https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(v=vs.110).aspx
I wrote a Windows Phone 8.1 (WINRT) App. I am trying to share an image from my app which is in LocalStorage of the app. I am using Windows Phone 8.1 Share Contract.
private async void OnShareDataRequested(DataTransferManager sender, DataRequestedEventArgs _dataRequestedEventArgs)
{
_dataRequestedEventArgs.Request.GetDeferral();
List<StorageFile> ListObject = new List<StorageFile>();
Uri UriObject = new Uri(FileLocation,UriKind.RelativeOrAbsolute);
_dataRequestedEventArgs.Request.Data.Properties.Title = "Dr. App";
_dataRequestedEventArgs.Request.Data.Properties.Description = "Photo from my Dr. App Album.";
StorageFolder StorageFolderObject;
StorageFile StorageFileObject;
try
{
StorageFolderObject = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFolderAsync(LocalCache);
StorageFileObject = await StorageFolderObject.GetFileAsync(FileNameSaved);
_dataRequestedEventArgs.Request.Data.Properties.Thumbnail = RandomAccessStreamReference.CreateFromFile(StorageFileObject);
_dataRequestedEventArgs.Request.Data.SetBitmap(RandomAccessStreamReference.CreateFromFile(StorageFileObject));
ListObject.Add(StorageFileObject);
_dataRequestedEventArgs.Request.Data.SetStorageItems(ListObject);
}
catch(Exception ex_)
{
}
finally
{
_dataRequestedEventArgs.Request.GetDeferral().Complete();
}
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
DataTransferManager.GetForCurrentView().DataRequested -= OnShareDataRequested;
base.OnNavigatedFrom(e);
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
DataTransferManager.GetForCurrentView().DataRequested += OnShareDataRequested;
base.OnNavigatedTo(e);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
DataTransferManager.ShowShareUI();
}
I am getting PREPARING CONTENT TO SHARE and then it vanishes in a second. ShareUI doesnt open.
The documentation states that the asynchronous work has an upper limit of 200 ms. Are you violating this premise?
DataRequest.GetDeferral(): Use this method when you want to use an asynchronous function call to generate the DataPackage during a share operation. This function must return a DataPackage object within 200ms to prevent the operation from timing out. If your app shares content that takes more time to package, such as a collection of files or photos, don't use this method. Instead, use the SetDataProvider method to assign a delegate to a DataPackage and return that DataPackage to the target app.
Another thing that stands out to me when I look at your code is that you invoke the GetDeferral method twice instead of saving the result from the first invocation.
I got stuck trying to implementing file picker for windows phone app. I need to choose files from gallery using FileOpenPicker. I didn't get how it works. Here is my code:
private readonly FileOpenPicker photoPicker = new FileOpenPicker();
// This is a constructor
public MainPage()
{
// < ... >
photoPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
photoPicker.FileTypeFilter.Add(".jpg");
}
// I have button on the UI. On click, app shows picker where I can choose a file
private void bChoosePhoto_OnClick(object sender, RoutedEventArgs e)
{
photoPicker.PickMultipleFilesAndContinue();
}
So, what to do next? I guess I need to get a file object or something.
I found this link. It is msdn explanation where custom class ContinuationManager is implemented. This solution looks weird and ugly. I am not sure if it is the best one. Please help!
PickAndContinue is the only method that would work on Windows Phone 8.1. It's not so weird and ugly, here goes a simple example without ContinuationManager:
Let's assume that you want to pick a .jpg file, you use FileOpenPicker:
FileOpenPicker picker = new FileOpenPicker();
picker.FileTypeFilter.Add(".jpg");
picker.ContinuationData.Add("keyParameter", "Parameter"); // some data which you can pass
picker.PickSingleFileAndContinue();
Once you run PickSingleFileAndContinue();, your app is deactivated. When you finish picking a file, then OnActivated event is fired, where you can read the file(s) you have picked:
protected async override void OnActivated(IActivatedEventArgs args)
{
var continuationEventArgs = args as IContinuationActivatedEventArgs;
if (continuationEventArgs != null)
{
switch (continuationEventArgs.Kind)
{
case ActivationKind.PickFileContinuation:
FileOpenPickerContinuationEventArgs arguments = continuationEventArgs as FileOpenPickerContinuationEventArgs;
string passedData = (string)arguments.ContinuationData["keyParameter"];
StorageFile file = arguments.Files.FirstOrDefault(); // your picked file
// do what you want
break;
// rest of the code - other continuation, window activation etc.
Note that when you run file picker, your app is deactivated and in some rare situations it can be terminated by OS (little resources for example).
The ContinuationManager is only a helper that should help to make some things easier. Of course, you can implement your own behaviour for simpler cases.