Wednesday, 9 January 2019

Play Audio in Xamarin Forms using Xam.Plugin.SimpleAudioPlayer


A light-weight and easy to use cross-platform audio player for Windows UWP, Xamarin.iOS, Xamarin.Android, Xamarin.Mac, Xamarin.tvOS and Xamarin.Forms. Load wav and mp3 files from any location including a shared library. Works well for sound effects or music. Multiple instances can be instantiated to play multiple sources simultaniously.

Install-Package Xam.Plugin.SimpleAudioPlayer -Version 1.1.0

Dependencies

·         .NETPlatform 5.0

    • No dependencies.

·         .NETStandard 1.0

    • NETStandard.Library (>= 1.6.1)

·         MonoAndroid 1.0

    • No dependencies.

·         Tizen 0.0

    • No dependencies.

·         UAP 0.0

    • No dependencies.

·         Xamarin.iOS 1.0

    • No dependencies.

·         Xamarin.Mac 2.0

    • No dependencies.

·         Xamarin.TVOS 0.0

    • No dependencies.

API Usage

Call CrossSimpleAudioPlayer.Current from any project or PCL to gain access to APIs

Properties

Duration: length of audio in seconds
CurrentPosition: current playpack position in seconds
Volume: volume of audio between 0 and 1
Balance: balance between left and right as as double, -1 is left only, 0 is both, +1 is right only
IsPlaying: is the audio currently playing
CanSeek: can the playback position be updated

Methods

Load(Stream audioStream): load a compatible (wav, mp3, etc) audio from a stream
Load(string fileName): load a compatible audio file stored in the executing platform project
Play(): play the currently loaded audio
Stop(): stop playback and reset current position to start (0)
Pause(): pause playback (use Play() to resume)
Seek(double position): seek to a specific location in the audio (in seconds)

Please keep your mp3 files in both the platforms as below image



Design Page Xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="SAPlayerSample.PCLAudioPage"
             Title="Shared Audio">

  <StackLayout Orientation="Vertical" Spacing="5" Margin="10">
    <Label Text="Postion:" />
    <Slider x:Name="sliderPosition" />
    <Label x:Name="lblPosition" />

    <Button x:Name="btnPlay" Text="Play" BorderColor="Green" />
    <Button x:Name="btnPause" Text="Pause" BorderColor="Blue" />
    <Button x:Name="btnStop" Text="Stop" BorderColor="Red" />

    <Label Text="Volume:" />
    <Slider x:Name="sliderVolume" Minimum="0" Maximum="1"/>
  </StackLayout>

</ContentPage>

Code Behind:
using Plugin.SimpleAudioPlayer.Abstractions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;

using Xamarin.Forms;

namespace SAPlayerSample
{
    public partial class PCLAudioPage : ContentPage
    {
        ISimpleAudioPlayer player;
        public PCLAudioPage()
        {
            InitializeComponent();

            var stream = GetStreamFromFile("Diminished.mp3");
            player = Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.CreateSimpleAudioPlayer();
            player.Load(stream);

            InitControls();
        }

        void InitControls ()
        {
            sliderVolume.Value = player.Volume;

            btnPlay.Clicked += BtnPlayClicked;
            btnPause.Clicked += BtnPauseClicked;
            btnStop.Clicked += BtnStopClicked;

            sliderVolume.ValueChanged += SliderVolumeValueChanged;
            sliderPosition.ValueChanged += SliderPostionValueChanged;
 
        }

        private void SliderPostionValueChanged(object sender, ValueChangedEventArgs e)
        {
            if (sliderPosition.Value != player.Duration)
                player.Seek(sliderPosition.Value);       
        }

        private void SliderVolumeValueChanged(object sender, ValueChangedEventArgs e)
        {
            player.Volume = sliderVolume.Value;
        }

        private void BtnStopClicked(object sender, EventArgs e)
        {
            player.Stop();
        }

        private void BtnPauseClicked(object sender, EventArgs e)
        {
            player.Pause();
        }

        private void BtnPlayClicked(object sender, EventArgs e)
        {
            player.Play();
                       
            sliderPosition.Maximum = player.Duration;
            sliderPosition.IsEnabled = player.CanSeek;

            Device.StartTimer(TimeSpan.FromSeconds(0.5), UpdatePosition);
        }

        bool UpdatePosition ()
        {
            lblPosition.Text = $"Postion: {(int)player.CurrentPosition} / {(int)player.Duration}";

            sliderPosition.ValueChanged -= SliderPostionValueChanged;
            sliderPosition.Value = player.CurrentPosition;
            sliderPosition.ValueChanged += SliderPostionValueChanged;

            return player.IsPlaying;
        }

        Stream GetStreamFromFile(string filename)
        {
            var assembly = typeof(App).GetTypeInfo().Assembly;

            var stream = assembly.GetManifestResourceStream("SAPlayerSample." + filename);

            return stream;
        }
    }
}
Get Full Source Code :


31 comments:

  1. System.NullReferenceException
    Message=Object reference not set to an instance of an object.

    ReplyDelete
  2. Replies
    1. Always, ALWAYS: make sure you change the properties of whatever file you've added to your project to Embedded Resource before compiling. So your "player" value doesn't throw that exception.

      Delete
  3. How you will play list of sounds?
    I tried to get list of sounds and play in foreach or for loop, but it will iterate all and play the last one.
    I used thread sleeping (duration of trak) to wait and play each track, but it will stop the system and no option to pause or resume it till end of duration.
    Any sulotion please!

    ReplyDelete
  4. Hey! I simply wish to give an enormous thumbs up for the good information you’ve got here on this post. I will likely be coming back to your blog for more soon. Mega888 game client download

    ReplyDelete
  5. I’m curious to find out what blog system you have been using? I’m experiencing some small security problems with my latest website and I would like to find something more risk-free. Do you have any suggestions? wettanbieter ohne oasis

    ReplyDelete
  6. Hi, I'm manager of Ganja Skunks, Feel Free Contact Us about medicines and pharma:
    can of coke

    ReplyDelete
  7. Hi, I'm manager of Ganja Skunks, Feel Free Contact Us about medicines and pharma:
    Alaskan Thunderfuck Weed Strain

    ReplyDelete
  8. Due to the use of Chebe Powder, it is common in Chad for the hair to grow past the waist of women in Chad. Chebe moisturizes hair and prevents breakage.
    african hair grease

    ReplyDelete
  9. Renting a single 15 passenger van is often more cost-effective than renting multiple smaller vehicles to accommodate the same number of passengers.
    15 passenger van rental atlanta

    ReplyDelete
  10. 69DAFLauraAC7E014 April 2024 at 05:48

    04E34
    ----
    ----
    ----
    ----
    ----
    ----
    ----
    ----
    matadorbet

    ReplyDelete
  11. I am usually to blogging and i also actually appreciate your site content. The content has really peaks my interest. My goal is to bookmark your website and keep checking choosing details. babysitting jobs cardiff

    ReplyDelete
  12. You have observed very interesting details ! ps decent internet site . mexican food

    ReplyDelete
  13. Thank you for another wonderful post. Where else could anyone get that type of information in such a perfect way of writing? I have a presentation next week, and I’m on the look for such information. Unfallwagen Verkaufen

    ReplyDelete

All About .NET MAUI

  What’s .NET MAUI? .NET MAUI (.NET Multi-platform App UI) is a framework for building modern, multi-platform, natively compiled iOS, Androi...

Ads2