简体   繁体   中英

How to play audio in xamarin forms?

I am trying to play an audio file which is stored locally. I am using Xam.Plugin.SimpleAudioPlayer for playing audio. For UWP and Android, added the files in the Assets folder with the Build Action set to Content and Android Asset respectively.

My Code:

private void PlayAudio()
    {
        try
        {
            var stream = GetStreamFromFile("audio.mp3");
            var audio = Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current;
            audio.Load(stream);
            audio.Play();
        }
        catch (Exception e)
        {
            Debug.WriteLine("exception:>>" + e);
        }
    }

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

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

        return stream;
    }

But getting an exception in android and UWP, didn't check in IOS.

Android Exception:

[0:] exception:>>System.NullReferenceException: Object reference not set to an instance of an object. at Plugin.SimpleAudioPlayer.SimpleAudioPlayerImplementation.Load (System.IO.Stream audioStream) [0x00050] in C:\dev\open\Xamarin-Plugins\SimpleAudioPlayer\SimpleAudioPlayer\Plugin.SimpleAudioPlayer.Android\SimpleAudioPlayerImplementation.cs:100 at AudioPlay.MainPage.PlayAudio () [0x00014] in F:\AudioPlay\AudioPlay\AudioPlay\MainPage.xaml.cs:63

I am using.mp3 file. Am I missing something in this implementation? Please help me to fix this issue?

You just need to directly put the mp3 file in share project. And call the method

var stream = GetStreamFromFile("xxx.mp3");
var audio = Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current;
audio.Load(stream );
audio.Play();
Stream GetStreamFromFile(string filename)
{
   var assembly = typeof(App).GetTypeInfo().Assembly;

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

   return stream;
}

Update

I check your demo, and if you want to play mp3 file in your project. You need to set the build action of the mp3 as Embedded resource

Right click the mp3 file -> Property

在此处输入图像描述

try this For xamarin.android

var u = Android.Net.Uri.Parse("filepath");
MediaPlayer _player = MediaPlayer.Create(this, u);
_player.Start();

or use XamarinMediaManager plugin

https://github.com/martijn00/XamarinMediaManager

The accepted answer does not work when attempting to load a resource from a project that is not the main Xamarin Forms project.

The solution is to use Android.AssetManager.Open() to get a Stream (I'm sure iOS has something similar) . You'll need to use DependencyService to access this outside the Android project.

The MP3 files would be put in the Assets folder of the Android project. The audio files need to have Build Action: "Android Asset" , not "Embedded Resource" as above.


Example:
Android Project has Assets/Audio/click.mp3

AndroidProject/AndroidAssetManager.cs

[assembly: Dependency (typeof (AndroidAssetManager))]
namespace App.Droid
{
    public interface IAssetManager
    {
        Stream LoadAsset(string assetName);
        ...
    }

    public class AndroidAssetManager : IAssetManager
    {
        private readonly AssetManager _assets;

        public AndroidAssetManager(AssetManager assets)
        {
            _assets = assets;
        }
        
        public Stream LoadAsset(string assetName)
        {
            return _assets.Open(assetName);
        }
        ...
    }
}

Shared/AudioPlayer.cs:

class AudioPlayer : IAudioPlayer
{
    private IAssetManager AssetManager => DependencyService.Get<IAssetManager>();
    private ISimpleAudioPlayer _clickPlayer;

    public AudioPlayer()
    {
        _clickPlayer = CrossSimpleAudioPlayer.CreateSimpleAudioPlayer();
        _clickPlayer.Load(AssetManager.Load("Audio/click.mp3"));
    }

    public void PlayClick()
    {
        _clickPlayer.Play();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM