How do I play sound when app begins windows phone - c#

On my windows phone app, I want to play a short .wav audio, similar to windows when it boots up. At first I tried using an event handler when one of my controls was loaded (this worked about 60% of the time, which is very interesting, maybe someone can clear that up as well, I'm thinking it has to do with the order things happen to load. That's why its different each time running it). I'm using visual studios 2012 ultimate, this is my xaml code for the .wav file:
<MediaElement x:Name="MySound"
Source="/quantum_drive.wav"
Volume="1"
AutoPlay="false"
/>
I've also just tried to call this method when the main page loads:
private void MainPage1_Loaded(object sender, RoutedEventArgs e)
{
MySound.Play();
}
For some reason this only works about 60% of the time(seemingly randomly), why is this?! This seems like a common thing to want to do in a phone app, yet I cannot find any information on this on stackoverflow or google searches.

Don't use the media element to do what you are trying to do. It is to buggy for sound effects. It is meant more for user interaction media.
Instead, do the following (you can the full article here)
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework;
static Stream stream1 = TitleContainer.OpenStream("soundeffect.wav");
static SoundEffect sfx = SoundEffect.FromStream(stream1);
static SoundEffectInstance soundEffect = sfx.CreateInstance();
Now just invoke play sound from your loaded method
public void playSound(){
FrameworkDispatcher.Update();
soundEffect.Play();
}

Related

Xamarin - Constantly getting NSInvalidArgumentException on Button click

I'm currently doing some cross-platform mobile development through Visual Studio using Xamarin (so in C#) and am about to start the iOS portion. I've never done iOS development before and thought I could get myself acquainted with their "Hello, iOS" Tutorials. Unfortunately, things have not been going smoothly. I constantly get NSInvalidArgumentExceptions from my TouchUpInside actions:
Foundation.MonoTouchException: Objective-C exception thrown.
Name: NSInvalidArgumentException Reason:
-[ViewController TranslateButton_TouchUpInside:]:
unrecognized selector sent to instance 0x7b6200d0
I can occasionally remedy it for a moment by literally remaking the Buttons, but it breaks pretty much right afterwards. The actual error itself occurs in my Main.cs file:
using UIKit;
namespace CheckinIOS
{
public class Application
{
static void Main(string[] args)
{
UIApplication.Main(args, null, "AppDelegate"); //this line is where it breaks
}
}
}
In case it is any helpful, I am trying to deploy to iPhone 5S simulator running iOS 9.3 (but it breaks on iPhone 6 simulator as well). I could also post more of my code if necessary, but I copypasted all the C# from Xamarin's tutorial, and did the same thing as them for Main.storyboard.
I have spent a while looking for people with the same problem as me, but their solutions either did not work, or they got the error for slightly different reasons. Any assistance is appreciated.
EDIT: Here is my implementation of TranslateButton_TouchUpInside:
TranslateButton.TouchUpInside += (object sender, EventArgs e) =>
{
// Convert the phone number with text to a number
// using PhoneTranslator.cs
translatedNumber = PhoneTranslator.ToNumber(PhoneNumberText.Text);
// Dismiss the keyboard if text field was tapped
PhoneNumberText.ResignFirstResponder();
if (translatedNumber == "")
{
CallButton.SetTitle("Call", UIControlState.Normal);
CallButton.Enabled = false;
}
else
{
CallButton.SetTitle("Call " + translatedNumber, UIControlState.Normal);
CallButton.Enabled = true;
}
};
The iOS Runtime is looking for a method called (in Obj-C land) TranslateButton_TouchUpInside: in your ViewController class. However there is no method exported to Obj-C with that name. A first guess is that you added an event to the button in the storyboard that perhaps had that name, but you either deleted that method or never implemented it.
Try opening your storyboard in iOS Designer and removing any event from the Properties->Events tab when your button is selected on the canvas. Also I assume your button has the name TranslateButton in the Properties->Widget pane when the button is selected on the canvas.
There are a couple ways to attach events to controls in Xamarin iOS. One, and the preferred way, is to create an event in iOS Designer for the control. If you do this, a partial method stub will be in the .designer.cs file with an Export attribute that exports the method name to the Obj-C runtime. You will then need to implement this method, using the same signature (without the Export Attribute), in your main .cs file for the ViewController. This is called, in Obj-C land, an action.
The other way is to do as is shown in your code snippet. In this case you ONLY need to give the control a name in the Properties->Widget pane that you can then use in code to subscribe to the TouchUpInside event. This is called, in Obj-C land, an outlet.
My guess is that you did both but without ever implementing the TranslateButton_TouchUpInside: method in your ViewController. Note that this is the Obj-C name used in the Export attribute of the method stub created in the .designer.cs file when you add an event to a control.
But it is hard to say without seeing the storyboard and both the main ViewController.cs file and the ViewController.designer.cs file

MediaPlayer Universal Windows App

I started to develop application using xamarin, and one of projects inside my solution is UWP.
I need to play sound there when someone clicked button, I'm using MediaPlayer to achieve my goal, and on windows 10 (desktop) it works fine, but on my Windows Mobile 10 (Lumia 930) it starts with long delay (about 1 second).
Below I provide my code to play audio source:
MediaPlayer _player = BackgroundMediaPlayer.Current;
_player.SetUriSource(new Uri(String.Format("ms-appx:///Assets/Sound/5s.wav", UriKind.Absolute)));
_player.Play();
My Question is:
Is there any other way to play audio in UWP than MediaPlayer?
If you don't have specific reason to use background audio, you can use just media element to play audio in foreground:
<!-- create element in XAML or in code -->
<MediaElement Name="mediaElement" ... />
// Code - set source or reference to stream
MediaElement mediaElement = new MediaElement();
mediaElement.Source = new Uri("msappx:///Media/sound.mp3");
I would also recommend to check with the list of supported codecs.
In more complex scenarios you may want to look at Audio Graph API.
I'm not sure if this is bad practice or not, but I am able to get instant playback if I pre-load the media.
Something like this example in pseudo-code (c# style):
class Foo
{
private MediaPlayer _player;
Foo() //constructor
{
_player = BackgroundMediaPlayer.Current;
_player.AutoPlay = false;
_player.SetUriSource(new Uri(String.Format("ms-appx:///Assets/Sound/5s.wav", UriKind.Absolute)));
}
void ButtonClicked(Object sender, EventArgs event)
{
_player.Play();
}
}

MvvmCross picturechoosen plugin and camera stuck issue

Hi I'm experiencing a strange problem with a MvvmCross picturechooser plugin for iOS development using Xamarin. I am developing a form where user can choose/take multiple photos and a video.
My app allow users to add multiple photos either from the camera roll or to be captured directly from form.
For capturing video, i use Xamarin.Mobile api.
I'm using the MvvmCross picture choosen to do this. The problem occurs when 1 or 2 images / videos are taken with the camera.
Once 1 or 2 images / videos are captured when the camera screen is re-entered for a third time the image is static and doesn't update the camera view finder. The view is stuck at the last frame of whatever was captured last.
I have the same problem described here but only difference is that I used MvvmCross picture choosen plugin.
in my code i used to bind the command with my button as follow:
// MyView is inherited from MvxViewController (of mvvmcross)
var set = this.CreateBinding<MyView,MyViewModel>();
//Binding button to picture chooser command
set.Bind(this.TakePhotoButton).To(vm=>vm.TakePictureCommand);
and in my view model:
public MvxCommand TakePictureCommand
{
get
{
this.takePictureCommand => this.takePictureCommand ?? new MvxCommand(()=>
this.pictureChooserTask.TakePicture(300,95,this.OnPictureSelected,
()=>{}),,this.CanTakeOrChoosePicture);
}
}
private void OnPictureSelected(Stream stream)
{
using(var memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
// PictureBytes is a property which i am using to bind with image view
this.PictureBytes= memoryStream.ToArray();
}
}
private bool CanTakeOrChoosePicture()
{
return this.PictureBytes= null;
}
can any one guide me what am i doing wrong?
Looking at iOS Monotouch UIImagePickerController multiple photos / videos from camera, it looks like this is either an issue in Xamarin.iOS or in iOS/UIKit.
Do you see the same problem in the main MvvmCross sample apps?
If you do, then you can try changing the MvvmCross code to use delegates instead of the Xamarin.iOS C# events as suggested in iOS Monotouch UIImagePickerController multiple photos / videos from camera - the Mvx code is in https://github.com/MvvmCross/MvvmCross/blob/v3.1/Plugins/Cirrious/PictureChooser/Cirrious.MvvmCross.Plugins.PictureChooser.Touch/MvxImagePickerTask.cs
Another thing you can perhaps try, is to use a separate task for each image request - e.g. using var task = Mvx.Resolve<IMvxPictureChooserTask(); to get a new task each time instead of using the same constructor injection task every time.
If nothing else helps, then maybe try contacting Xamarin support to see if they are aware of the issue and have any suggestions.

Windows Phone MediaElement

I am creating an app using c# and xaml where i have 20 pages each page has some character images and when i tap on that image some dialogues should pop up.so i have taken a MediaElement and made it global like this:
App.xaml:
<MediaElement x:Key="StorySound"
Volume="1"
AutoPlay="True"/>
App.xaml.cs:
public static MediaElement StorySound
{
get { return Current.Resources["StorySound"] as MediaElement; }
}
And on every page on tap event i have written this code:
App.StorySound.Source = new Uri("/Sounds/Dialogues/" + textblock.Text + ".mp3", UriKind.Relative);
App.StorySound.MediaOpened+=StorySound_MediaOpened;
void StorySound_MediaOpened(object sender, RoutedEventArgs e)
{
App.StorySound.Play();
}
This plays the sound on not more than 2 pages when i navigate to the 3rd page using the next button which i have created no sound plays but when i close the app and directly open the 3rd page the sound plays.I have even tested this by using MessageBox to show the current state of the mediaelement i have found that on the first two pages the current state is "Opening" and the sound plays but on the third page the current state is "Closed" so the sound does not Play.is there any memory issue when playing sounds using MediaElement.I cannot use SoundEffect Because all my sound files are .mp3 and if i use soundeffect i will have to convert these sounds in .wav which will increase the size of my app because i have more than 50 sound files.
If I understand you correctly you are hooking the MediaOpened-event on the global StorySound-object on each page but you never seem to unhook it.
I would suggest you to either:
use a local MediaElement on each page that you start (and perhaps stop), or
make sure you unhook all events on the StorySound when you navigate (so that each page is the only "user" of this global resource).
I am sure it will be fine to have may mp3's in your app; you should not need to convert them to wav.

Set source and play a single mp3 file on each button on windows phone 7

i'm trying to make an application for windows phone 7.1 for schoool. I want to play a sound for each pressed button on my application (just like istantfun button for android) but i have some problem. If i declare on my xaml all the 120 Media Elements my applcation will play only 3/4 sound randomly. I want to make something like this:
private void button1_Click(object sender, RoutedEventArgs e)
{
prova.Source = new Uri("/mp3/call.mp3", UriKind.Relative);
prova.Play();
}
where prova is a single MediaElement declared on the first page of xaml file.
How can i do? Thanks advice
first of all if you want play sound in multi-page app than media element is no good solution.
Besides of it's limitation (single sound at a time) and after considering amount of sound effects maybe you should try using XNA as described here: http://www.dotnetscraps.com/dotnetscraps/post/Play-multiple-sound-files-in-Silverlight-for-Windows-Phone-7.aspx
public void PlaySound(string soundFile)
{
using (var stream = TitleContainer.OpenStream(soundFile))
{
var effect = SoundEffect.FromStream(stream);
FrameworkDispatcher.Update();
effect.Play();
}
}
With this solution you don't need any XAML elements and thus you can play it app-wide.

Categories