iPhone:AVAudioPlayer不支持的文件类型 [英] iPhone: AVAudioPlayer unsupported file type

查看:182
本文介绍了iPhone:AVAudioPlayer不支持的文件类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序从我们的服务器下载一个mp3并将其播放回用户。该文件是64 kbps(如果我理解正确,这完全在iPhone的可接受范围内)。我已经查询了如何在数十个网站上执行此操作,他们都建议我这样做:

My app downloads an mp3 from our server and plays it back to the user. The file is 64 kbps (which is well within the acceptable range for iPhone if I understand correctly). I have looked up how to do this on dozens of sites and they all suggest that i do exactly this:

NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://.../file.mp3"]];
NSError *e = nil;
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithData:data error&e];
[player setDelegate:self];

当我运行代码时,播放器返回null并且我收到此错误:

When I run the code, player comes back null and I get this error:

2011-02-04 10:44:46.176 MyApp[6052:207] Error loading audio: Error Domain=NSOSStatusErrorDomain Code=1954115647 "The operation couldn’t be completed. (OSStatus error 1954115647.)"
2011-02-04 10:44:49.647 MyApp[6052:207] unsupported file type

我检查了文件,我知道它有效。它将在Windows Media Player和Mac上的Quicktime上没有问题。我还将文件上传到iPhone模拟器,它没有任何问题。文件很好,但由于某种原因,AVAudioPlayer不喜欢它。

I have checked the file and I know that it works. It will play with no problems on Windows Media Player, and Quicktime on mac. I have also uploaded the file to the iPhone emulator and it plays with no problems whatsoever. The file is fine, but for some reason AVAudioPlayer doesn't like it.

我需要改变一些东西吗? NSData是否有某种设置来指定它是什么类型的文件?有没有人有任何想法?

Is there something I need to change? Is there some kind of setting for NSData to specify what kind of file it is? Does anyone have any idea?

推荐答案

最后我找到了解决这个问题的方法!我没有使用NSData对象初始化音频播放器,而是将文件保存到Documents文件夹,然后使用文件URL初始化播放器

At long last i have found a solution to this problem! Instead of initializing the audio player with the NSData object, I saved the file to the Documents folder, and then initialized the player with the file URL

//download file and play from disk
NSData *audioData = [NSData dataWithContentsOfURL:someURL];
NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@.mp3", docDirPath , fileName];
[audioData writeToFile:filePath atomically:YES];

NSError *error;
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
if (player == nil) {
    NSLog(@"AudioPlayer did not load properly: %@", [error description]);
} else {
    [player play];
}

当应用程序完成文件后,可以将其删除。希望他的帮助不仅仅是我!

When the app is done with the file, it can be deleted. Hope that his helps more than just me!

这篇关于iPhone:AVAudioPlayer不支持的文件类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆