繁体   English   中英

用AVFoundation播放wav声音文件

[英]Playing wav sound file with AVFoundation

我正在使用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];

}

这是解决方案;

我在头文件中设置AVAudioPlayer ..

@property(nonatomic,retain)AVAudioPlayer * theAudio;

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

我在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];

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM