I'm creating a Maui .Net 7 application that can play audio files and works well for local files on Android and Windows using Plugin.Maui.Audio. For local files, the below code works correctly.
var player = AudioManager.Current.CreatePlayer(await FileSystem.OpenAppPackageFileAsync("audio_file_name.mp3"));
player.Play();
The problem is that I want to play audio files that will be hosted on a web server or some remote location. I've tested it by uploading a few test files to a personal web hosting account and linking directly to the file, finding a test audio file hosted elsewhere https://www.learningcontainer.com/wp-content/uploads/2020/02/Kalimba.mp3
, And also setup Azure Blob storage and tried playing audio from there. Still, no matter what I try, the audio file does not play. Nothing happens. No errors. I tried the below 2 ways of having a remotely hosted file play in the app. Even if I press play and wait minutes for it to start playing, nothing happens.
#1. Streaming directly from the remote source:
var player = AudioManager.Current.CreatePlayer("https://link/to/file.mp3");
player.Play();
#2 Downloading the file first and then playing it:
public async Task DownloadFile(string url, string filePath)
{
var client = new HttpClient();
var response = await client.GetAsync(url);
var stream = await response.Content.ReadAsStreamAsync();
var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
await stream.CopyToAsync(fileStream);
}
var localFilePath = Path.Combine(FileSystem.CacheDirectory, "file.mp3");
await DownloadFile("https://link/to/file.mp3", localFilePath);
var player = AudioManager.Current.CreatePlayer(localFilePath);
player.Play();
Looking into Plaugin.Maui.Audio, It's supposed to be able to play a Stream as well and not just local files. I'm not sure what I'm doing wrong here. Any suggestions for having this work correctly for a Maui application?
It's supposed to be able to play a Stream as well and not just local files.
In the source code of the IAudioManager it provide the method.
IAudioPlayer CreatePlayer(Stream audioStream)
{
return new AudioPlayer(audioStream);
}
but just as jdweng said that Applications are suppose to test the file type using both extension and ASCII Header
I am not sure that the https response can be recognized as a stream.
Acturaly, you can use the MediaElement to play the audio by using the HTTP and HTTPS URI schemes. Here is the code sample:
<toolkit:MediaElement Source="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
ShouldShowPlaybackControls="True" />
This MediaElement belongs to the .NET MAUI Community Toolkit.