AVAudioPlayer stops playing immediately with ARC

后端 未结 3 1259
心在旅途
心在旅途 2020-11-30 12:55

I am trying to play an MP3 via AVAudioPlayer which I thought to be fairly simple. Unfortunately, it\'s not quite working. Here is all I did:

  • For t
3条回答
  •  悲哀的现实
    2020-11-30 13:22

    If you need multiple AVAudioPlayers playing at the same time, create a NSMutableDictionary. Set the key as the filename. Remove from Dictionary via Delegate Callback like so:

    -(void)playSound:(NSString*)soundNum {
    
    
        NSString* path = [[NSBundle mainBundle]
                          pathForResource:soundNum ofType:@"m4a"];
        NSURL* url = [NSURL fileURLWithPath:path];
    
        NSError *error = nil;
        AVAudioPlayer *audioPlayer =[[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    
        audioPlayer.delegate = self;
    
        if (_dictPlayers == nil)
            _dictPlayers = [NSMutableDictionary dictionary];
        [_dictPlayers setObject:audioPlayer forKey:[[audioPlayer.url path] lastPathComponent]];
        [audioPlayer play];
    
    }
    
    -(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {        
       [_dictPlayers removeObjectForKey:[[player.url path] lastPathComponent]];
    }
    

提交回复
热议问题