AVAudioPlayer 无法在 iOS7 上运行



我已经尝试了这里找到的所有不同选项,甚至使用 NSData 加载音频文件。我已经尝试了mp3,m4a,caf文件,但没有任何效果。

没有错误消息,什么都没有。

这是一个使用XCODE 5,iOS7的新应用程序。

这就是我正在使用的

- (void)playOnce:(NSString *)aSound
{

    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker error:nil];
    [audioSession setActive:YES error:nil];
    // Gets the file system path to the sound to play.
    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:aSound ofType:@"m4a"];
    // Converts the sound's file path to an NSURL object
    NSURL *soundURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
    AVAudioPlayer * newAudio=[[AVAudioPlayer alloc] initWithContentsOfURL: soundURL error:nil];

    [newAudio prepareToPlay];
    // set it up and play
    [newAudio setNumberOfLoops:0];
    [newAudio setVolume: 1];
    [newAudio setDelegate: self];
    [newAudio play];
}

任何帮助将不胜感激。我已经被这些困住了太久了。

提前,谢谢。

您需要在视图控制器中将AVAudioPlayer声明为强引用@property,如下所示

@property (strong, nonatomic)  AVAudioPlayer * newAudio;

如果您在方法中声明 AVAudioPlayer,它将在方法执行后立即发布,没有足够的时间发出声音。

我尝试过这样,我能够在iOS 7中播放音频文件

- (void)viewDidLoad {
  [super viewDidLoad];
  NSURL* url = [[NSBundle mainBundle] URLForResource:@"DR" withExtension:@"mp3"];
  NSAssert(url, @"URL is valid."); 
  NSError* error = nil;
  self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
  if(!self.player) {
    NSLog(@"Error creating player: %@", error);
  }
  self.player.delegate = self;
  [self.player prepareToPlay];
}
- (IBAction)playAction:(id)sender {
   [self.player play];
}

最新更新