I'm trying to write a WP8 app that plays a short sound when a button is pressed, but I cannot seem to figure out how to play the sound. Here's a quick example of my code:
XAML
<Rectangle x:Name="Rect1" Grid.Row="0" Grid.Column="0" Tap="RectTapped" Fill="White" />
App.cs
private void RectTapped(object sender, System.Windows.Input.GestureEventArgs e)
{
MediaElement sound = new MediaElement();
sound.AutoPlay = false;
sound.Source = new Uri("Assets\\Sounds\\bark-1.wav", UriKind.Relative);
sound.Play();
}
When testing on my Nokie 820 device no sound plays. I can't understand why.
Is there something I'm doing wrong? The .wav is in my resources.
I've read that MediaElement shouldn't be used for this task. I've tried using the SoundEffect class in Xna.Framework.Audio; following the example from MSDN but that also fails because I couldn't use Content.Load as Load was not an available method of the Content class.
I've also looked at XAudio2, but as I do not know C++ I can't get my head around the examples.
You need to add MediaElement to your XAML tree
this.LayoutRoot.Children.Add(sound);
Instead of a Rectangle, use a Button. Also, MediaElement is good for playing short sounds in Silverlight applications. Make sure that the control is a part of your visual tree (add it in XAML). Then bind to the button Click event handler:
private void YourClickHandler(object sender, RoutedEventArgs e)
{
myMediaElement.Source = new Uri("/Assets/Sounds/bark-1.wav", UriKind.Relative);
myMediaElement.Play();
}
You should be using the XNA SoundEffect class instead of the MediaElement because, well, you're playing sound effects.
The documentation is bad for this area, but this is how you do it:
effect = SoundEffect.FromStream(stream);
FrameworkDispatcher.Update();
effect.Play();
so to play a soundeffect from your app package:
var stream = Application.GetResourceStream(filepath);
effect = SoundEffect.FromStream(stream);
FrameworkDispatcher.Update();
effect.Play();
The advantage over MediaElement is that the SoundEffect does not need to be in the visual tree (and also it doesn't screw up the background audio player). The disadvantage is that you have none of the (sometimes useful) events that you have on MediaElement.
For Windows Phone 8.1 Silverlight, take the first two answers (from #DenDelimarsky and #onmyway133) to play the sound.
Without adding MediaElement to XAML sound not played in my case.
Use below code to play sound:
private void YourClickHandler(object sender, RoutedEventArgs e)
{
MediaElement myMediaElement = new MediaElement();
myMediaElement.Source = new Uri("/MP3/AirHornTwoBlows.mp3", UriKind.Relative);
LayoutRoot.Children.Add(myMediaElement);
myMediaElement.Play();
}
Remove the line
sound.AutoPlay=false;
or change it to:
sound.AutoPlay = true;
it will work then.
Related
I know that we can not record/Access anything out of flash player, because of it's security sandbox.
Instead We can record the video while streaming it to server.
like
netStream.publish("YourFileName.flv","record");
But in recorde file, I will get only a video file Published by webcam to server and i want to record entire session.
Is there any way to record it locally, or Can i record the window ??
p.s. : I am not trying to access anything outside of flash player.
Thanks in advance...
ok, so you can record the entire contents of the swf like this:
first, create a container object (anything that extends DisplayObject which implements IBitmapDrawable) then place everything that you want to capture (video view and everything else in your "session") then using an ENTER_FRAME event or Timer (preferable to control capture fps), draw the container to a BitmapData using BitmapData.draw(container). Pass that BitmapData to the FLV encode library found here using it's addFrame() method (docs and examples come with that library... super easy) and that's it! When you are done, you will have an flv video containing a frame by frame "screen capture" of what was going on in your swf! Just make sure EVERYTHING is in the container! That lib also accepts captured audio too if you want.
private function startCapturing():void{
flvEncoder.start(); // see the libs docs and examples
var timer:Timer = new Timer(1000/15); //capture at 15 fps
timer.addEventListener(TimerEvent.Timer, onTimer);
timer.start();
}
private function onTimer(event:TimerEvent):void{
var screenCap:BitmapData = new BitmapData(container.width, container.height);
screenCap.draw(container);
flvEncoder.addFrame(screenCap); // see the libs docs and examples
}
I have an application that allows the user to take photos and save to isolated storage for upload to a server.
I am trying to play a shutter sound when the user clicks the software capture button provided. All documentation I can find indicates that soundeffect.play is asynchronous so the sound should keep playing in the background while logic continues, however in my case the sound either only partially plays or does not have time to play unless I put a breakpoint just after play() or add a Thread.Sleep(x) just after the call to play().
private void BtnCaptureClick(object Sender, RoutedEventArgs E)
{
if (_PhotoCamera != null)
{
PlayShutter();
_FileName = Guid.NewGuid().ToString(); //A breakpoint here will allow sound to play
_PhotoCamera.CaptureImage();
}
}
private void PlayShutter()
{
var Info = App.GetResourceStream(new Uri("Assets/camera.wav", UriKind.Relative));
try
{
_Effect = SoundEffect.FromStream((Info.Stream));
FrameworkDispatcher.Update();
using (_Effect)
{
if (_Effect.Play())
{
//Thread.Sleep(1000); //uncommenting this will allow sound to play if duration < 1000
}
}
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
I have tried using a soundeffectinstance explicitly, however behaviour does not change.
I have tried explicitly calling Play() asynchronously, no change in behaviour.
I have tried calling the following code asynchronously, no change in behaviour.
I have tried calling FrameworkDispatcher.Update frequently, no change in behaviour.
I have tried setting the .wav file in the project to “Resource” but this causes a nullreferenceexception when I call _Effect = SoundEffect.FromStream((Info.Stream)); because Info is null.(even with an absolute path)
This behaviour is present using both the emulator and an actual device via usb connection to pc to debug.
Can anybody help me resolve this frustrating issue please?
Answering my own issue now, it was the using block causing this behaviour, as the instance was being disposed. No idea why I was using that!
Developing tools : Visual Studio 2012, target wp platform : wp8.
I am facing the above problem:
When my application is running on background and i am receiving a notification i vibrate the phone successful and i want to play a specific sound.
What i have tried so far:
Player = new MediaElement();
Player.AutoPlay = true;
Player.Volume = 5;
Player.Source = new Uri("/data/alert.mp3", UriKind.RelativeOrAbsolute);
Player.MediaOpened += (Object s, RoutedEventArgs args) =>
{
Player.Play();
};
I i am not getting any exception but no sound. Neither on foreground nor background .
Am i missing something?
I will appreciate any help.
You can't use the MediaElement API to play notification sounds when the app is in background. In order to launch a notification and play a custom sound, you need to use the ShellToast and use the Sound property via reflection.
Here is how play a custom notification sound from background (MSDN link) Using custom sounds in toasts on Windows Phone 8 Update 3
EDIT: When the app is running in foreground, you can use the same technique (ShellToast with Sound).
Even MediaPlayer class can help you play songs and media in the background when you are showing a toast or a small pop up dialog.
Check here : http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.media.mediaplayer.play.aspx
Could someone tell me what I'm doing wrong here? I'm trying to use one icon in the Windows Phone Application Bar to enable a user to tap it to play and pause background audio that I've inserted as a MediaElement in the XAML. This is my code:
private void ApplicationBarIconButton_Click(object sender, EventArgs e)
{
if (PlayState.Playing == BackgroundAudioPlayer.Instance.PlayerState)
{
BackgroundAudioPlayer.Instance.Pause();
}
else if (PlayState.Paused == BackgroundAudioPlayer.Instance.PlayerState)
{
BackgroundAudioPlayer.Instance.Play();
}
It makes sense reading it through and does not throw up any errors when building, however when I tap it whilst testing on my device, the music does not pause and carries on playing (I've set AutoPlay = true to achieve this) Could someone tell me what I should do to enable one button to control play and pause functionality?
Also if I remove the "else if" and make the code into a simple "else" so it looks like this:
private void ApplicationBarIconButton_Click(object sender, EventArgs e)
{
if (PlayState.Playing == BackgroundAudioPlayer.Instance.PlayerState)
{
BackgroundAudioPlayer.Instance.Pause();
}
else
{
BackgroundAudioPlayer.Instance.Play();
}
}
it pauses, but does not resume to play!
Here is the step by step implementation to achieve play/pause functionality
click and get solution
"I've inserted as a MediaElement in the XAML."
If you are using a MediaElement, I think you are playing the audio in the foreground. Try closing out of your app after the audio starts. Does it keep playing? To pause and play a media element you can just use the play and pause methods on the media element.
nameOfMediaElement.Pause();
nameOfMediaElement.Play();
To use the event handlers that use the BackgroundAudioPlayer.Instance.PlayerState, you have to setup the initial audio playing back in the background. For this you need to start the audio playback via the BackgroundAudioPlayer.
http://msdn.microsoft.com/en-us/library/windowsphone/develop/microsoft.phone.backgroundaudio.backgroundaudioplayer(v=vs.105).aspx
Try this.
if(mediaelement.CurrentState == MediaElementState.Paused)
{
mediaelement.Play();
}
else
{
mediaelement.Pause();
}
Hope it works for you.
I have developed an app in AS3 and Starling to be ported to IOS. I have updated the Default.png image and this works great however my app takes a while to load and a black screen is shown for about 3-4 seconds.
I have looked everywhere for a solution but couldn't find any that work. Does someone have a working solution?
Many thanks
I'm not sure if there is a neater solution at the moment but what I do is add a bitmap of the default screen to the native flash stage. Then when Starling is ready I remove the bitmap.
So before you instantiate Starling, add the bitmap image to the stage (this will be the Flash stage)
public static var _splash:Bitmap;
//load or embed your bitmap//
addChild(_splash);
Then instantiate and start Starling. e.g.
myStarling = new Starling(Main, stage, null, null, Context3DRenderMode.AUTO, Context3DProfile.BASELINE);
myStarling.stage3D.addEventListener(starling.events.Event.CONTEXT3D_CREATE, function(e:flash.events.Event):void {
// Starling is ready!
myStarling.start();
});
In your root Starling class (in this example it's Main), use an ADDED_TO_STAGE listener and when this is triggered, remove the bitmap.
public function Main() {
addEventListener(starling.events.Event.ADDED_TO_STAGE, onAdded);
}
private function onAdded ( e:starling.events.Event ):void {
StartUp._splash.parent.removeChild(StartUp._splash);
StartUp._splash = null;
}
In the example above the root document class is called 'StartUp'.
As described by docs there is Default.png used as splash screen in iOS.