如何使用Xamarin Forms在Android上播放音频?我有以下服务,但是可以使用,但是Forms.Context
不再支持,消息为“上下文从版本2.5开始已过时。请改用本地上下文。”。
[assembly: Dependency(typeof(AudioService))]
namespace SensaLabScan.Droid.Services
{
public class AudioService : IAudioService
{
private readonly MediaPlayer _mediaPlayer = new MediaPlayer();
public void PlayBeep()
{
_mediaPlayer.Reset();
// Forms.Context references the Activity which calls Forms.Init, i.e. MainActivity.
using (var beepFile = Forms.Context.Assets.OpenFd("beep.mp3"))
{
_mediaPlayer.SetDataSource(beepFile);
_mediaPlayer.Prepare();
_mediaPlayer.Start();
}
}
}
}
在这种情况下,替代已弃用的Forms.Context
有什么选择?我已经尝试过
Android.App.Application.Context.Assets.OpenFd("beep.pm3");
,但这会引发文件未找到异常MainActivity
作为上下文,并从中使用Assets
,但仍然是找不到文件错误。我要阅读的mp3文件位于Assets文件夹中,并标记为AndroidAsset。
[assembly: Dependency(typeof(MyDependenceService))]
namespace MediaPlayDemo.Droid
{
public class MyDependenceService : IPlayMedia
{
public void playMusic()
{
//throw new NotImplementedException();
var bytes = default(byte[]);
using (StreamReader reader = new StreamReader(Android.App.Application.Context.Assets.Open("Test.mp3")))
{
using (var memstream = new MemoryStream())
{
reader.BaseStream.CopyTo(memstream);
bytes = memstream.ToArray();
}
}
Play(bytes);
}
// Stop();
MediaPlayer currentPlayer;
public void Play(byte[] AudioFile)
{
Stop();
currentPlayer = new MediaPlayer();
currentPlayer.Prepared += (sender, e) =>
{
currentPlayer.Start();
};
currentPlayer.SetDataSource(new StreamMediaDataSource(new System.IO.MemoryStream(AudioFile)));
currentPlayer.Prepare();
}
void Stop()
{
if (currentPlayer == null)
return;
currentPlayer.Stop();
currentPlayer.Dispose();
currentPlayer = null;
}
}
public class StreamMediaDataSource : MediaDataSource
{
System.IO.Stream data;
public StreamMediaDataSource(System.IO.Stream Data)
{
data = Data;
}
public override long Size
{
get
{
return data.Length;
}
}
public override int ReadAt(long position, byte[] buffer, int offset, int size)
{
data.Seek(position, System.IO.SeekOrigin.Begin);
return data.Read(buffer, offset, size);
}
public override void Close()
{
if (data != null)
{
data.Dispose();
data = null;
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (data != null)
{
data.Dispose();
data = null;
}
}
}
}