简体   繁体   English

如何在 Xamarin.forms 上播放声音?

[英]How to play sounds on Xamarin.forms?

I'm creating an app for Android, iOS and Windows Phone using Xamarin.forms.我正在使用 Xamarin.forms 创建适用于 Android、iOS 和 Windows Phone 的应用程序。 My question is how to play a mp3 or wav with Xamarin Forms?我的问题是如何使用 Xamarin Forms 播放 mp3 或 wav?

My business logic is handled by Shared Project and I don't know how to use platform specifically "MediaPlayer".我的业务逻辑由共享项目处理,我不知道如何专门使用“MediaPlayer”平台。

Right now Xamarin.form s has not sound API , so you need to use DependencyService现在Xamarin.form s 还没有完善的API ,所以你需要使用DependencyService

Check the following link, it is working fine for me:检查以下链接,它对我来说工作正常:

https://www.codeproject.com/Articles/1088094/Playing-audio-mp-File-in-Xamarin-Forms https://www.codeproject.com/Articles/1088094/Playing-audio-mp-File-in-Xamarin-Forms

We would require to create an Interface which will be implemented in platform specific project, I named it as IAudio.cs and the code for the same is as follows:我们需要创建一个将在特定平台项目中实现的接口,我将其命名为 IAudio.cs,其代码如下:

using System;
  namespace AudioPlayEx
   {
    public interface IAudio
        {
            void PlayAudioFile(string fileName);
        }
   }

Android Solution:安卓解决方案:

    using System;
    using Xamarin.Forms;
    using AudioPlayEx.Droid;
    using Android.Media;
    using Android.Content.Res;

    [assembly: Dependency(typeof(AudioService))]
    namespace AudioPlayEx.Droid
    {
        public class AudioService: IAudio
        {
            public AudioService ()
            {
            }

            public void PlayAudioFile(string fileName){
                var 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();
            }
        }
}

iOS Solution: 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();
        }
    }
}

And finally, we will use the following code in our PCL/shared project in order to play the audio file.最后,我们将在我们的 PCL/共享项目中使用以下代码来播放音频文件。

DependencyService.Get<IAudio>().PlayAudioFile("MySong.mp3");

You might give Xam.Plugin.SimpleAudioPlayer a try, since Xamarin.Forms doesn't have a sound API.您可以尝试Xam.Plugin.SimpleAudioPlayer ,因为 Xamarin.Forms 没有声音 API。

In short, add the NuGet package to each platform-specific project you wish to support.简而言之,将 NuGet 包添加到您希望支持的每个特定于平台的项目中。 Copy the audio files to the Assets folder for Windows UWP and Android and set the build actions as Content and Android Asset respectively.将音频文件复制到 Windows UWP 和 Android 的 Assets 文件夹,并将构建操作分别设置为ContentAndroid Asset For iOS copy the audio files to the Resources folder and set the build action to BundleResource , then play the files like so:对于 iOS,将音频文件复制到 Resources 文件夹并将构建操作设置为BundleResource ,然后像这样播放文件:

var player = Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current; 
player.Load("intro_sound.mp3");
player.Play();

I just finished creating an AudioManager for Xamarin that works on iOS, Android, UWP, Windows 8.1, and Windows Phone 8.1.我刚刚为 Xamarin 创建了一个适用于 iOS、Android、UWP、Windows 8.1 和 Windows Phone 8.1 的 AudioManager。 If you are interested check it out at https://github.com/jcphlux/XamarinAudioManager .如果您有兴趣,请查看https://github.com/jcphlux/XamarinAudioManager There is a link to a Nuget package or feel free to clone the project.有一个指向 Nuget 包的链接或随意克隆该项目。

I think, Xamarin.Forms has no sound APIs at the moment so you will have to write custom, platform-specific code.我认为, Xamarin.Forms 目前没有完善的 API,因此您必须编写自定义的、特定于平台的代码。

Check how James Montemagno implements TextToSpeech (using DependencyService )检查James Montemagno如何实现TextToSpeech (使用DependencyService

Refer :参考 :

Use a dependency service to play the sounds through the native platforms.使用依赖服务通过本机平台播放声音。 If you only need to play one sound at a time, you can use static fields to manage the lifetime of the player objects.如果您一次只需要播放一种声音,您可以使用静态字段来管理播放器对象的生命周期。 The static fields prevent the player from be destroyed and the audio to stop if a garbage collection occurs while the audio is playing.如果在播放音频时发生垃圾收集,则静态字段可防止播放器被破坏和音频停止。

The following approach plays one sound at a time, with any new sound terminating and replacing any previous sound.以下方法一次播放一个声音,任何新声音终止并替换任何以前的声音。

Create an interface for a dependency service:为依赖服务创建一个接口:

public interface IAudio {
    void PlayAudioFile(string fileName);
}

Use the dependency service where you want to play the sound:在要播放声音的地方使用依赖服务:

DependencyService.Get<IAudio>().PlayAudioFile("honk.mp3");

This is the dependency service for iOS:这是 iOS 的依赖服务:

using AVFoundation;
using Foundation;
using System.IO;
using Xamarin.Forms;

[assembly: Dependency(typeof(AudioService))]
public class AudioService : IAudio {
    static AVAudioPlayer player;

    public void PlayAudioFile(string fileName) {
        var url = NSUrl.FromString(NSBundle.MainBundle.PathForResource(Path.GetFileNameWithoutExtension(fileName), Path.GetExtension(fileName)));
        player = AVAudioPlayer.FromUrl(url);
        player.FinishedPlaying += (sender, e) => { player = null; };
        player.Play();
    }
}

This is the dependency service for Android:这是 Android 的依赖服务:

using Xamarin.Forms;
using Android.Media;

[assembly: Dependency(typeof(AudioService))]
public class AudioService : IAudio {
    static MediaPlayer player;

    public void PlayAudioFile(string fileName) {
        player?.Stop();
        player = new MediaPlayer();
        var fd = Android.App.Application.Context.Assets.OpenFd(fileName);
        player.SetDataSource(fd.FileDescriptor, fd.StartOffset, fd.Length);
        player.Prepared += (s, e) => player.Start();
        player.Completion += (s, e) => { player = null; };
        player.Prepare();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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