play music on windows phone 8.1 - windows-phone-8.1

I tried to get all the music files into listbox and play the selected file.
The below code is what i did to play music but unfortunately it doesn't play. Can anyone tell me what the mistake is?
private async void button1_Click(object sender, RoutedEventArgs e)
{
StorageFolder folder = Windows.Storage.KnownFolders.MusicLibrary;
IReadOnlyList<StorageFile> files = await folder.GetFilesAsync();
foreach (var file in files)
{
MusicProperties music = await file.Properties.GetMusicPropertiesAsync();
listBox2.Items.Add(music.Title);
}
}
private async void listBox2_Tapped(object sender, TappedRoutedEventArgs e)
{
try
{
StorageFolder folder = Windows.Storage.KnownFolders.MusicLibrary;
IReadOnlyList<StorageFile> files = await folder.GetFilesAsync();
if (files.Count > 0)
{
var file = files[listBox2.SelectedIndex];
mediaElement1.Source = new Uri(files[listBox2.SelectedIndex].Path);
textBlock1.Text = files[listBox2.SelectedIndex].Path;
mediaElement1.Play();
}
}
catch(Exception ex)
{
textBlock1.Text = ex.Message;
}
}

Instead mediaElement1.Source = new Uri(files[listBox2.SelectedIndex].Path); you need use the code bellow:
var fileStream = await file.OpenReadAsync();
mediaElement.SetSource(fileStream, file.ContentType);

You need to use BackgroundMediaPlayer with background task.
MSDN
You can write apps for Windows Phone 8.1 that play audio in the background. This means that even after the user has left your app by pressing the Back button or the Start button on their device, your app can continue to play audio.
Scenarios for background audio playback include:
Long-running playlists The user briefly brings up a foreground app to select and start a playlist, after which the user expects the playlist to continue playing in the background.
Using task switcher The user briefly brings up a foreground app to start playing audio, then switches to another open app using the task
switch. The user expects the audio to continue playing in the
background.

Related

Store update of 8.1 app to uwp app

I have a Windows Phone 8.1 app in the store. Now I have created an uwp update. My question is:
If I load an update of the app into the store and an user does this update. Is the app just overwritten or deinstalled and then new installed? And are the saved settings in ApplicationData.Current.LocalSettings deleted?
thx newone
TL;DR; - It preserves data in LocalFolder and LocalSettings when updating from WP8.1 Runtime to UWP (tested with mobile on device with Insider preview - Fast ring).
I've run similar test, like the last time:
I've published a Beta version of the App - WP8.1 Runtime.
After successful installation on the Phone, I've created a file in LocalFolder and set value in LocalSettings (see code below),
I've submitted an update - went to Store, selected the App, clicked Update then Packages, after a while, browse your files and chosen the new generated appxbundle (I have not deleted the old WP8.1 package), save and submit.
After some time my Phone is notified that there is an update for the App - I click update
After successful installation, I see that it's a new App, I click my special button to check LocalFolder and value in LocalSettings - I see that there are old values from WP8.1 version.
Code for buttons used to test:
private async void Generate_Click(object sender, RoutedEventArgs e)
{
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("test.txt");
await FileIO.WriteTextAsync(file, "Something inside");
}
private async void CheckFile_Click(object sender, RoutedEventArgs e)
{
try
{
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("test.txt");
string text = await FileIO.ReadTextAsync(file);
await new MessageDialog($"File exists = {text}").ShowAsync();
}
catch (Exception) { await new MessageDialog("File desnt exists").ShowAsync(); }
}
private void GenerateSetting_Click(object sender, RoutedEventArgs e) => ApplicationData.Current.LocalSettings.Values["CHECK"] = "Test value";
private async void CheckSetting_Click(object sender, RoutedEventArgs e)
{
if (ApplicationData.Current.LocalSettings.Values.ContainsKey("CHECK"))
await new MessageDialog($"Setting exists = {ApplicationData.Current.LocalSettings.Values["CHECK"]}").ShowAsync();
else await new MessageDialog("Setting doesn't exist").ShowAsync();
}

WinRT Toolkit Windows Phone 8.1 save video wth CameraCaptureControl

I'm pretty new on Windows Phone 8.1 development and what I'm currently trying is recording a video and store it on the Windows Phone. However, I don't have any idea how that can be done. I have some code excerpt below which is the code executed when the start/stop record button is pressed. The code is taken from an example.
My questions:
How _videoFile can be saved to the VideoLibrary?
Preferably I would like the program to execute a method when recording is stopped. How I get the video filename inside this method?
private async void OnCaptureVideoButtonClick(object sender, RoutedEventArgs e)
{
if (!_capturingVideo)
{
//BtnStartStop.Content = "Stop";
StartAppBarButton.Icon = new SymbolIcon(Symbol.Stop);
_capturingVideo = true;
_videoFile = await TestedControl.StartVideoCaptureAsync(KnownFolders.VideosLibrary, "capture.mp4");
CapturedVideoElement.Visibility = Visibility.Visible;
IRandomAccessStreamWithContentType stream;
try
{
stream = await TryCatchRetry.RunWithDelayAsync<Exception, IRandomAccessStreamWithContentType>(
_videoFile.OpenReadAsync(),
TimeSpan.FromSeconds(0.5),
10);
}
catch (Exception ex)
{
#pragma warning disable 4014
new MessageDialog(ex.Message, "Error").ShowAsync();
#pragma warning restore 4014
return;
}
CapturedVideoElement.SetSource(stream, _videoFile.ContentType);
}
else
{
StartAppBarButton.Icon = new SymbolIcon(Symbol.Camera);
_capturingVideo = false;
#pragma warning disable 4014
await TestedControl.StopCapture();
#pragma warning restore 4014
}
}
Using the await keyword, StartVideoCaptureAsync is called asynchronously.
So the next line of code will be executed only once this asynchronous task is finished.
It means that the line of code below (and all the next ones):
CapturedVideoElement.Visibility = Visibility.Visible
will be executing at the end of the recording.
So if you need to execute a method after the recording is done, you can just put it after the call of StartVideoCaptureAsync.

CameraPreviewImageSource empty preview frame

I made cut and paste of the code below about how to use CameraPreviewImageSource and access to preview buffer frames, but do not work and it seems the frame buffer size is 0x0 reading the value of IImageSize parameter of OnPreviewFrameAvailable event.
How to get preview buffer of MediaCapture - Universal app
protected override void OnNavigatedTo(NavigationEventArgs e)
{
InitializeAsync();
}
public async void InitializeAsync()
{
_cameraPreviewImageSource = new CameraPreviewImageSource();
await _cameraPreviewImageSource.InitializeAsync(string.Empty);
var properties = await _cameraPreviewImageSource.StartPreviewAsync();
var width = 640.0;
var height = 480;
_writeableBitmap = new WriteableBitmap((int)width, (int)height);
_writeableBitmapRenderer = new WriteableBitmapRenderer(_cameraPreviewImageSource, _writeableBitmap);
Initialized = true;
_cameraPreviewImageSource.PreviewFrameAvailable += OnPreviewFrameAvailable;
}
private async void OnPreviewFrameAvailable(IImageSize args)
{
System.Diagnostics.Debug.WriteLine("ww:"+args.Size.Width+" hh:"+args.Size.Height);
// Prevent multiple rendering attempts at once
if (Initialized && !_isRendering)
{
_isRendering = true;
try
{
await _writeableBitmapRenderer.RenderAsync();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("\n\n"+ex.Message);
System.Diagnostics.Debug.WriteLine(ex.StackTrace);
}
_isRendering = false;
}
}
Capabilities (webcam & microphone) on Package.appxmanifest has been selected
Implementing CameraPreviewImageSource on a Silverlight app works great!
I am afraid you are (were) seeing a bug in Lumia Imaging SDK 2.0.184. The problem only occured on some camera models and only on 8.1/universal applications. Silverlight applications were not affected by the problem.
The bug has been fixed in the newly released Lumia Imaging SDK 2.0.208. From release notes:
Fixed ArgumentOutOfRangeException being thrown by CameraPreviewImageSource when used with certain camera models.

Share Media Task

I'm developing app for Windows Phone 8, and i'm trying to share image via ShareMediaTask.
The procedure? that i use for it is as follows :
private static Microsoft.Phone.Tasks.ShareMediaTask shareMediaTask;
public static void shareCurrentCroppedImage ()
{
shareMediaTask = new Microsoft.Phone.Tasks.ShareMediaTask();
GC.Collect();
Debug.WriteLine("file path : {0}", currentFileName);
shareMediaTask.FilePath = currentFileName;
shareMediaTask.Show();
}
The path from console looks like this:
file path : C:\Data\Users\Public\Pictures\Saved Pictures\Lo_1.jpg
Unfortunately, when i call this proc ( from button click event ) the app shuts down, a black screen shows, but then suddenly workflow returns back to my app without any sharing UI. How can i fix this issue? Any help would be appreciated!
This is the code which worked for me..
I had created a PhotoChooserTask to capture an image or open an existing image from library and then when this PhotoChooserTask completes, I create a ShareMediaTask and set its Filepath property to The "OriginalFileName" filed from the parameter photoresult e.
The issue with your code, i think, might be this path of image.
private void OnShareMediaTaskClicked(object sender, RoutedEventArgs e)
{
var photoChooserTask = new PhotoChooserTask { ShowCamera = true };
photoChooserTask.Completed += OnPhotoChooserTaskCompleted;
photoChooserTask.Show();
}
void OnPhotoChooserTaskCompleted(object sender, PhotoResult e)
{
var photoChooserTask = (PhotoChooserTask)sender;
photoChooserTask.Completed -= OnPhotoChooserTaskCompleted;
var shareMediaTask = new ShareMediaTask ();
shareMediaTask.FilePath = e.OriginalFileName;
shareMediaTask.Show();
}
I have set the OnShareMEdiaClicked as ahandler of an onClick event for a button. and the rest flow is clear.
Hope this helps.

WP8 - WebBrowser class : How to handle downloading of file?

I have created a simple app in WP8 to display web pages using the Microsoft.Phone.Controls.WebBrowser class.
I am able to load the page, navigate links, move back and forward in history.
Apart from this basic functionality I also want to provide means to download files which cannot be displayed within the browser like say .ppt or .mp3.
I have not been able to find anything in the WebBrowser class documentation to initiate a download. There is just a Navigate function which takes a URL to load.
So can a download be done using WebBrowser class?
You'll have to intercept the navigation events and handle it on your own.
The following code sample should point you in the right direction. (You'll want to polish that up, I just put that together to show it can work with a random mp3 site that came up on Google when I searched for test mp3 files)
using Microsoft.Phone.Controls;
using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Net;
using System.Threading.Tasks;
using System.Windows;
namespace PhoneApp2
{
public partial class MainPage
{
public MainPage()
{
InitializeComponent();
MyWebBrowser.Navigate(new Uri("http://robtowns.com/music/"));
}
private async void MyWebBrowser_OnNavigating(object sender, NavigatingEventArgs e)
{
if (!e.Uri.AbsolutePath.EndsWith(".mp3")) return; //Find a more reliable way to detect mp3 files
e.Cancel = true; // Cancel the browser control navigation, and take over from here
MessageBox.Show("Now downloading an mp3 file");
var fileWebStream = await GetStream(e.Uri);
using(var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
var filePath = "downloadedfile.mp3";
var localFile = isolatedStorage.CreateFile(filePath);
await fileWebStream.CopyToAsync(localFile.AsOutputStream().AsStreamForWrite());
fileWebStream.Close();
MessageBox.Show("File saved as 'downloadedfile.mp3'");
}
}
public static Task<Stream> GetStream(Uri url)
{
var tcs = new TaskCompletionSource<Stream>();
var wc = new WebClient();
wc.OpenReadCompleted += (s, e) =>
{
if (e.Error != null) tcs.TrySetException(e.Error);
else if (e.Cancelled) tcs.TrySetCanceled();
else tcs.TrySetResult(e.Result);
};
wc.OpenReadAsync(url);
return tcs.Task;
}
}
}