'audio pause in xamarin.forms C#
So i am building an app using xamarin.forms which needs to play and control audio. I have currently got my audio file playing on both android and iOS BUT I can't get other controls to work such as .Pause() and .Stop()
Playing audio works in both examples.
I thank you in advance!
Here is my code for each platform
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();
}
}
}
Solution 1:[1]
That topic is old, but I did it that way:
MediaPlayer player;
public void PlayAudioFile(string fileName, string ONOF)
{
if (ONOF == "OFF")
{
player.Stop();
}
if (ONOF == "ON")
{
player = new MediaPlayer();
var fd = global::Android.App.Application.Context.Assets.OpenFd(fileName);
player.Prepared += (s, e) =>
{
player.Start();
};
player.SetDataSource(fd.FileDescriptor, fd.StartOffset, fd.Length);
player.Prepare();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
