- 先用NuGet下载Plugin.MediaManager, 这里用到1.09版
- 把mp3文件复制到Android项目的Assets目录中
- 编辑Android项目中 MainActivity.cs:
using MediaManager; //引用
...
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState); // add this line to your code, it may also be called: bundle
CrossCurrentActivity.Current.Init(this, savedInstanceState);
Mp3Import(); //从Assets复制MP3文件到本地
CrossMediaManager.Current.Init(this); //初始化
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
//从Assets复制MP3文件到本地
private void Mp3Import()
{
string filePath = Constants.Mp3Path;
try
{
if (!File.Exists(filePath)) //不存在,拷贝Assets中的.mp3到SD卡目录
{
Console.WriteLine("mp3复制");
// Read the contents of our asset
const int maxReadSize = 256 * 1024;
AssetManager assets = this.Assets;
byte[] buffer = new byte[1024];
using (BinaryReader br = new BinaryReader(assets.Open("pass_mp3")))
{
buffer = br.ReadBytes(maxReadSize);
}
FileStream outfile = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
outfile.Write(buffer);
outfile.Close();
}
else
{
Console.WriteLine("mp3已存在.");
}
}
catch (Exception e)
{
Console.WriteLine("复制mp3失败" + e.Message);
}
}
-
ViewModel中播放:
注意"file:///"协议的使用
async void PlayMp3()
{
await CrossMediaManager.Current.Play("file:///" + Constants.Mp3Path);
}
附1: MediaManager源码及使用说明
附2: 自述文件
注1: 其实用微软的MediaPlayer就可以实现. 文档
注2: 遇到无法完整播放MP3(只播放10几秒), 目前解决方案好像只能搞mp3文件: 降低其速率, 深度, 或双声道改为单声道.