Objective-C AVAudioPlayer无法播放声音。

4
我正在使用这个函数在我的iPhone应用程序上播放声音。问题是声音没有播放。该函数正常工作并正确读取文件路径,我没有收到任何错误信息,但声音没有播放。
-(void) playSound : (NSString *) fName; {
    if ([audioPlayer isPlaying]) {
        [audioPlayer stop];
    }
    audioPlayer.volume = 1.0;
    soundpath = [NSString stringWithFormat:@"sounds/%@", fName];
    soundFilePath = [[NSBundle mainBundle] pathForResource:soundpath  ofType: @"mp3"];
    soundURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
    NSError *error;
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:&error];
    audioPlayer.numberOfLoops = -1;
    if (audioPlayer == nil){

    }
else {
    [audioPlayer play];
        if ([audioPlayer isPlaying]) {
            NSLog(@"%@", @"run");
     }
}
}

你是否已经在某个地方完成了prepareForPlay:的操作?在使用类之前,一定要先阅读手册。 - DanSkeel
1个回答

5

试着添加这个:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive:YES error: nil];
UInt32 route = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof(route), &route);

我曾经遇到过类似的问题,而在调用播放之前添加了这个代码,这为我解决了问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接