应用程序在播放声音时崩溃

时间:2012-05-22 18:03:19

标签: ios avfoundation avaudioplayer

我正在使用AVFoundation framework播放声音。在文件的开头,我有:

#import <AVFoundation/AVAudioPlayer.h>

AVFoundation framework已正确添加到我的项目中。但是,当我使用此代码播放声音时,应用程序崩溃:

NSString *pathForBgMusicFile = [[NSBundle mainBundle] pathForResource:@"ClenchedTeeth" ofType:@"mp3"];
NSURL *bgMusicFile = [[NSURL alloc] initFileURLWithPath:pathForBgMusicFile];
AVAudioPlayer *bgMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:bgMusicFile error:NULL];
[bgMusic play];

有谁知道如何解决这个问题?提前谢谢!

3 个答案:

答案 0 :(得分:1)

#import <AudioToolbox/AudioToolbox.h>

和你的.m文件

FBundleRef mainBundle = CFBundleGetMainBundle();
        CFURLRef soundFileURLref;
        soundFileURLref = CFBundleCopyResourceURL(mainBundle ,(CFStringRef)@"yourSoundFile",CFSTR ("wav"),NULL);
        UInt32 soundID;
        AudioServicesCreateSystemSoundID(soundFileURLref, &soundID);
        AudioServicesPlaySystemSound(soundID);}

如果是你的情况,你可以在按钮内使用这个代码。不要忘记添加音频工具框架​​。祝你好运

答案 1 :(得分:0)

我不在我的Mac前面,试试这个(我只更改了第二行):

NSString *pathForBgMusicFile = [[NSBundle mainBundle] pathForResource:@"ClenchedTeeth" ofType:@"mp3"];
NSURL *bgMusicFile = [NSURL fileURLWithPath:pathForBgMusicFile];
AVAudioPlayer *bgMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:bgMusicFile error:NULL];
[bgMusic play];

答案 2 :(得分:0)

尝试播放之前,请尝试设置AVAudioSession。像这样:

  AVAudioSession *audioSession = [AVAudioSession sharedInstance];
  audioSession.delegate = self;
  [audioSession setActive:YES error:nil];
  [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];

请务必导入它,并确保您的类同时实现AVAudioPlayerDelegateAVAudioSessionDelegate