I have asked this question in Xamarins forum but nobody has answered, im hoping this forum can provide an answer for me.
My problem is how to play an mp3 file from a shared project on android.
I'm making a Xamarin Forms project and uses interfaces to make platform specific code for playning tha mp3 file.
I have embedded 360 mp3 files in my shared project, and the pass the file to the interface to make the mp3 play.
The class AudioHelper returns a stream by getting the correct mp3 file based on it's name
var assembly = typeof(StaveApp_v2.App).GetTypeInfo().Assembly;
var stream = assembly.GetManifestResourceStream
(resourcePrefix + $"Audio.{name}.mp3");
return stream;
Then I pass the stream to the Interface
var audioStream = AudioHelper.AudioFile("aften");
DependencyService.Get<IPlayWord>().Play(audioStream);
On windows the file plays as expected, but I’m having trouble getting the file to play on android. I'm using AudioTrack to play the sound (the sound should play 2 times). The app plays a scratchy sound 2 times with a duration matching the file length, but I can’t get it to play correctly.
This is the code im using
var memoryStream = new MemoryStream();
audio.CopyTo(memoryStream);
var audioBytes = memoryStream.ToArray();
var byteLenght = audioBytes.Length * sizeof(short);
var audioTrack = new AudioTrack(Android.Media.Stream.Music,
16000,
ChannelOut.Mono,
Encoding.Pcm16bit,
byteLenght,
AudioTrackMode.Static);
for (int i = 0; i < 2; i++)
{
try
{
audioTrack.Write(audioBytes, 0, audioBytes.Length);
audioTrack.Play();
}
catch (IllegalStateException illEx)
{
Log.Debug("StaveApp", $"Unable to initialize audio exception {illEx.Message}");
}
await Task.Delay(2000);
audioTrack.Stop();
audioTrack.ReloadStaticData();
}
audioTrack.Release();
audioTrack.Dispose();
I'm getting no errors in logcat and