问题
I am using AVFoundation to play wav files. But i could not make it play. Also no errors or warnings showed up.
XCode is 4.2 and device is iOS 5.
- (IBAction) playSelectedAlarm:(id)sender {
UIButton *button = (UIButton *)sender;
int bTag = button.tag;
NSString *fileName = [NSString stringWithFormat:@"%d23333", bTag];
NSLog(@"%@", fileName);
NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:@"wav"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: path];
AVAudioPlayer *theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:NULL];
theAudio.volume = 1.0;
theAudio.delegate = self;
[theAudio prepareToPlay];
[theAudio play];
}
回答1:
Here is the solution;
I set AVAudioPlayer in header file..
@property (nonatomic, retain) AVAudioPlayer *theAudio;
i guess 'retain' is solved my problem. Because after i sending "play", it sends "release" to balance the alloc. When AVAudioPlayer is deallocated it stops playing audio.
回答2:
I have had the same issue with Xcode 4.5. Making the AVAudioPlayer into a strongly typed property made it play.
So the following code needs added to the @interface:
@property (nonatomic, strong) AVAudioPlayer *theAudio;
The @implementation would then become:
- (IBAction) playSelectedAlarm:(id)sender {
UIButton *button = (UIButton *)sender;
int bTag = button.tag;
NSString *fileName = [NSString stringWithFormat:@"%d23333", bTag];
NSLog(@"%@", fileName);
NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:@"wav"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: path];
self.theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:NULL];
self.theAudio.volume = 1.0;
self.theAudio.delegate = self;
[self.theAudio prepareToPlay];
[self.theAudio play];
}
来源:https://stackoverflow.com/questions/8323294/playing-wav-sound-file-with-avfoundation