Playing back audio using AVAudioPlayer iOS 7

旧街凉风 提交于 2019-11-27 09:52:56

You're having an ARC issue here. myPlayer is being cleaned up when it's out of scope. Create a strong property, assign the AVAudioPlayer and you're probably all set!

@property(nonatomic, strong) AVAudioPlayer *myPlayer;

...

// create new audio player
self.myPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:nil];
[self.myPlayer play];

Is the filePath coming back with a valid value? Is the fileURL coming back with a valid value? Also, you should use the error parameter of AVAudioPlayer initWithContentsOfURL. If you use it it will likely tell you EXACTLY what the problem is.

Make sure you check for errors and non-valid values in your code. Checking for nil filepath and fileURL is the first step. Checking the error parameter is next.

Hope this helps.

What I do is create an entire miniature class just for this purpose. That way I have an object that I can retain and which itself retains the audio player.

- (void) play: (NSString*) path {
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: path];
    NSError* err = nil;
    AVAudioPlayer *newPlayer =
        [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: &err];
    // error-checking omitted
    self.player = newPlayer; // retain policy
    [self.player prepareToPlay];
    [self.player setDelegate: self];
    [self.player play];
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!