【问题标题】:AVAudioPlayer is nil after viewDidLoadviewDidLoad 后 AVAudioPlayer 为零
【发布时间】:2014-03-03 02:33:34
【问题描述】:

我正在使用最新的 Xcode,Xcode 5.0.2,我用 iPad Simulator 7.0 测试它,我的音频文件 是 m4a,在我的 iPad 上用 GarageBand 导入和编写的,但是当我尝试播放它时,它运行了 nil,我将 AVFoundation.framework 导入到我的项目中,这里是 .h 文件

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface NastyCansViewController : UIViewController
{
AVAudioPlayer *audioPlayer;
}
@end

这是 .m 文件。我使用 NSLog 来查看我的 audioPlayer 是否为 nil。

- (void)viewDidLoad
{
    NSURL *songURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/song.m4a"], NSBundle mainBundle] resourcePath];
    NSError * error
    audioPlayer = [[AVAudioPlayer alloc] initWithContentOfURL:songURL error:&error];
    if (audioPlayer == nil) {
        NSLog(@"audioPlayer is nil");
    }
}

当我运行应用程序时,出现 NSLog 并显示“audioPlayer is nil” 我也尝试了很多其他代码,但我得到的都是零,请帮忙,谢谢

【问题讨论】:

  • 在您尝试创建AVAudioPlayer 后是否设置了error?如果是这样,它告诉你什么?

标签: ios iphone avaudioplayer null


【解决方案1】:

替换

NSLog(@"audioPlayer is nil");

使用以下代码获取错误信息:

NSLog(@"audioPlayer init error:%@", error); 

试试这个来实现这个功能:

NSString *urlStr = [[NSBundle mainBundle] pathForResource:@"song" ofType:@"m4a"];
NSError *error = nil;
NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:urlStr]
                                             options:NSDataReadingMappedIfSafe
                                               error:&error];
audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:&error];
if (audioPlayer == nil) {
    NSLog(@"audioPlayer is init error:%@", error);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-06
    • 2012-08-30
    • 1970-01-01
    相关资源
    最近更新 更多