0

我有以下代码,并且找到了 sound_file。我也没有错误。音频文件被添加到包中。但是我在 iOS 模拟器上没有声音。

- (void)playNotificationSound
{
    NSString *sound_file;
    AVAudioPlayer * audioPlayer;

    sound_file = [[NSBundle mainBundle] pathForResource:@"onebell" ofType:@"caf"];
    if (sound_file){

        NSURL *url = [[NSURL alloc] initFileURLWithPath:sound_file];
        NSError *error;
        audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
        //audioPlayer.delegate = self;
        audioPlayer.volume = 1.0f;
        [audioPlayer prepareToPlay];
        [audioPlayer play];
    }
}
4

1 回答 1

0

您需要对您的AVAudioPlayer. 因为您使用的是 ARC,并且在您完成执行AVAudioPlayer后不会存在于内存中。playNotificationSound对它的字符串引用可以阻止它被释放。

只需添加一个@property (strong, nonatomic) AVAudioPlayer *audioPlayer;And 使用self.audioPlayer而不是声明一个新AVAudioPlayer变量。

于 2013-09-17T02:47:50.887 回答