Media player in Windows Phone 7 - c#

I am using the media player in Windows Phone 7 to play the music in the phone song collection. But when it play the music they will be an exception and the error is stating
FrameworkDispatcher.Update has not been called. Regular FrameworkDispatcher.Update calls are necessary for fire and forget sound effects and framework events to function correctly.
How should i go about modifying my code?
private void songBtn_Click(object sender, RoutedEventArgs e)
{
using (var ml = new MediaLibrary())
{
foreach (var song in ml.Songs)
{
System.Diagnostics.Debug.WriteLine(song.Artist + " " + song.Name);
MessageBox.Show(song.Artist + " " + song.Name);
}
MediaPlayer.Play(ml.Songs[0]);
}
}

You have to call
FrameworkDispatcher.Update()
whenever you make a call to an XNA media library
so your code should look like this
using (var ml = new MediaLibrary())
{
foreach (var song in ml.Songs)
{
System.Diagnostics.Debug.WriteLine(song.Artist + " " + song.Name);
MessageBox.Show(song.Artist + " " + song.Name);
}
FrameworkDispatcher.Update();
MediaPlayer.Play(ml.Songs[0]);
}

The error is occouring because you're using the XNA Framework in a regular Windows Phone 7 application.
If you read the error description, you would gotten this link to MSDN: Enable XNA Framework Events in Windows Phone Applications , which explains precisely what to do.

Related

How would I detect and display an HTTP error message(404) on Xamarin if I'm using an API wrapper?

I am currently using Xamarin to create a multiplatform application for the phone. The app idea is basically a Pokemon encyclopedia that utilizes the PokeAPi (https://pokeapi.co/) and also uses the following wrapper library (https://gitlab.com/PoroCYon/PokeApi.NET). Currently, I want it to where if the user types in an incorrect Pokemon into the search bar, it will return an alert error to the user. However, every time I test it and enter in an invalid pokemon, the application stops and Visual Studio/Xamarin informs me of a HTTP404 error. How would I go about this?
I've tried using comparison statements in where if the API call doesn't find the pokemon name, it should pop up with an alert, but VS/Xamarin will stop running the application and display a Http404 exception. I really dont know where to go at this point.
'''
async Task PullData()
{
LoadingIcon.IsRunning = true;
string newPokemon = PokemonFind.Text;
Pokemon p = await DataFetcher.GetNamedApiObject<Pokemon>(newPokemon);
string PokemonName = p.Name;
int PokemonHeight = p.Height;
int PokemonWeight = p.Mass;
int PokemonXp = p.BaseExperience;
int PokemonOrder = p.Order;
OrderLabel.Text = "#" + PokemonOrder;
NameLabel.Text = "Name: " + PokemonName;
HeightWeightLabel.Text = "Height/Weight: " + PokemonHeight.ToString() +" dm " + "/" + PokemonWeight.ToString() + " hg";
ExpLabel.Text = "Experience on defeat: " + PokemonXp.ToString() + "XP";
LoadingIcon.IsRunning = false;
}
'''
I expected it to display an alert message instead of VS/Xamarin stopping the program and throwing me an HTTP404 exception.
Wrap your call inside a try/catch block
try
{
async Task PullData()
}
catch(HttpRequestException ex)
{
//Shows an alert error to the user
}

Load achievements from Google Play without any Unity plugins only native code

It is possible to use this code from Unity samples:
//C#
Social.LoadAchievements (achievements => {
if (achievements.Length > 0) {
Debug.Log ("Got " + achievements.Length + " achievement instances");
string myAchievements = "My achievements:\n";
foreach (IAchievement achievement in achievements)
{
myAchievements += "\t" +
achievement.id + " " +
achievement.percentCompleted + " " +
achievement.completed + " " +
achievement.lastReportedDate + "\n";
}
Debug.Log (myAchievements);
}
else
Debug.Log ("No achievements returned");
});
and get Google Play achievements. Or it's works only for iOs devices and for Android I have to use some plugins?
This script as I understood works only for iOs devise not for Android.
Why don't use standard Unity Google plugin?
- Because they don't teach it to load achievements.
/// <summary>
/// Not implemented yet. Calls the callback with an empty list.
/// </summary>
public void LoadAchievements(Action<IAchievement[]> callback) {
Logger.w("PlayGamesPlatform.LoadAchievements is not implemented.");
if (callback != null) {
callback.Invoke(new IAchievement[0]);
}
}
Why not to use the official Google Play Services plugin for Unity?
Here's a Link to an official Google Developer web site, where you can find all the information you need to set it up correctly.
This plugin works on both Android and iOS Devices!

Trying to update livetile from backgroundaudiotask in Windows Phone 8.1: "The application identifier provided is invalid"

I have a music player and would like to update the livetile with the albumart of the playing track. So each time the track changes I call a method in a seperate Windows Runtine Component. The method looks like this:
public async void CreateLivetile(string albumart, string artist, string trackname)
{
try
{
// constants
string textElementName = "text";
string imageElementName = "image";
// Create a tile update manager
var updater = TileUpdateManager.CreateTileUpdaterForApplication();
updater.EnableNotificationQueue(true);
updater.Clear();
// wide 310x150
var tileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWide310x150PeekImage03);
tileXml.GetElementsByTagName(textElementName).LastOrDefault().InnerText = string.Format(artist + " - " + trackname);
var image = tileXml.GetElementsByTagName(imageElementName).FirstOrDefault();
if (image != null)
{
var src = tileXml.CreateAttribute("src");
src.Value = albumart;
image.Attributes.SetNamedItem(src);
}
// square 150x150
var squaredTileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquare150x150PeekImageAndText01);
squaredTileXml.GetElementsByTagName(textElementName).FirstOrDefault().InnerText = string.Format(artist + " - " + trackname);
image = squaredTileXml.GetElementsByTagName(imageElementName).LastOrDefault();
if (image != null)
{
var src = squaredTileXml.CreateAttribute("src");
src.Value = albumart;
image.Attributes.SetNamedItem(src);
}
updater.Update(new TileNotification(tileXml));
updater.Update(new TileNotification(squaredTileXml));
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
// Inform the system that the task is finished.
//_deferral.Complete();
}
}
When the method reaches this line:
var updater = TileUpdateManager.CreateTileUpdaterForApplication();
I get this error:
The application identifier provided is invalid.
This method does work fine in the app (front-end)...
There is solution:
http://social.msdn.microsoft.com/Forums/windowsapps/en-US/83498107-fe0d-4a8b-93f3-02d484983953/tileupdatemanager-throws-exception?forum=wpdevelop
Just provide ID directly:
TileUpdateManager.CreateTileUpdaterForApplication("App")
You've found a common bug in the simulator.
From one of Microsoft's blogs:
We’ve found two scenarios that cause this failure. The first is during
app development when running the app in the simulator in Visual
Studio. This error may be thrown when updating tiles. The
recommendation is to run the app under the Local Machine setting
[...].
Secondly, this failure can occur when the underlying notification
platform is not available on the user’s machine. If the notification
platform has encountered an issue that caused it to terminate, it
causes tile notification and updating to fail as well. The call to
TileUpdateManager.CreateTileUpdaterForApplication normally retrieves
the package full name, creates a notification endpoint, and performs
package and app name validation for the notification subsystem.
Problems with either of the last two steps can cause “The application
identifier provided is invalid” to be returned, generating this
exception.
See also:
updating tiles in Win 8 Metro app
Why is identifier for secondary tile invalid?
"cant-update-secondary-tile"

NAudio record never receiving a sample

I'm attempting the simplest possible NAudio example to record from an input device but for some reason I can't get the DataAvailable callback function to be called.
In the example below a break point on Do Something never gets hit.
WaveIn waveIn = new WaveIn();
waveIn.DeviceNumber = 0;
waveIn.DataAvailable += waveIn_DataAvailable;
waveIn.RecordingStopped += new EventHandler(waveIn_RecordingStopped);
waveIn.WaveFormat = new WaveFormat(44100, 1);
waveIn.StartRecording();
private void waveIn_DataAvailable(object sender, WaveInEventArgs e)
{
Do Something
}
I've checked, re-checked and re-re-checked that the settings are exactly the same as those used by the NAudio VoiceRecorder test application which is able to record audio fine with the exact same settings.
The only difference is my test application is a console application rather than a WPF app. Would that make a difference?
Yes, it is because it is a console app, and the WaveIn class uses Windows messages as callbacks. If you are able to download and build the very latest source code from codeplex, you can use the brand new WaveInEvent class (added 6 Mar 2012), which does not rely on a Windows message loop.
Alternatively, if you are familiar with installing pre-release packages using NuGet, you can install the latest NAudio prerelease (currently 1.5.4-beta) which has this class in.
Just a thought, have you verified your device is valid?
Try something like this;
int waveInDevices = WaveIn.DeviceCount;
for (int waveInDevice = 0; waveInDevice < waveInDevices; waveInDevice++)
{
WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(waveInDevice);
MessageBox.Show("Device " + waveInDevice + ": " + deviceInfo.ProductName +
", " + deviceInfo.Channels + " channels");
}
to verify you have a recording device.

Mute/unmute, Change master volume in Windows 7 x64 with C#

How can I adjust master volume in Windows 7 with C#?
I have seen an excellent implementation using winmm.dll here, but it works with XP and not with Windows 7.
I used the nuget package Naudio successfully with this code:
public void SetVolume(int level)
{
try
{
//Instantiate an Enumerator to find audio devices
NAudio.CoreAudioApi.MMDeviceEnumerator MMDE = new NAudio.CoreAudioApi.MMDeviceEnumerator();
//Get all the devices, no matter what condition or status
NAudio.CoreAudioApi.MMDeviceCollection DevCol = MMDE.EnumerateAudioEndPoints(NAudio.CoreAudioApi.DataFlow.All, NAudio.CoreAudioApi.DeviceState.All);
//Loop through all devices
foreach (NAudio.CoreAudioApi.MMDevice dev in DevCol)
{
try
{
if (dev.State == NAudio.CoreAudioApi.DeviceState.Active)
{
var newVolume = (float)Math.Max(Math.Min(level, 100),0) / (float)100;
//Set at maximum volume
dev.AudioEndpointVolume.MasterVolumeLevelScalar = newVolume;
dev.AudioEndpointVolume.Mute = level == 0;
//Get its audio volume
_log.Info("Volume of " + dev.FriendlyName + " is " + dev.AudioEndpointVolume.MasterVolumeLevelScalar.ToString());
}
else
{
_log.Debug("Ignoring device " + dev.FriendlyName + " with state " + dev.State);
}
}
catch (Exception ex)
{
//Do something with exception when an audio endpoint could not be muted
_log.Warn(dev.FriendlyName + " could not be muted with error " + ex);
}
}
}
catch (Exception ex)
{
//When something happend that prevent us to iterate through the devices
_log.Warn("Could not enumerate devices due to an excepion: " + ex.Message);
}
}
CodeProject has a very good sample here. Note that it relies on COM interop completely (check COM interface like IAudioEndpointVolume and IAudioMeterInformation on MSDN if you are interested in implementation details), and works ONLY for Vista/Win7 and higher.
Minimum supported client: Windows Vista
Minimum supported server: Windows Server 2008

Categories