2016-11-01 48 views
1

我可以顺利播放使用Xamarin形式(Android和iOS)的声音,但是我还需要做到以下几点:Xamarin形式播放声音异步

  • 我需要等待,这样,如果多个声音是“玩” ,一个将在下一个之前完成。
  • 我需要返回一个布尔值来指示操作是否成功。

这是我目前的简化代码(在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,代码似乎没有达到第二个等待。

三江源

回答

0

我觉得这里的问题是,AVAudioPlayer _player正在清理出它完成之前。如果您要将调试添加到您的FinsihedPlaying,您会注意到,您从未达到过这一点。

尝试这些变化了,我发一个私人AVAudioPlayer到的Task

坐在外面(I使用下述导作为参考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

+0

** Apple的AVAudioPlayer参考** - https://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVAudioPlayerClassReference/ –

+0

** Xamarin - 用AVAudioPlayer播放声音** - https://developer.xamarin.com/recipes/ios/media/sound/avaudioplayer/ –