In my WP7 gaming app , I want two music files to run. One is the background music and another follows the user action , say, user kills the enemy. I am using MediaElement to do this. I am facing two issues.
1) How to loop background music ?
2) As soon as second music starts, the first music stops and does not start back when the second music stops. I do not want background music to stop, they should overlap. How to do this ?
I am using silverlight.
XAML
<MediaElement x:Name="stroke" AutoPlay="False" />
<MediaElement x:Name="bmusic" AutoPlay="True" />
C#
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
var settings = IsolatedStorageSettings.ApplicationSettings;
if (settings.Contains("bm"))
{
string hy=(string)settings["bm"];
//check if user has disabled music play
if (hy == "1")
{
bmplay = 1;
// play background music
bmusic.Source = new Uri("bmusic.mp3", UriKind.Relative);
bmusic.Play();
}
else
{
bmplay = 0;
}
}
else
{
bmplay = 1;
// play b music
bmusic.Source = new Uri("bmusic.mp3", UriKind.Relative);
bmusic.Play();
}
if (NavigationContext.QueryString.TryGetValue("msg", out msg))
{
// textBox1.Text +=" "+ msg;
find_move();
}
}
For repeating music you can use this:
Song s = Song.FromUri("song", new Uri(path));
FrameworkDispatcher.Update();
MediaPlayer.IsRepeating = repeat;
MediaPlayer.Play(s);
And try to use SoundEffect for sounds, they can be played simultaneously with background music.
Sound effect in windows phone 7
Related
I have UWP(Universal Windows Platform) Application and I want to add shoutcast player, but can't find anything how to do that.
I have Button which should start/stop playing music and volume slider.
I found element in xaml such as MediaElement but when I'm trying to use it like that:
private async void StartPlayer()
{
var result = await AdaptiveMediaSource.CreateFromUriAsync(new Uri("http://camon22.sxcore.net:"+Port, UriKind.Absolute));
if (result.Status == AdaptiveMediaSourceCreationStatus.Success)
{
var astream = result.MediaSource;
Media.SetMediaStreamSource(astream);
}
else
{
var dialog = new MessageDialog("Result Status Wrong!\n"+result.Status);
await dialog.ShowAsync();
}
}
I got UnsupportedManifestContestType Status.
Anybody knows how to play radio in UWP application?
I am learning how to work with xAudio2. Made a simple application Windows 8 in Visual Studio 2012 Express For Windows 8.
Simple xAudio2 player class:
public class SoundEffect
{
readonly XAudio2 _xaudio;
readonly WaveFormat _waveFormat;
readonly AudioBuffer _buffer;
readonly SoundStream _soundstream;
SourceVoice sourceVoice;
public SoundEffect(string soundFxPath)
{
_xaudio = new XAudio2();
var masteringsound = new MasteringVoice(_xaudio);
var nativefilestream = new NativeFileStream(
soundFxPath,
NativeFileMode.Open,
NativeFileAccess.Read,
NativeFileShare.Read);
_soundstream = new SoundStream(nativefilestream);
_waveFormat = _soundstream.Format;
_buffer = new AudioBuffer
{
Stream = _soundstream.ToDataStream(),
AudioBytes = (int)_soundstream.Length,
Flags = BufferFlags.EndOfStream
};
//sourceVoice = null;
}
public void Play()
{
sourceVoice = new SourceVoice(_xaudio, _waveFormat, true);
if (sourceVoice != null)
{
sourceVoice.FlushSourceBuffers();
sourceVoice.SubmitSourceBuffer(_buffer, _soundstream.DecodedPacketsInfo);
sourceVoice.Start();
}
}
public void Stop()
{
sourceVoice.Stop();
}
}
And Xaml:
<Border Background="Gray" MinHeight="150" MinWidth="150" Margin="10,10,0,0" x:Name="A" PointerPressed="btnAPointerPressed" PointerReleased="btnAPointerReleased" />
and:
private SoundEffect shotEffect = new SoundEffect(#"sounds\mywav.wav");
private void btnAPointerPressed(object sender, PointerRoutedEventArgs e)
{
bool _hasCapture = ((Border)sender).CapturePointer(e.Pointer);
shotEffect.Play();
}
private void btnAPointerReleased(object sender, PointerRoutedEventArgs e)
{
((Border)sender).ReleasePointerCapture(e.Pointer);
shotEffect.Stop();
}
Tested in Windows 8 Simulator.
If I press one finger, then everything is fine.
When I click on the button - the sound plays when I let go of your finger - the sound stops.
If I click with two fingers and let go of both fingers, the sound continues to play. And the result is aliasing.
Called two events: btnAPointerPressed and two events: btnAPointerReleased but the sound continues to play. As if the audio stream freezes and continues to play. As if the audio stream freezes and continues to play.
I want to understand the problem haudio2? or I do not properly done something?
When you call Play() again - the previous SourceVoice gets replaced with a new one in your SoundEffect, but you never stop the old one. You should create a new SourceVoice with each touch, but keep them all associated with the pointer IDs so that we can stop each of them when the associated pointers are released.
Hi i'm trying to play a specifc song for example if i have a list with 100 songs i want to play the song #20
to do this i use the following code
private void playSong(int n)
{
IsolatedStorageSettings.ApplicationSettings["currentSong"] = n;
if (BackgroundAudioPlayer.Instance.PlayerState == PlayState.Playing)
{
BackgroundAudioPlayer.Instance.Close();
BackgroundAudioPlayer.Instance.Play();
}
else
BackgroundAudioPlayer.Instance.Play();
}
And then in my AudioPlayer.cs i get the song
//get the song
currentSong = (int)IsolatedStorageSettings.ApplicationSettings["currentSong"];
It works fine but it takes too much time to load the song.
so please is there any other way to do this?
thanks.
I have an app that runs background music at the application level so that the music doesn't stop when the user navigates through pages. However, I also make use of a VideoBrush. As I found out, I cannot have the two running at the same time as the VideoBrush will crash when setting its source.
I found that if I set the source of the MediaElement to null when the user attempts to use the VideoBrush, that everything works. Sure the music stops, much to my chagrin, but no error happens.
However, when the user taps away from the VideoBrush, I am trying to make the music start back up (beginning is fine) to no avail. Simply put, I am having trouble getting the music to start up again.
Here is my code:
App.xaml
<Application.Resources>
<MediaElement x:Key="GlobalMedia" Source="minutelongsong.mp3"
MediaEnded="MediaElement_MediaEnded" Visibility="Collapsed" />
</Application.Resources>
App.xaml.cs
public static MediaElement GlobalMediaElement
{
get { return Current.Resources["GlobalMedia"] as MediaElement; }
}
private void Application_Launching(object sender, LaunchingEventArgs e)
{
var AppMediaElement = App.GlobalMediaElement;
AppMediaElement.Position = TimeSpan.Zero;
AppMediaElement.Play();
}
private void MediaElement_MediaEnded(object sender, RoutedEventArgs e)
{
var AppMediaElement = App.GlobalMediaElement;
AppMediaElement.Position = TimeSpan.Zero;
AppMediaElement.Play();
}
And now the page that is making use of the VideoBrush.
MainPage.xaml
<Canvas x:Name="viewfinderCanvas" Width="480" Height="800" HorizontalAlignment="Center" VerticalAlignment="Center" Visibility="Collapsed">
<Canvas.Background>
<VideoBrush x:Name="videoBrush" Stretch="Fill">
<VideoBrush.RelativeTransform>
<CompositeTransform x:Name="previewTransform"
CenterX=".5"
CenterY=".5" />
</VideoBrush.RelativeTransform>
</VideoBrush>
</Canvas.Background>
</Canvas>
MainPage.xaml.cs
private void Button_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var AppMediaElement = App.GlobalMediaElement;
AppMediaElement.Pause();
AppMediaElement.Stop();
AppMediaElement.Source = null; //set it to null to allow the cam to be set.
if ((PhotoCamera.IsCameraTypeSupported(CameraType.Primary)))
{
viewfinderCanvas.Visibility = Visibility.Visible;
cam = new PhotoCamera(CameraType.Primary);
if (Orientation == PageOrientation.PortraitUp || Orientation == PageOrientation.PortraitDown || Orientation == PageOrientation.Portrait)
{
videoBrush.RelativeTransform = new CompositeTransform() { CenterX = 0.5, CenterY = 0.5, Rotation = 90 };
}
videoBrush.SetSource(cam);
}
When the user exits out of the camera VideoBrush by hitting an on screen button, this code is fired. It disposes the cam, and tries to get the music playing again if the user allows the music. However the music will not play, even with this code.
private void zoomout_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (cam != null)
{
cam.Dispose();
}
viewfinderCanvas.Visibility = Visibility.Collapsed;
if (allowingamemusic == true)
{
var AppMediaElement = App.Current.Resources["GlobalMedia"] as MediaElement;
AppMediaElement.Source = new Uri("minutelongsong.mp3", UriKind.RelativeOrAbsolute);
AppMediaElement.Position = TimeSpan.Zero;
AppMediaElement.Play(); //despite this here, it will not play. No error thrown.
}
}
I switch back and forth between capturing an image and audio in the same page on my phone app.
You were very close, but you also have to set the videoBrush source to something else or it won't let go of the resources.
So when you want to use the MediaElement, then first dispose of the camera like this:
cam.Dispose();
viewfinderBrush.SetSource(new MediaElement()); //so it will let go of cam
cam = null;
//now set source for MediaElemet and do whatever
And when you use the camera again:
mediaElement.Stop();
mediaElement.Source = null; //or else setting the source for the video brush will fail
//now set source for videoBrush and do whatever
Old question, but hopefully this will help someone... it took me a few tries to figure it out.
After writing this last night, and finally testing it this morning, I see what may have happened but am still having the problem of the music not replaying once it's stopped.
MediaElement.MediaFailed was for the entire time being called. I found out that it was calling: AG_E_NETWORK_ERROR. This error is thrown when Zune is running and my device is USB connected to the same computer.
It was suggested that I deploy my app to my phone, close zune, and disconnect the USB. I tried this, and the music still did not play once I tried to replay it. This also happened on the emulator too.
The same AG_E_NETWORK_ERROR is still being thrown.
Since then, I have given up on this as I spent a few hours not finding out how to make this happen. So, I have since gone with the MediaPlayer class and will be using that instead.
------ If anyone solves this problem, I will give you the checkmark for a correct answer.
I have some Windows Phone 7 code that starts playing a sound using SoundEffect.FromStream. I am using this instead of a normal media object as I need multiple audio clips to be on the one page.
However, based on certain external events I want to stop a particular sound playing. As sounds played via Open Stream are "play and forget" I cannot work out how to reference this playing sound and stop it.
public void PlaySoundCircus(object sender, RoutedEventArgs e)
{
if (audioPlaying == false)
{
using (var stream = TitleContainer.OpenStream("circus.wav"))
{
var effect = SoundEffect.FromStream(stream);
FrameworkDispatcher.Update();
effect.Play();
}
audioPlaying = true;
}
}
You need to create a SoundEffectInstance which will store a reference to your SoundEffect. The SoundEffectInstance has a Stop method which can be called.
SoundEffectInstance seiCircus;
using (var stream = TitleContainer.OpenStream("circus.wav"))
{
var effect = SoundEffect.FromStream(stream);
//create the instance
seiCircus = effect.CreateInstance();
FrameworkDispatcher.Update();
//play sound via the instance
seiCircus.Play();
}
//some event called to stop sound
seiCircus.Stop();