Resume music after exit app on windows phone - visual-studio-2012

i`m using mediaElement to play background music in my app. And that works just fine.
Problem is when the user minimize the application. When the application resume there is no sound... I can play other sounds in my application but cant play that background music any more.
First i have this code to stop all background music at first time app open:
if (Microsoft.Xna.Framework.Media.MediaPlayer.State == MediaState.Playing)
{
Microsoft.Xna.Framework.Media.MediaPlayer.Pause();
FrameworkDispatcher.Update();
}
xaml code of that mediaElement
<MediaElement AutoPlay="True" Source="/Dodaci/pozadina.mp3" x:Name="muzika_pozadina" MediaEnded="pustiPonovo" Loaded="pustiPonovo" />
and the cs code
private void pustiPonovo(object sender, RoutedEventArgs e)
{
muzika_pozadina.Play();
}
sound is about 300kb size.
So, how can i resume that sound playing after the user resume the application?

When your App is put into Dormant State (when you hit Start buton for example), the MediaElement is stopped. Then after you return to your App (and it wasn't Tombstoned), the Page is not Initialized once again, which means that your MediaElement is not loaded once again, so your Music doesn't start once again.
It depends on your purpose and code how it can be returned. In very simple example when you don't need to remember music last position you can just set source of your MediaElement once again in OnNavigatedTo() event:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (e.NavigationMode == NavigationMode.Back)
muzika_pozadina.Source = new Uri("/Dodaci/pozadina.mp3", UriKind.RelativeOrAbsolute);
}
As you have set your MediaElement.AutoPlay to true - it should start automatically (because of that you probably also don't need your Loaded event pustiPonovo).
In more complicated cases you can take an advantage of Activation and Deactivation events of your App - returning to MediaElement from Dormant/Tombstoned case is well explained here in the article.
You should also read about Fast App Resume in case User decides to return to your App by Tile instead of Launchers-Choosers.
I haven't tried above code, but hopefully it will do the job.

Related

How to prevent the screen from locking on UWP 10

I want to prevent the phone to lock if the user didnt interact with the phone for some time.
In win8 phone development i used the PhoneApplicationService.UserIdleDetectionMode Property. Unfortunately i cannot find anything alike for win 10 universal app.
Any suggestions?
Simple Answer
DisplayRequest class
var displayRequest = new DisplayRequest();
displayRequest.RequestActive(); //to request keep display on
displayRequest.RequestRelease(); //to release request of keep display on
Detailed Answer
Using display requests to keep the display on consumes a lot of power. Use these guidelines for best app behavior when using display requests.
Use display requests only when required, that is, times when no user input is expected but the display should remain on. For example, during full screen presentations or when the user is reading an e-book.
Release each display request as soon as it is no longer required.
Release all display requests when the app is suspended. If the display is still required to remain on, the app can create a new display request when it is reactivated.
To Request keep display on
private void Activate_Click(object sender, RoutedEventArgs e)
{
if (g_DisplayRequest == null)
{
g_DisplayRequest = new DisplayRequest();
}
if (g_DisplayRequest != null)
{
// This call activates a display-required request. If successful,
// the screen is guaranteed not to turn off automatically due to user inactivity.
g_DisplayRequest.RequestActive();
drCount += 1;
}
}
To release request of keep display on
private void Release_Click(object sender, RoutedEventArgs e)
{
// This call de-activates the display-required request. If successful, the screen
// might be turned off automatically due to a user inactivity, depending on the
// power policy settings of the system. The requestRelease method throws an exception
// if it is called before a successful requestActive call on this object.
if (g_DisplayRequest != null)
{
g_DisplayRequest.RequestRelease();
drCount -= 1;
}
}
References - Prevent the screen from locking on Universal Windows Platform
Hope it help someone!!
You want the DisplayRequest class in Windows 10.

Getting a sound trigger to work

I don't understand why my sound trigger is not working. I have created a GameObject and added an Audio Source to it (on Audio Source I have the Play On Wake and Loop checked. Then I added a Sphere Collider (I have the Is Trigger checked). Finally I added my script and added the sound clips into the inspector. Unity also says that: "There are 2 audio listeners in the scene." I have pretty much unchecked all the audio listeners and it still says it, what am I doing wrong?
Here is a look at my code:
#pragma strict
var WalkAudio:AudioClip;
var OutCry:AudioClip;
function Update (){
var Audio= gameObject.GetComponent(AudioSource);
if(Input.GetButton("Horizontal") || Input.GetButton("Vertical"))
{
Audio.Play();
}
else
{
Audio.Pause();
}
}
function OnControllerColliderHit (hit : ControllerColliderHit)
{
var Audio= gameObject.GetComponent(AudioSource);
if (hit.gameObject.tag == "templeFloor")
{
var groundType = 1;
print("Temple");
Audio.clip=OutCry;
}
else{
Audio.clip=WalkAudio;
}
}
As you said:
I have pretty much unchecked all the audio listeners
The component AudioListener attached to the Main Camera must be enabled. Probably you have used LoadLevelAdditive so you have two camera and two AudioListener components, one on each of them. Please make sure this additive camera and any other gameObject should have this component disabled.
Also at runtime, you can search which component(s) have AudioListener component attached using this in the Hierarchy window search bar.
t:AudioListener
This should help you out. Also double check using Debug.Log that OnControllerColliderHit function calls and Audio.clip is not null after assignment. Also is it necessary to play sound in Update ?
Also, you should move this line from Update to Start function instead, due to performance cost:
var Audio= gameObject.GetComponent(AudioSource);
and use this Audio variable throughout your script.

Windows Phone Background Audio current track is resetting

I am developing an WP8 app witch uses background audio agent. i have taken the background audio players sample. i have added the following method to audioplayer.cs
public static void playTrackAtIndex(int index)
{
currentTrackNumber = index;
BackgroundAudioPlayer.Instance.Track = _playList[currentTrackNumber];
}
after it is called the song at the specified index (let's say 5) will play, but when i pres skipnext in my ap or in the UVC currentTrackNumber is 0!. Please, any help is apreciated
it turns out you don't have any control over the lifecycle of the background audio agent, so at any time it may be killed and then instanced by the foreground app or the Background audio player. So the only whey to make the agent work is to design it as it will always be killed and instanced (use sql lite or files with a lock, or always check what backgoundaudioplayer is playing when your agent is called, so your agent will "remember" where it was before getting killed

How do I turn the mic off?

I'm using navigator.getUserMedia for a voice memo app. It works like a charm.
When I quit the app, the microphone stays on (there is a notification "Audio Memos Mic is on" and the red dot remains in the status bar. It stays on even after the phone went to sleep for fifteen minutes.
How do I turn the mic off when I quit the app. I've check the mediastream API but couldn't find any reference.
Have you tried the stop method: https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder.stop
There may be a better way but I got the light to turn off on minimized apps by using code similar to:
mediaRecorder was a ref to the MediaRecorder object tied to the stream. You can also just call stop on the stream returned by the GetUserMedia call. Also had to call setup on init of app as well.
function handleVisibilityChange() {
if (document.hidden) {
console.log("hidden");
if( gumStream ){
gumStream.stop();
mediaRecorder = null;
}
} else {
console.log("visible");
setup(); //Call getUserMedia
}
}
document.addEventListener("visibilitychange", handleVisibilityChange, false);

Notification sound not playing in J2ME

I am working on a J2ME application.
I am using Nokia 6131 NFC phone. I am using NetBeans IDE.
I have 4 forms and I am playing some notification sounds for the user while filling the form.
The problem is sound goes off suddenly after 3 to 4 min and the only solution is to exit the application and again open it.
My Code
public void playSoundOK()
{
try
{
InputStream is = getClass().getResourceAsStream("/OK.wav");
Player player = Manager.createPlayer(is,"audio/X-wav");
player.realize();
player.prefetch();
player.start();
}
catch(Exception e)
{
e.printStackTrace();
}
}
Exception
at com.nokia.mid.impl.isa.mmedia.audio.AudioOutImpl.openSession(AudioOutImpl.java:206)
at com.nokia.mid.impl.isa.mmedia.MediaOut.openDataSession(MediaOut.java:282)
at com.nokia.mid.impl.isa.mmedia.MediaPlayer.doPrefetch(MediaPlayer.java:155)
at com.nokia.mid.impl.isa.amms.audio.AdvancedSampledPlayer.doPrefetch(+4)
at com.nokia.mid.impl.isa.mmedia.BasicPlayer.prefetch(BasicPlayer.java:409)
at org.ird.epi.ui.UtilityClass.playSoundOK(UtilityClass.java:139)
at org.ird.epi.ui.EnrollmentForm.targetDetected(+695)
at javax.microedition.contactless.DiscoveryManager.notifyTargetListeners(DiscoveryManager.java : 700)
at javax.microedition.contactless.DiscoveryManager.access$1200(DiscoveryManager.java:103)
at javax.microedition.contactless.DiscoveryManager$Discoverer.notifyIndication(DiscoveryManager.java:882)
at com.nokia.mid.impl.isa.io.protocol.external.nfc.isi.NFCConnectionHandler$IndicationNotifier.run(+67) javax.microedition.media.MediaException: AUD
I would advise you to split NFC and audio playback into 2 different threads.
It is typically a bad idea to call a method that should take some time to complete (like prefetch) from inside an API callback (like targetDetected) because it makes you rely on a particularly robust kind of internal threading model that may not actually exist in your phone's implementation of MIDP.
You should have one thread whose sole purpose is to play the sounds that your application can emit. Use the NFC callback to send a non-blocking command to play a sound (typically using synchronized access to a queue of commands). The audio playback thread can decide to ignore commands if they were issued at a time when it was busy playing a sound (no point in notifying the users of multiple simultaneous NFC contacts)
You should close your player. Add the following code to your method:
PlayerListener listener = new PlayerListener() {
public void playerUpdate(Player player, String event, Object eventData) {
if (PlayerListener.END_OF_MEDIA.equals(event)) {
player.close();
}
}
};
player.addPlayerListener(listener);

Resources