continue playing music when app closes - c#

I am developing an app in wp7 and in some part.
I start a mediaelement to play my music file from isolated storage, with available functions(play, pause, next, previous, seek) and all goes perfect!
Now i want to make the app continue playing on user-exit or page-unload or something like that when mediaelement already playing!
Notice in the abobe try the
list.playlist: is a list with audiotracks
num_input: is the number of music file in list that will play, (get: from mediaelement)
time_input: is the timespan from mediaelement before stop, (set: backgroundaudioplayer to start)
play: is boolean variable, true if mediaelement plays
Stop(): is function that stops mediaelement from playing
Thats i am trying is:
private void PhoneApplicationPage_Unloaded(object sender, RoutedEventArgs e)
{
if (play == true)
{
TimeSpan time_input = med.Position;
Stop();
BackgroundAudioPlayer.Instance.Close();
BackgroundAudioPlayer.Instance.Track = list.playlist[num_input];
BackgroundAudioPlayer.Instance.Position = time_input;
if (PlayState.Playing == BackgroundAudioPlayer.Instance.PlayerState) { BackgroundAudioPlayer.Instance.Pause(); }
else { BackgroundAudioPlayer.Instance.Play(); }
}
}
void Instance_PlayStateChanged(object sender, EventArgs e)
{
switch (BackgroundAudioPlayer.Instance.PlayerState)
{
case PlayState.Playing:
break;
case PlayState.Paused:
case PlayState.Stopped:
break;
}
}
The problem is that when the app page-unload (not on user exit, the first problem)
the backgroundaudioplayer gets the name and the EnabledControls and all staff but it isn't playing even I press the play button(so buttons not working, second problem)!
Also i want to control the list of my app beside that player(previous, next, play, pause) even the app is closed!
All the songs are located in isolated and i have the song-name and file-name in database. The audio track looks like:
AudioTrack audiotrack1 = new AudioTrack(new Uri(emp.EmployeeFile + ".mp3", UriKind.Relative), emp.EmployeeName, null, null, null, null, EnabledPlayerControls.All);
Thanks!

Implementing background audio requires more work. See this article for a walkthrough: http://msdn.microsoft.com/EN-US/library/windowsphone/develop/hh202978(v=vs.105).aspx
Beware the agent lives in another process, I'm not sure whether SqlCe supports concurrent access to the same database from different processes. IMO the best way to communicate with the background agent is the isolated storage file (e.g. the playlist) guarded by the named System.Threading.Mutex.

Related

How can I use sound effect in C# console app?

I´m doing this small RPG game in the C# console app, and I wanted to add some background music and effects when choosing menu options.
What I noticed was that I wasn´t able to do anything when the background music started to play. I thought of threading, but this is completly new to me (started to learn C# 6 weeks ago).
What I managed to do was starting a new thread and play the sounds
static Thread backgroundMusic = new Thread(() =>
{
using (var audioFile = new AudioFileReader(AppDomain.CurrentDomain.BaseDirectory + "\\menu.mp3"))
using (var outputDevice = new WaveOutEvent())
{
backgroundMusic.IsBackground = true;
outputDevice.Init(audioFile);
outputDevice.Play();
while (true)
{
Thread.Sleep(1);
}
}
});
And then for the sound effect I do...
static Thread click = new Thread(() =>
{
using (var audioFile = new AudioFileReader(AppDomain.CurrentDomain.BaseDirectory + "\\click.mp3"))
using (var outputDevice = new WaveOutEvent())
{
click.IsBackground = true;
outputDevice.Init(audioFile);
outputDevice.Play();
while (true)
{
Thread.Sleep(1);
}
}
});
I start these with
click.Start();
backgroundMusic.Start();
Ok so far so good. It plays the background music and it plays the sound effect, but only one time. Can I reuse the thread in some way to play the click sound again when another option is chosen?
And can I abort sound in some way? I might want different music when you play the game and in the menus.
tried backgroundMusic.Abort(); but then I got this:
System.PlatformNotSupportedException: 'Thread abort is not supported on this platform.'
And i can not restart a thread once I´ve started it one time. I tried with
backgroundMusic.Start();
I´ve been checking out forums but all seems to cover windows forms, and not be working with console app.
https://learn.microsoft.com/en-us/dotnet/api/system.threading.thread?view=net-5.0
I´ve also checked out the documentation... but honestly I think the documentation at microsoft is NOT for beginners. I find it very hard to understand.
I´ve might have been doing it all wrong, so don´t be hard on me, but please come with suggestions how I can improve.
So I want:
Background music playing and looping
Click sound every time you choose a menu option
I have:
Background music playing once (til the end of the file)
Click sound on the first menu option, there after it throws an exception (see above)
You should never, ever use Thread.Abort(). It just stops the thread in an "evil" way - by throwing an exception, and you never know what side effects that will have.
You need CancellationToken. Check out this article: https://learn.microsoft.com/en-us/dotnet/standard/threading/cancellation-in-managed-threads

How to play background music in C# Form FROM properties.resources simultaneously with other sounds

I'm new to C# and I'm making a mini-game. Playing sound effects is no problem, I can just use the System.Media.SoundPlayer class object to play a wav file streaming from, for example Properties.Resources.attack.wav, this is good but the background music will stop after I play the sound effect. Yes, I know there's Windows Media Player, but that uses URI, which I can't seem to add the resources directory there. I don't want to use local directory like #"D:\MyGame\backgroundmusic.wav" because I want to send it to a friend and can still hear the music. Is there any class or external sdk's that allow sound to be played simultaneously with other sounds FROM Properties.Resources? If none, what is the URI of the Resources folder inside a solution? Any help or advice would be awesome! Thank you.
edit: I already opened those links and tried them all several times. My main question is "How to play sound FROM the Resources Folder of the solution without other sounds interrupting it"
This is the concept:
private void Form_Load(object sender, EventArgs e)
{
var player = new System.Windows.Media.MediaPlayer();
player.Open(Properties.Resources.sfx_background);
player.Play();
}
private void attack()
{
SoundPlayer p1 = new SoundPlayer();
p1.Stream = Properties.Resources.sfx_sword;
p1.Play();
}
Where p1 plays synchronous with player, in which player gets the sound file from the Resources of the solution, not from a local storage of a computer.

c# WindowsMediaPlayer End of Audio

I am playing an Audio use Windows Media Player in c# WinForms. I want to display a message at the end of the audio play back.
I have a separate Audio class for playing audio and in the play method I have written:
Player = new WMPLib.WindowsMediaPlayer();
public static void play()
{
Player.controls.play();
Player.PlayStateChange += new WMPLib._WMPOCXEvents_PlayStateChangeEventHandler(Player_PlayStateChange);
}
private void Player_PlayStateChange(int NewState)
{
if ((WMPLib.WMPPlayState)NewState == WMPLib.WMPPlayState.wmppsStopped)
isComplete=true;
}
public static boolean hasCompleted()
{
return isComplete;
}
here isComplete is a boolean variable initialized to false
In my form, the code for my play button is:
//Play my audio
while(!hasCompleted());
//display message
The problem is that when i click the play button, my application goes into an infinite loop.
However when i do this:
while(!hasCompleted())
MessageBox.Show("Playing");
//display message
It works fine.
Why is this happening?
I dont want to display a message while it's playing.
I tried using:
Player.currentMedia.duration
and duration string property for a timer or Thread.sleep application but the value returned by both is always 0.
I also tried giving a delay of 1-2 seconds before calling the duration property but this doesn't work as some of my audio tracks are just 2 seconds long.
It is not the best way to do so since you are in a busy waiting situation which waste a lot of CPU cycles and may not work as you wish. I would recommend you to use "Event". Here you can find a very basic example:
http://www.codeproject.com/Articles/11541/The-Simplest-C-Events-Example-Imaginable
http://msdn.microsoft.com/en-us/library/aa645739(v=vs.71).aspx

Background audio not working in windows 8 store / metro app

I've tried setting background audio through both a mediaElement in XAML
<MediaElement x:Name="MyAudio" Source="Assets/Sound.mp3" AudioCategory="BackgroundCapableMedia" AutoPlay="False" />
And programmatically
async void setUpAudio()
{
var package = Windows.ApplicationModel.Package.Current;
var installedLocation = package.InstalledLocation;
var storageFile = await installedLocation.GetFileAsync("Assets\\Sound.mp3");
if (storageFile != null)
{
var stream = await storageFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
_soundEffect = new MediaElement();
_soundEffect.AudioCategory = AudioCategory.BackgroundCapableMedia;
_soundEffect.AutoPlay = false;
_soundEffect.SetSource(stream, storageFile.ContentType);
}
}
// and later...
_soundEffect.Play();
But neither works for me. As soon as I minimise the app the music fades out
akton replied to a similar question with this excellent answer
It wasn't easy to find initially as it doesn't use 'audio' in the title and I wasn't playing music. It's an excellent, comprehensive answer, the likes of which I love to see on StackExchange. It also mentions a few things other answers to similar questions had failed to point out. In brief
You need to handle the MediaControl events PlayPressed, PausePressed, PlayPausedTogglePressed and StopPressed, even if you have no buttons. EDIT: these events are required by Windows 8 app certification, make sure they actually work.
Add audio to the list of support background tasks in the applications manifest [see aktons answer for more detail]
However, in implementing this solution I did come across what I can only assume is a bug. I've built a kitchen timer within a UserControl. It plays an optional ticking sound as it counts down and then buzzes when elapsed. However, if the ticking sound is turned off before the timer is set, the buzz sound will not play. It seems that a Windows 8 app needs to play a sound before being minimised in order for background audio to work. To fix this, I created a silent audio file which is 1 second in duration. This file plays whether the ticking is on or off. It's a weird hack, and I hope I can figure out a better solution, but for now its all I can think of.

mediaelement keep playing after lock

I have a medialement with a url-source which streams a radio station. Everything works fine and music plays as expected! When I press the shutdown button and the phone locks, the streaming stops. How can I fix that? Even if I press the "flag" button, I see my main screen but the music stops :/
thanks in advance
You must use the BackgroundAudioPlayer to accomplish this.
See this msdn article for more info and my post explaining some gotchas of the BackgroundAudioPlayer
Taking the sample from the msdn link. I changed the PlayTrack method to:
private void PlayTrack(BackgroundAudioPlayer player)
{
var track = new AudioTrack(
new Uri("http://m1.onweb.gr/1055rock"),
"Online",
"Music",
string.Empty,
null,
string.Empty,
EnabledPlayerControls.Pause);
if (player != null)
{
player.Track = track;
}
}
And I get the errors noted below. How are you trying to start the player?

Categories

Resources