UWP, Playing sound is stop sometime - audio

in UWP application, Sometime Playing sound is stop.
await Execute.OnUIThreadAsync(async () =>
{
var element = new MediaElement();
var uri = new Uri($"ms-appx:///Assets/sound/abc.wav");
StorageFile sf = await StorageFile.GetFileFromApplicationUriAsync(uri);
var stream = await sf.OpenAsync(Windows.Storage.FileAccessMode.Read);
element.SetSource(stream, "");
element.Play();
});
I think, This UIThread job finish immediately.
but My sound file has 1 minutes length, Then,
The task was closed. then, Sound can not play by end.
How should I write to play sound ?

Refer to the following MSDN doc:Play media in the background. To support your music playing in background, you need to check the requirements from "Requirements for background audio". Actually you've mentioned that it is "sometime", so I'm not so sure whether you've already used the solution from the above doc. But if you haven't, you need to refer to that article, enable capbility and then manage both the transitioning and also notice the memory.

Related

MediaPlayerElement vs MediaElement Which one to choose?

I have gone through the answer provided here for the difference. But I need to just play notification sound for like 2 seconds as an alert. No video or any other heavy loading.
This is the notification sound I am about to play.
ms-winsoundevent:Notification.SMS
The below is for MediaPlayerElement:
MediaPlayerElement mediaPlayerElement = new MediaPlayerElement();
mediaPlayerElement.SetMediaPlayer(new Windows.Media.Playback.MediaPlayer { AudioCategory = Windows.Media.Playback.MediaPlayerAudioCategory.Alerts});
mediaPlayerElement.MediaPlayer.AudioCategory = Windows.Media.Playback.MediaPlayerAudioCategory.Alerts;
mediaPlayerElement.Source = Windows.Media.Core.MediaSource.CreateFromUri(new Uri("ms-winsoundevent:Notification.Default"));
mediaPlayerElement.AutoPlay = false;
mediaPlayerElement.MediaPlayer.Play();
The below is for MediaElement:
MediaElement mediaElement = new MediaElement();
mediaElement.AudioCategory = AudioCategory.Alerts;
mediaElement.Source = new Uri("ms-winsoundevent:Notification.Default");
mediaElement.AutoPlay = false;
mediaElement.Play();
Can I use MediaElement since its a small audio or should I only use MediaPlayerElement as it is the one prescribed by Microsoft? which one is better to use in this case?
P.S.: I need to set audio category as Alerts in order to dim any background music.
Can I use MediaElement since its a small audio or should I only use MediaPlayerElement as it is the one prescribed by Microsoft? which one is better to use in this case?
Derive from official document,
In Windows 10, build 1607 and on we recommend that you use MediaPlayerElement in place of MediaElement. MediaPlayerElement has the same functionality as MediaElement, while also enabling more advanced media playback scenarios. Additionally, all future improvements in media playback will happen in MediaPlayerElement.
And it means that the new feature will be developed base on the MediaPlayerElement, we recommend using MediaPlayerElement that could make your app has longer life.

Set Spotify playing position

I'm using the SpotifyAPI-NET on GitHub from JohnnyCrazy to play and pause songs on my Spotify desktop client. This works fine.
Now I want to change the playing position of the currently playing song. So I only want to say something like "SetPlayingPosition(64)" to play the current song from position "01:04". It seems that the SpotifyLocalAPI didn't support this feature.
To play and pause a song the API uses a message with the following format:
http://127.0.0.1:4381/remote/pause.json?pause=true&ref=&cors=&_=1520448230&oauth=oauth&csrf=csrf
I tried to find a summary of possible commands in this format, but I didn't find anything.
Is there something like http://127.0.0.1:4381/remote/seek.json... that I can use to seek to a specific position?
EDIT:
I tried to write my own method in the RemoteHandler class in the local portion of the SpotifyAPI. With this method I can set the position in the current playback.
Here's my code:
internal async Task SendPositionRequest(double playingPositionSec) //The desired playback position in seconds
{
StatusResponse status = GetNewStatus(); //Get the current status of the local desktop API
string trackUri = "spotify:track:" + status.Track.TrackResource.ParseUri().Id; //The URI of the current track
TimeSpan playingPositionTimeSpan = TimeSpan.FromSeconds(playingPositionSec);
string playingPosStr = playingPositionTimeSpan.ToString(#"mm\:ss"); //Convert the playingPosition to a string (Format mm:ss)
string playingContext = "spotify:artist:1EfwyuCzDQpCslZc8C9gkG";
await SendPlayRequest(trackUri + "#" + playingPosStr, playingContext);
if (!status.Playing) { await SendPauseRequest(); }
}
I need to call the SendPlayRequest() method with the correct playingContext because when the current song is part of a playlist and you call SendPlayRequest() without the context, the next song isn't from the playlist anymore.
But you can see that I use a fixed context at the moment.
So my question is now: How can I get the context (playlist, artist, ...) of the currently played song with the SpotifyLocalAPI?
The SeekPlayback method of the library you mentioned lets you seek through playback on whatever device your user is listening on. You can find the docs here.
Seeking playback is not currently possible using the Spotify Local API portion of that library.

Auto focus camera without preview

I am running Win10 IoT on a pi 2. I need to be able to take pictures that are focused but cannot get the focus working. The application is a background app so I don't have a way of previewing the camera on a display. Is there any way of doing this? Currently I have
await _mediaCapture.StartPreviewAsync();
_mediaCapture.VideoDeviceController.FocusControl.Configure(new FocusSettings
{
Mode = FocusMode.Continuous,
WaitForFocus = true
});
await _mediaCapture.VideoDeviceController.FocusControl.FocusAsync();
await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);
await _mediaCapture.StopPreviewAsync();
but I am getting the error
WinRT information: Preview sink not set
when I try to focus. All of the examples I've seen online show that the preview is output to a control and I assume it wires a sink up automagically. Is there a way to do this manually through code? Possibly without the preview?
I wonder if the code may work even without FocusControl.
I propose you follow Customer Media Sink implementation example and use of StartPreviewToCustomSinkIdAsync method described at http://www.codeproject.com/Tips/772038/Custom-Media-Sink-for-Use-with-Media-Foundation-To
I didn't find a way to do this. I ended up converting the background app to a UI app with a Page containing a CaptureElement control in order to preview and focus.
Instead of adding a UI, just create a CaptureElement and set the source to the _mediaCapture before calling await _mediaCapture.StartPreviewAsync();
Something like:
_captureElement = new CaptureElement { Stretch = Stretch.Uniform };
_mediaCapture = new MediaCapture();
await _mediaCapture.InitializeAsync(...);
_captureElement.Source = _mediaCapture;
await _mediaCapture.StartPreviewAsync();

Adobe AIR for iPhone app: can't play audio properly

I just developed an App by using adobe air. It contains some animations with background music in mp3 format. The problem is that the music is very jerky when the animation is playing...
FYI, this is the way how I play audio in flash:new Sound(new URLRequest("m3.mp3")).play()
Have I done anything wrong?
BTW, the funny thing is that if you hit the HOME button, and then come back to the app again, everything plays beautifully...
Without knowing more about the code, it seems like the sound is not fully loaded. The file plays as far as it can, then waits for more data to show up, then continues . . . very jerky. You may have to wait for the sound to load completely before playing it:
var s = new air.Sound();
s.addEventListener(air.Event.COMPLETE, onSoundLoaded);
var req = new air.URLRequest("bigSound.mp3");
s.load(req);
function onSoundLoaded(event)
{
var localSound = event.target;
localSound.play();
}
This code is from Adobe's Sound docs.

Playing a sound in a Firefox add-on

I would like to create a simple add-on that would play a different MP3 recording every time the user double clicks a word in a webpage he is visiting and selects a special option from the context menu.
The MP3 files are located on a remote server. Normally I would use JavaScript+Flash to play the MP3 file. In a Firefox add-on, however, I'm unable to load external scripts for some reason (playing the sound works fine if it's the webpage itself that loads the scripts, but of course I need it to work with every website and not just the ones that include the script).
So what's the easiest way to play a remote MP3 file in a Firefox add-on using JavaScript?
This may not entirely solve your question, as I don't BELIEVE it plays MP3s, but I'm not certain.
Firefox has nsISound, which I KNOW can play remote WAV files, as I've tested and proved it.
You may want to test it for yourself and see if it leads you a little closer!
var ios = Components.classes['#mozilla.org/network/io-service;1'].getService(Components.interfaces.nsIIOService);
var sound = ios.newURI("http://www.yoursite.com/snds/haha.wav", null, null);
var player = Components.classes["#mozilla.org/sound;1"].createInstance(Components.interfaces.nsISound);
player.play(sound);
Good luck, I hope this at least gets you close!
I know this is an old question, but if someone needs a way to do it:
let player = document.createElement("audio");
player.src = browser.runtime.getURL(SOUND_URL);
player.play();
There is one caveat: the user must have allowed autoplay on the website.
Here is a working code....
var sound = Components.classes["#mozilla.org/sound;1"].createInstance(Components.interfaces.nsISound);
var soundUri = Components.classes['#mozilla.org/network/standard-url;1'].createInstance(Components.interfaces.nsIURI);
soundUri.spec = "chrome://secchat/content/RING.WAV";
sound.play(soundUri);
var window = require('sdk/window/utils').getMostRecentBrowserWindow();
var audio = ('http://example.com/audio.mp3');
audio.play();

Resources