【问题标题】:AVFoundation - iOS can't hear soundAVFoundation - iOS 听不到声音
【发布时间】:2012-09-19 15:49:24
【问题描述】:

我正在尝试使用 AVFoundation 框架播放 mp3 文件。它无法检测到文件并出现以下错误:

     Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSURL initFileURLWithPath:]: nil string parameter'

实现的代码:

NSString *path = [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"mp3"];
NSLog(@"directory %@",path);
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
[theAudio play];

当我将 pathForResource:@"sound" 更改为 pathForResource:@"sound" (空格)时,它可以检测到文件但听不到声音。我也在 .h 文件中声明了 AVdelegate。有谁知道是什么问题?

【问题讨论】:

标签: ios xcode audio avfoundation


【解决方案1】:

您需要先准备好准备播放音频才能播放..检查此代码 sn-p.. 它适用于我。

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3", fileName]];

NSError        *err;

if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) 
{    
    AVAudioPlayer  *player = [[AVAudioPlayer alloc] initWithContentsOfURL:
              [NSURL fileURLWithPath:filePath] error:&err];

    player.delegate = self;

    [player prepareToPlay];
    [player setNumberOfLoops:0];
    [player setVolume:0.5];
    [player play];    

}

【讨论】:

  • prepareToPlay 有助于减少声音开始播放所需的时间,但实际上并不是必需的。此外,OP 无法从应用程序包中播放声音,而不是 NSDocumentDirectory。也许你可以编辑这个来帮助 OP :)
  • 你好 NSPostWhenldle 你说的 OP 是什么意思?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-14
相关资源
最近更新 更多