gpt4 book ai didi

c# - Xamarin Forms 异步播放声音

转载 作者:行者123 更新时间:2023-12-02 23:39:43 24 4
gpt4 key购买 nike

我可以使用 Xamarin 表单(Android 和 iOS)成功播放声音,但我还需要实现以下目标:

  • 我需要等待,以便如果“播放”多个声音,一个会在下一个之前完成。
  • 我需要返回一个 bool 值来指示操作是否成功。

  • 这是我当前的简化代码(适用于 iOS 平台):
        public Task<bool> PlayAudioTask(string fileName)
    {
    var tcs = new TaskCompletionSource<bool>();

    string filePath = NSBundle.MainBundle.PathForResource(
    Path.GetFileNameWithoutExtension(fileName), Path.GetExtension(fileName));

    var url = NSUrl.FromString(filePath);

    var _player = AVAudioPlayer.FromUrl(url);

    _player.FinishedPlaying += (object sender, AVStatusEventArgs e) =>
    {
    _player = null;
    tcs.SetResult(true);
    };

    _player.Play();

    return tcs.Task;
    }

    为了测试该方法,我尝试这样调用它:
        var res1 = await _audioService.PlayAudioTask("file1");
    var res2 = await _audioService.PlayAudioTask("file2");
    var res3 = await _audioService.PlayAudioTask("file3");

    我曾希望听到 file1、file2、file3 的音频。但是我只听到文件 1 并且代码似乎没有达到第二个等待。

    谢谢

    最佳答案

    我认为您的问题是 AVAudioPlayer _player在它完成之前被清除。如果您要在 FinsihedPlaying 中添加调试,你会注意到你从来没有达到那个点。

    试试这些改变,我做了一个私有(private)的AVAudioPlayer坐在 Task 外面

    (我使用以下指南作为引用 https://developer.xamarin.com/recipes/ios/media/sound/avaudioplayer/ )

        public async void play()
    {

    System.Diagnostics.Debug.WriteLine("Play 1");
    await PlayAudioTask("wave2.wav");

    System.Diagnostics.Debug.WriteLine("Play 2");
    await PlayAudioTask("wave2.wav");

    System.Diagnostics.Debug.WriteLine("Play 3");
    await PlayAudioTask("wave2.wav");

    }


    private AVAudioPlayer player; // Leave the player outside the Task

    public Task<bool> PlayAudioTask(string fileName)
    {
    var tcs = new TaskCompletionSource<bool>();

    // Any existing sound playing?
    if (player != null)
    {
    //Stop and dispose of any sound
    player.Stop();
    player.Dispose();
    }

    string filePath = NSBundle.MainBundle.PathForResource(
    Path.GetFileNameWithoutExtension(fileName), Path.GetExtension(fileName));

    var url = NSUrl.FromString(filePath);

    player = AVAudioPlayer.FromUrl(url);

    player.FinishedPlaying += (object sender, AVStatusEventArgs e) =>
    {
    System.Diagnostics.Debug.WriteLine("DONE PLAYING");
    player = null;
    tcs.SetResult(true);
    };


    player.NumberOfLoops = 0;
    System.Diagnostics.Debug.WriteLine("Start Playing");
    player.Play();

    return tcs.Task;
    }

    application output

    关于c# - Xamarin Forms 异步播放声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40366146/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com