How to play songs in repeat mode in an UWP app - c#

I have created a UWP app to play certain tracks in the background. Basically by following this link: https://blogs.windows.com/buildingapps/2016/01/13/the-basics-of-background-audio/ .
I want to set the repeat count for certain songs, so if a song has repeat count 10, that song is meant to be repeated 10 times before moving on to the next song in the playlist.
On the Windows phone 8.0 platform, the AudioPlayerAgent had the following event which indicated that the play state has changed. It was easy to override that event and add custom logic to repeat songs.
protected override void OnPlayStateChanged(BackgroundAudioPlayer player, AudioTrack track, PlayState playState)
{
switch (playState)
{
case PlayState.TrackEnded:
// keep repeating the same track
player.Position = new TimeSpan(0, 0, (int)0);
// add custom logic here..
break;
}
NotifyComplete();
}
What would be an equivalent event in the UWP platform?
So far I have tried the following events on the UWP platform, but to no avail..
BackgroundMediaPlayer.Current.CurrentStateChanged += Current_CurrentStateChanged;
BackgroundMediaPlayer.Current.MediaEnded += Current_MediaEnded;
BackgroundMediaPlayer.Current.MediaOpened += Current_MediaOpened;

With Windows 10, version 1607, a new single-process model has been introduced that greatly simplifies the process of enabling background audio.
Media continues to play when your app moves from the foreground to the background. This means that even after the user has minimized your app, returned to the home screen, or has navigated away from your app in some other way, your app can continue to play audio.
Starting with Windows 10, version 1607,the recommended best practice for playing media is to use the MediaPlayer class instead of MediaElement
Play a media file with MediaPlayer
_mediaPlayer = new MediaPlayer();
_mediaPlayer.Source = MediaSource.CreateFromUri(new Uri("ms-appx:///Assets/example_video.mkv"));
_mediaPlayer.Play();
MSDN: Play media in the background
Now your app can manage the playlist or loop settings and use the media player instance to call Play method again.

Related

Controlling Sounds in audio in multiple forms

I want to play a playlist in the resources folder for a windows forms project I'm working on (wav or mp3). The application will be completely offline. (actually a game project)
What I want to do is this:
I need to be able to stop or convert a music that I created in one form to another sound file, depending on the situation.
In this case, I couldn't figure out how to write a code block. There are many examples that describe how we can pause and start the music on single form, but I have not come across an example that covers the whole project and can be intervened from different forms.
I'm not sure if I explained exactly what I wanted to ask, but I can give an example as follows. Let's say I created 3 forms.
1st form and 2nd form game menus.
In these menus, the same music should continue to play.
But when I reach the 3rd form, this music should be cut and replaced with in-game music.
What I want to ask is: How can I control the music I created in form 1, in form 2 or form 3?
The reason I don't use the soundplayer class is because I have to play multiple sounds at once.
i.e., somehow I need to make the music player "static" so that I can control it from all forms, but I couldn't find the way around it.
var importer = new RawSourceWaveStream(Properties.Resources.sound, new WaveFormat());
var soundFx = new WaveOut();
soundFx.Init(importer);
soundFx.Play();
For example, in this way, I start playing the music in the form1. I need to give the command to change this music in the form3, but somehow I cannot reach the "soundfx" object that I defined there because I cannot make this process static.
I think that your intuition is valid. It is probably not the best way, but I inffer that it is a way that you would manage to do.
Have a public static class, that holds a private (or public) instance of you sound player. Have public static methods of the different things that you want to do with the audio player.
Control that class from all forms.
Since this is your intuition. I am curious of what have you so far in this way?
Anyhow, I have a few questions.
When you say "convert" the music, what do you mean?
What do you mean that you couldnt find a way around it?
Can you add some code of how you are controlling the sounds? With some code, people will be able to better support you.
It is recommended that you use MediaPlayer. From your description, MediaPlayer can better meet your needs. Compared with SoundPlayer, MediaPlayer has the following characteristics:
Multiple sounds can be played at the same time (create multiple MediaPlayer objects);
You can adjust the volume (Volume property);
You can use Play, Pause, Stop and other methods to control;
You can set the IsMuted property to True to achieve mute;
You can use the Balance property to adjust the balance of the left and right speakers;
The speed of audio playback can be controlled through the SpeedRatio property;
The length of the audio can be obtained through the NaturalDuration property, and the current playback progress can be obtained through the Position property;
Seek can be performed through the Position property;
Use MediaPlayer to play audio files as follows:
MediaPlayer player = new MediaPlayer();
player.Open(new Uri("BLOW.WAV", UriKind.Relative));
player. Play();
A MediaPlayer object can only play one file at a time. And the file is played asynchronously, you can also call Close to release the file.
For details, please refer to https://learn.microsoft.com/en-us/dotnet/api/system.windows.media.mediaplayer?view=windowsdesktop-7.0
When using it in VS, you need to perform the following steps first:
This way you can find MediaPlayer in the toolbar.
If you still have any questions please speak up.

Windows Media Player - Hide player after it is done playing

I am creating a game, I want to display a short tutorial video to the player after they have registered. I am using a windows media player control. I don't know how to hide the video after it has finished playing ?
I tried using the following:
WMP.Ctlcontrols.play();
Thread.Sleep(3000);
WMP.Dispose();
I am using the disposing as a way to close down the video. I tried hide and close as well but they close the video before it's finished playing, after 3 seconds.
You can handle PlayStateChange event of control and check if e.newState==1, it means the playing has been stopped. Then you can hide the control.
void axWindowsMediaPlayer1_PlayStateChange(object sender,
AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if(e.newState== 1) // Stopped
axWindowsMediaPlayer1.Hide();
}

Display Current Video in Windows Phone 8 using AudioVideoCaptureDevice?

I've managed to setup code for a Windows Phone 8 Application that initializes and can start/stop recording video using an AudioVideoCaptureDevice. (saves it to an IRandomAccessStream)
//Initialize Camera Recording
Windows.Foundation.Size resolution = new Windows.Foundation.Size(640, 480);
captureDevice = await AudioVideoCaptureDevice.OpenAsync(CameraSensorLocation.Back, resolution);
captureDevice.VideoEncodingFormat = CameraCaptureVideoFormat.H264;
captureDevice.AudioEncodingFormat = CameraCaptureAudioFormat.Aac;
captureDevice.RecordingFailed += captureDevice_RecordingFailed;
However, I cannot figure out how to hook this recording up to a VideoBrush to display the recording to the user. I want the user to be able to see the video they are recording as it is happening...
I know there is a tutorial that shows how to do this using the old APIs for Windows Phone 7 (CaptureSource, VideoDevice, etc.) but I specifically need to use the AudioVideoCaptureDevice to record. Anyone know how to display this video on screen?
Well, I was able to solve my problem.
Apparently there is a library in Microsoft.Devices that contains extensions for the VideoBrush class.
Therefore, in order to set the videobrush source to an AudioVideoCaptureDevice, you must first have:
using Microsoft.Devices;
at the top of your class in which your using the videobrush.
Hope this is able to help someone else.
You should be able to simply use VideoBrush.SetSource(captureDevice).

Windows 8 app XNA on two monitors with different resolutions

I'm using Monogame to write an XNA game for Windows 8 app store. I'm also using a laptop hooked up to an external monitor. Naturally the resolution on my external monitor is much higher than my laptop's screen. When I drag the app from one screen to another the resolution on the view port changes.
In my constructor I'm using
_graphics = new GraphicsDeviceManager(this);
_graphics.PreferredBackBufferHeight = 768;
_graphics.PreferredBackBufferWidth = 1366;
To set my viewport resolution. This makes the app to work fine when the application runs on either monitors, however dragging the app from one monitor to another changes the resolution on the GraphicsDeviceManager. Is there anyway to prevent this change?
So I figured it out
First I wrote a method that checks to see if the port resolution on the graphic device has changed
private bool hasResolutionChanegd()
{
if ((GraphicsDevice.Viewport.Width != ScreenManager.Instance.ScreenWidth) || (GraphicsDevice.Viewport.Height != ScreenManager.Instance.ScreenHeight))
{
return true;
}
else
{
return false;
}
}
I call this method on every update
if (hasResolutionChanegd())
{
Debug.WriteLine("Resolution Change new width= " + GraphicsDevice.Viewport.Width +" new height="+ GraphicsDevice.Viewport.Height);
_graphics.PreferredBackBufferHeight = 768;
_graphics.PreferredBackBufferWidth = 1366;
_graphics.ApplyChanges();
}
This way every time the resolution changes on the Graphic Device Manager (when the user drags the app from one screen environment to another), the preferred resolution is enforced.
I get the same thing as the original poster, but with XNA, not MonoGame. When I drag the window between the two monitors, the resolution changes, but the ClientSizeChanged event is not (of course) triggered. The suggestion above to use the SizeChanged event is helpful but only for Windows8 the documentation says.
I appear to have fixed it by handling the Window.ScreenDeviceNameChanged event - I hooked it up to the same handler as the ClientSizeChanged.
I would have put this in as a comment to the original post, but I don't have enough "reputation" points for the system to let me.

How to play IMFMediaEngine background audio while SpeechSynthesizer is playing

I want to play Windows Phone 8's Speech Synthesizer while background audio is playing. But every time, I activate the Speech Synthesizer, the background audio stops playing, and resumes after the synthesizer finishes.
Any suggestions?
Thanks.
Some code snippets below:
Background Audio: using IMFMediaEngine in C++, plays successfully.
Microsoft::WRL::ComPtr<IMFMediaEngine> m_mediaEngine;
m_mediaEngine->Play();
In C# / XAML, I have a XAML page with a button, when I click on it, it plays from WP8's latest Speech classes. Plays the text.
using Windows.Phone.Speech.Synthesis;
public async void SpeakText(string text)
{
SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer();
await speechSynthesizer.SpeakTextAsync(text);
}
I tried putting the SpeakTextAsync through threads, but I guess I'm doing it all wrong, because I still can't get both audio playing at the same time.
private void bubble_Click(object sender, RoutedEventArgs e)
{
App.Manager.SpeakText("hello how are you");
// TRY 1: plays text only, background doesn't play
//new Thread(() =>
//{
// App.Manager.SpeakText(chinese);
//}).Start();
// TRY 2: plays text only, background doesn't play
//Deployment.Current.Dispatcher.BeginInvoke(() =>
//{
// App.Manager.SpeakText(chinese);
//});
// TRY 3: plays text only, background doesn't play
//ThreadPool.QueueUserWorkItem(new WaitCallback(SpeakTextProc));
}
private void SpeakTextProc(Object stateInfo)
{
App.Manager.SpeakText("Hello how are you");
}
On Windows Phone 7, I was able to get two separate audio streams using XNA but seeing how that XNA isn't supported for further development on Windows Phone 8, that's not a great solution for you good luck.

Categories

Resources