Playing wav sound file with AVFoundation

心已入冬 提交于 2019-12-10 10:18:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!