Xcode中无法得到的声音文件,AVAudioPlayer
我是新来的iOS,并试图将声音添加到我的应用程序玩。我遵循了几个关于将简单声音文件添加到我的项目的教程,但所有结果都相同。我没有错误,但没有声音播放。关于我做错什么的想法?任何帮助,将不胜感激!Xcode中无法得到的声音文件,AVAudioPlayer
- (IBAction)playSound:(id)sender {
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSLog(soundFilePath);
NSError *error;
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:&error];
player.numberOfLoops = 1;
[player play];
}
**UPDATE* **
所以我从来没有与上面的代码,这是非常令人沮丧的任何运气,但我并结束了它前往使用AudioToolbox框架改为使用:
SystemSoundID soundID;
NSString *soundFile = [[NSBundle mainBundle]
pathForResource:@"test" ofType:@"mp3"];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)
[NSURL fileURLWithPath:soundFile], & soundID);
AudioServicesPlaySystemSound(soundID);
任何人都可以向我解释差异,为什么这一个工程,其他不?我比任何事都好奇。会喜欢一些澄清。
终于明白了。我需要在我的头文件中为AVAudioPlayer创建一个属性才能使它工作。以下是我所做的:
// .h file
@interface ThirdViewController : UIViewController {
AVAudioPlayer *audioPlayer;
}
@property (nonatomic, retain) AVAudioPlayer *audioPlayer;
- (void) playSound //method in .m file
{
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:@"test"
ofType:@"mp3"]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
[audioPlayer play];
}
做后续的简化代码。也可以将test.mp3放到xcode中项目目录的根目录下。您的mp3位置和位置非常重要。此外,请确保音量已关闭,并且设备的振动已关闭,且未被静音。
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:@"test"
ofType:@"mp3"]];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:nil];
[audioPlayer play];
仍然没有运气。我的“test.mp3”文件位于根目录中。我试图从我的模拟器运行它。确认音量开启,静音关闭。 – mablecable 2013-03-25 19:23:21
你用真实的设备试过了吗? – neutrino 2013-03-25 19:32:14
还没有。首先尝试让它在模拟器中工作,就像教程示例一样 – mablecable 2013-03-25 19:43:13
确保安装quartz.h或支持音频播放器的特定框架。请仔细检查。
过去有同样的问题,框架必须正确安装。
您是否尝试过与任何其他应用程序打请将test.mp3?只是为了看到文件没有问题... – neutrino 2013-03-25 19:22:32
XCode不能播放声音文件的方式是什么?你会得到什么错误?你是否意味着你正在开发使用XCode,并且你的程序不能播放声音? – marko 2013-03-25 19:50:38