问题
I am trying to pause the AVAudioPlayer
if it is currently playing. When I debug my code and check AVAudioPlayer
, I see it is allocated. When I try to access a method/property on it (i.e. myAudioPlayer isPlaying
), I get an EXC_BAD_ACCESS
error. This happens if the AVAudioPlayer
does not have a sound loaded. Is there a way I can do a check to see if it has loaded a sound? I tried accessing myAudioPlayer.data
, but I still get the same error.
回答1:
I guess you have to use prepareToPlay method to find whether it has loaded or not.
回答2:
For me it was because I wasn't calling the one of the designated initialisers. I was instantiating it with AVAudioPlayer()
instead of the designated initialisers which are public init(contentsOfURL url: NSURL) throws
and public init(data: NSData) throws
回答3:
As of iOS 13, make sure you are removing the initialization on AVAudioPlayer before asigning it with AVAudioPlayer(contentsOf: URL(...))
i.e. change
var audioPlayer = AudioPlayer()
to var audioPlayer: AVAudioPlayer!
回答4:
First you have to add AVFoundation Framework.Then,import AVFounadtion framework in .h file.
.h:
AVAudioPlayer *audioPlayer;
.m:
NSURL *url1 = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/audio1.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url1 error:&error];
//audioPlayer.numberOfLoops = 0;
[audioPlayer play];
Try this code it may help you..
来源:https://stackoverflow.com/questions/7670430/avaudioplayer-exc-bad-access