用AVFoundation播放wav声音文件

时间:2011-11-30 08:57:02

标签: ios xcode avfoundation wav

我正在使用AVFoundation来播放wav文件。但我无法发挥它。也没有出现任何错误或警告。

XCode是4.2,设备是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];

}

2 个答案:

答案 0 :(得分:5)

这是解决方案;

我在头文件中设置了AVAudioPlayer ..

@property(nonatomic,retain)AVAudioPlayer * theAudio;

我猜'保留'解决了我的问题。因为在我发送“播放”之后,它发送“释放”来平衡分配。取消分配AVAudioPlayer后,它将停止播放音频。

答案 1 :(得分:4)

我遇到了与Xcode 4.5相同的问题。使AVAudioPlayer成为一个强类型属性使它发挥作用。

因此需要在@interface中添加以下代码:

@property (nonatomic, strong) AVAudioPlayer *theAudio;

@implementation将成为:

- (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];

}