I'm working on a UWP app (running on a Raspberry Pi running Windows 10 IoT), and I need to play sound at certain times each day. I initialize a MediaPlayer and StorageFile by calling the following method:
private async void prepPlayer() {
file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///audio.mp3"));
player = new MediaPlayer();
}
and then I call it when I want audio played by calling the following method:
public async void playAudio(){
player.SetFileSource(file);
player.Play();
}
The problem I'm having is that after a few times of playAudio getting called, it quits playing the audio. I can't reproduce this with the debugger running. Any ideas?
Try this:
Open Package.appxmanifest.
Click Capabilities tab.
Tick Background Media Playback
My requirement is almost same. My app should play different audio files on 5 different times per day. Whatever I developed till now is working well.
Related
I am trying to do a task that runs indefinitely in a background mode in xamarin ios, but the task takes only 30 seconds to kill the app when it is send to a second plane, so I really do not know how to extend this time in order to receive that information.
This is the method that launches the background task:
public async void ActivateHeartbeat()
{
await Task.Factory.StartNew(() =>
{
taskID = UIApplication.SharedApplication.BeginBackgroundTask(() =>
{
Console.WriteLine("APPLICATION GOT KILLED");
UIApplication.SharedApplication.EndBackgroundTask(taskID);
});
while (true)
{
Console.WriteLine("Background time remaining: " + UIApplication.SharedApplication.BackgroundTimeRemaining);
int sent = SendTCP(data);
if (sent > 0) Console.WriteLine("Sent Heartbeat.");
Thread.Sleep(10000);
}
});
}
I have already read all the documentation that Microsoft is offering, but it did not help for me. How can I increase that background time?
Result of console when the app is pushed to second plane (minimizing the app on an iPhone):
Background time remaining: 25.9390514166444
Sent Heartbeat.
Background time remaining: 15.8512012083665
Sent Heartbeat.
Background time remaining: 5.76157358335331
Sent Heartbeat.
APPLICATION GOT KILLED
APPLICATION GOT KILLED
Any help is welcome. Thanks in advance,
Raúl.
It is well-known that Apple is so strict about hardware resources occupied by App, not to mention App in the background state. When App enter the background state, it will soon be suspended by the OS, unless you apply for permisson from OS.
The following image is from XCode Capabilities. These modes can run in the Background Modes.
Seems that you couldn't directly run your app in the background mode.
However, some articles extend the background time by playing blank videos as audio can be played in Background modes. That means we have to play blank audio in the background task. You could refer to Unlimited Backgrounding on iOS. But i have no idea if Apple will approve this app on Apple Store.
Hope my answer makes sense.
I was publishing my first C# Windows Form Application with a built-in audio player (I used System.Media), but when I tried to run the program on another PC of mine, it returned an exception and then crashed every time I click on the button to play audio so I was wondering if there was a way to play the audio on another PC without crashing.
Here's the code part I used to play the sound:
System.Media.SoundPlayer player = new System.Media.SoundPlayer("mouse_click.wav");
player.Play();
Then the PC I used to run the program returned this error: verify that the audio file path is correct.
Thank you everyone for the help!
If you want to add a Wav file to Windows Form Application, you can refer to the following steps:
First, add the Wav file in the Resources File (Project>Properties>Resources):
Second, refer to the following code to play the Wav file in VS:
System.Media.SoundPlayer player = new System.Media.SoundPlayer(Properties.Resources._15035);//Use your own filename in place of _15035
player.Play();
I have little experience at playing .MP3 files in C# applications, but I have a need to do so. I tried writing a simple, .NET Core 3 console app over the weekend. It worked fine. I thought it would be easy to duplicate what I'd done at home to my work environment, but it's not playing to .MP3 file. Here's the code that I have in a WPF app we're writing:
private MediaPlayer mediaPlayer;
private void PlayDrinkingSound()
{
if (mediaPlayer == null)
{
mediaPlayer = new MediaPlayer();
mediaPlayer.Open(new Uri(Environment.CurrentDirectory + #"\Audio\Slurping-SoundBible.com-755296861.mp3", UriKind.RelativeOrAbsolute));
}
mediaPlayer.Play();
}
The differences between the two is at home I wrote a .NET Core 3.1 console app. At work its a .NET 4.5.2 WPF app.
I've set the Build Action on the .MP3 to Resource.
here maybe
When distributing media with your application, you cannot use a media
file as a project resource. In your project file, you must instead set
the media type to Content and set CopyToOutputDirectory to
PreserveNewest or Always.
When the BackgroundAudioTask for my app is cancelled by other app on Windows Phone 8.1 which also uses BackgroundAudioTask, when I go back into my app, it will no longer play audio in the background. It will play fine when the app is running but if it is suspended - the background audio also stops.
The steps to reproduce this issue are:
I launch the Windows Phone 8.1 app which has a BackgroundAudioTask & everything works fine. I that start another app, for example the Music player, that uses a BackgroundAudioTask it will cancel the BackgroundAudioTask of my app.
When I launch my app for the second time, I want to re-register my BackgroundAudioTask so that it will behave as it did originally.
In Package.appxmanifest I have the following:
<Extensions>
<Extension Category="windows.backgroundTasks" EntryPoint="WindowsPhoneBackgroundAudioTask.BackgroundAudioTask">
<BackgroundTasks>
<Task Type="audio" />
</BackgroundTasks>
</Extension>
</Extensions>
When I first run the application the Run method will be called and I add a Deferral to the task to make sure it is kept alive even when I close my application:
public void Run(IBackgroundTaskInstance taskInstance)
{
setupDeferral = taskInstance.GetDeferral();
}
When I start the music player from another application my BackgroundAudioTask Cancelled event is called (If I don't do setupDeferral.Complete() here my application will crash):
private void Task_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
setupDeferral.Complete();
}
When I open my app how do I recreate my BackgroundAudioTask? The problem is the Run method is never called again so I can't setup the Deferral again. Music will now play fine in the app, but as soon as I navigate away from the app the music will stop.
I tried manually re-registering the task in App.xaml.cs in the App_Resuming event with this code:
var taskBuilder = new BackgroundTaskBuilder();
taskBuilder.Name = "BackgroundAudioTask";
taskBuilder.TaskEntryPoint = typeof(WindowsPhoneBackgroundAudioTask.BackgroundAudioTask).FullName;
BackgroundTaskRegistration task = taskBuilder.Register();
The above code will throw and InvalidArgumentException because it does not have a Trigger setup. I don't want it to have a trigger. I just want to start the background task immediately.
Is there a way to manually instruct the OS to run the background audio again or a way to handle cancelled background audio better?
I know this is really old - but maybe someone will come across it. You actually don't need to register the task at all.
In the case of background audio, all you need to do is call
BackgroundMediaPlayer.Current
And it will fire up the task, and then your code will get the deferral.
I too had this same issue. The Background Audio Task wasn't starting playback once it was cancelled - either due to 5 minutes of inactivity, or due to another app. I was referring the sample code given by Microsoft here.
After hours of searching on the internet, I didn't find a solution. Then, digging in my code further, I found out that when the task is cancelled, the BackgroundMediaPlayer.Current.CurrentState becomes MediaPlayerState.Closed.
Hence, in order to restart the task/background audio playback, just set a source to the BackgroundMediaPlayer.Current again. In the sample code, this media player object is referenced using a variable named mediaPlayer inside the PlaylistManager project component.
Although the sample has a piece of code to restart playback once the task is cancelled, it does not work.
When I try to play a sound with a media element on my local machine I can't hear any sound. But I can hear sound in the simulator(same thing almost right?) and on my surface when I test it on there. It Doesn't work on all my pages too not just one on the local machine only too.
load event goes off in simulator but not in local machine. Also stream isn't null.
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Sound/" +selectedCharacterSets[currentCharacterSet].character[currentCharacter].romaji + ".mp3", UriKind.Absolute));
var stream = await file.OpenAsync(FileAccessMode.Read);
mdeSound.SetSource(stream, file.ContentType);
Media failed event going off. Error: MF_MEDIA_ENGINE_ERR_SRC_NOT_SUPPORTED : HRESULT 0x8000FFFF. Does anyone know how to fix this and why its only on local machine?
EDIT: converted mp3 to wma... still doesn't load. converted it to wmv now it plays on local machine... why? I'm still confused. Opening the mp3 in the music app throws an error too, windows media player plays it fine.
There is an issue with the file you are trying to play. This could be because of DRM or because of bitrates being too high, etc. Windows 8 Pro can play more codecs than Windows 8 RT, but you said it worked on your Surface which is interesting. Try using Audacity or another program to save it as a lower bitrate MP3 or even a basic .WAV file.
It's also interesting that you couldn't play it as WMA but you could as WMV. WMV is video while WMA is audio. You may have a corrupt media stack on your machine.
P.S. The simulator essentially uses Remote Desktop, so there is a difference in how the audio gets played.