1
因此,我使用需要播放和控制音頻的xamarin.forms構建應用程序。我目前有我的音頻文件在Android和iOS上播放,但我無法讓其他控件工作,如.Pause()和.Stop()xamarin.forms中的音頻暫停C#
播放音頻在兩個示例中都有效。
我提前感謝你!
這是我爲每個平臺代碼
ANDROID:
using System;
using Xamarin.Forms;
using AudioPlayEx.Droid;
using AudioToolbox;
using Android.Media;
using Android.Content.Res;
using Android.OS;
using Android;
[assembly: Dependency(typeof(AudioService))]
namespace AudioPlayEx.Droid
{
public class AudioService : IAudio
{
public AudioService()
{
}
MediaPlayer player;
public void PlayAudioFile(string fileName)
{
var player = new MediaPlayer();
var fd = Android.App.Application.Context.Assets.OpenFd(fileName);
player.Prepared += (s, e) =>
{
player.Start();
};
player.SetDataSource(fd.FileDescriptor, fd.StartOffset, fd.Length);
player.Prepare();
}
protected MediaPlayer playme;
public void PauseAudioFile(String fileName)
{
var player = new MediaPlayer();
var fd = Android.App.Application.Context.Assets.OpenFd(fileName);
player.Prepared += (s, e) =>
{
player.Pause();
};
player.SetDataSource(fd.FileDescriptor, fd.StartOffset, fd.Length);
player.Prepare();
}
}
}
的iOS:
using System;
using Xamarin.Forms;
using AudioPlayEx;
using AudioPlayEx.iOS;
using System.IO;
using Foundation;
using AVFoundation;
[assembly: Dependency(typeof(AudioService))]
namespace AudioPlayEx.iOS
{
public class AudioService : IAudio
{
public AudioService()
{
}
public void PlayAudioFile(string fileName)
{
string sFilePath = NSBundle.MainBundle.PathForResource(Path.GetFileNameWithoutExtension(fileName), Path.GetExtension(fileName));
var url = NSUrl.FromString(sFilePath);
var _player = AVAudioPlayer.FromUrl(url);
_player.FinishedPlaying += (object sender, AVStatusEventArgs e) => {
_player = null;
};
_player.Play();
}
public void PauseAudioFile(string fileName)
{
string sFilePath = NSBundle.MainBundle.PathForResource(Path.GetFileNameWithoutExtension(fileName), Path.GetExtension(fileName));
var url = NSUrl.FromString(sFilePath);
var _player = AVAudioPlayer.FromUrl(url);
_player.Pause();
}
}
}