AVAudioPlayer没有播放长音?

时间:2015-06-03 11:42:29

标签: ios audio avaudioplayer

我有一系列声音文件,范围从0.3秒到3.0秒。

当尝试使用AVAudioPlayer时,我什么也得不到,除非我之后添加了sleep(4)来确保声音可以播放。真的很奇怪。

除此之外,传入的错误参数没有错误,[player play]每次都返回YES。但是,奇怪的是,没有调用委托方法。

这是我的代码。

(。m档案)

@interface MyClass ()
@property (nonatomic, strong) AVAudioPlayer *soundPlayer;
@end

@implementation SLInspireKit
//view did load here

- (void)playRandomSound {
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];

    NSError *error;

    NSString *musicFileName = [NSString stringWithFormat:@"my-sound-%d.aiff", arc4random_uniform(8)];
    NSString *path = [NSString stringWithFormat:@"%@/%@", [[NSBundle mainBundle] resourcePath], musicFileName];
    NSURL *soundUrl = [NSURL fileURLWithPath:path];

    self.soundPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:&error];
    self.soundPlayer.delegate = self;
    [self.soundPlayer setVolume:1.0];
    [self.soundPlayer prepareToPlay];

    if ([self.soundPlayer play]){
        NSLog(@"Played fine");
    } else {
        NSLog(@"Did not play fine");
    }
    sleep(1); //uncomment this out, and nothing. Set to 1, first second of each sound, 2, 2 seconds and so on. 

}

有什么想法吗?我不认为它是ARC的东西,但它可能是:/我必须每次都启动,因为声音每次都会改变。

1 个答案:

答案 0 :(得分:1)

评论的快速摘要: 由于整个包含AVAudioPlayer的类已被释放,因此需要睡眠(n)。

保留课程可以解决问题。

干杯!

相关问题