【问题标题】:AVAudioPlayer not working on iOS7AVAudioPlayer 在 iOS7 上不起作用
【发布时间】:2013-10-02 15:48:23
【问题描述】:

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

}

非常感谢任何帮助。我已经被这些卡住了太久了。

提前,谢谢。

【问题讨论】:

  • 究竟是什么不起作用?你说没有错误,那是什么问题?你听不到音频吗?您使用的是模拟器还是设备?
  • 实际上什么也没发生。没有声音,什么都没有。在模拟器和设备上。我使用了一个按钮来触发播放,该按钮禁用了几秒钟,然后再次启用,但没有任何反应。一点声音都没有。
  • 我还添加了以下代码,但仍然没有... AVAudioSession *audioSession = [AVAudioSession sharedInstance]; [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord 错误:无]; [audioSession setActive:YES error:nil];
  • 在上面的代码中,您立即开始使用 [newPlayer Play],所以如果您使用的是按钮,这不是您实际使用的代码吗?你有没有调试过按钮是否按照你的想法做,也许是在适当的地方设置几个断点。
  • 是的,我进行了调试,它遍历了所有代码行。在 [newPlayer Play] 之后,什么也没有发生。我认为这可能是一个代表问题。与其他一些代码相比,我缺少 newPlayer.Delegate = self;打算尝试一下,但与此同时你有一个想法,请分享。感谢您到目前为止的回复。

标签: ios7 avaudioplayer xcode5


【解决方案1】:

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

@property (strong, nonatomic)  AVAudioPlayer * newAudio;

如果你在一个方法中声明了AVAudioPlayer,它会在方法执行完毕后立即释放,来不及发声。

【讨论】:

  • 是的,你明白了。非常感谢。
【解决方案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];
}

【讨论】:

  • self.player 与将其声明为强属性相同。 ARC 要求范围超出此方法,否则将被释放
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-22
  • 2013-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多