Search code examples
c#xamarin.iosavaudioplayeraudio-player

Open a large number of AVAudioPlayers at once?


Let's assume I want to use AVAudioPlayer and NOT SystemSound for the volume control that AVAudioPlayer provides that SystemSound does not.

It seems with the AVAudioPlayer that there is a limit to the number of Players I can have open at once. You'll notice in the code of my example project that when I create a list of 200 AVAudioPlayer's, List, that it works just fine. But when I increase that number to 300, it crashes with an error. My only conclusion is that I am allowed to create a certain number of players. Is this the case? Is there any way I can create more players without a crash?

    AVAudioPlayer player;
    NSUrl mediaFile;
    List<AVAudioPlayer> playerList;



    DateTime before = DateTime.Now;
    mediaFile = NSUrl.FromFilename("mySoundConvertedToCAF.caf");
    player = AVAudioPlayer.FromUrl(mediaFile);
    player.Delegate = new AVAudioPlayerDelegate();
    Console.WriteLine("total ms = " + DateTime.Now.Subtract (before).TotalMilliseconds);


    playerList = new List<AVAudioPlayer>();


    // For loop 200 times works
    // for ( int i = 0; i < 200; i++ )

    // For loop 300 times does NOT work.  Almost as if somewhere between 200 and 300 AVAudioPlayers is the max amount you can have open at once... Is it because all of them are accessing the same sound file?
    for ( int i = 0; i < 300; i++ )
    {
        playerList.Add (AVAudioPlayer.FromUrl(mediaFile));
        playerList[i].Delegate = new AVAudioPlayerDelegate();
    }

    Console.WriteLine("I made a list of " + playerList.Count() + " AVAudioPlayers!");


    playerList[0].Play();

    Thread.Sleep(500);

    playerList[1].Play();

As far as why I would want to do this, it's for iOS game engine work... I'm not playing hundreds of sounds at once but I want the players open so that at any point in time I could play them without loading up a new AVAudioPlayer or changing media files....


Solution

  • I've solved the problem. Instead of reading from the audio file using type NSURL, use type NSData. And instead of importing with the AVAudioPlayer.FromUrl function use the AVAudioPlayer.FromData. This does have that limit of around 245 players. As a test, I tried up to 6000 AVAudioPlayers with NSData and they worked fine.