4

我已经尝试了这里找到的所有不同选项,甚至使用 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];

}

任何帮助是极大的赞赏。我已经被这些困住了太久了。

提前谢谢你。

4

2 回答 2

17

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

@property (strong, nonatomic)  AVAudioPlayer * newAudio;

如果你在方法中声明了 AVAudioPlayer,它会在方法执行后立即释放,没有足够的时间发出声音。

于 2013-09-27T04:15:05.300 回答
2

我试过这样,我能够在 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];
}
于 2013-10-07T05:57:59.210 回答