使用AVFoundation播放wav音频文件

3

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

}

确保您不会忽略任何可能的错误(因为您在initWithContentsOfUrl调用中)。使用正确的NSError对象并将其结果打印到控制台。 - Till
请检查是否忘记添加音频基础框架。 - slonkar
@SumitLonkar:已经仔细检查过了 :) - Quaso
@Till仍然没有错误。`NSError *audioError = nil;AVAudioPlayer *theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&audioError]; if(audioError != nil) { NSLog(@"发生音频错误:\"%@\"", audioError); } else { [theAudio prepareToPlay]; [theAudio play]; }` - Quaso
WAV是一种我实际上不会使用的格式 - 尝试将该文件转换为AIFF或CAF并使用结果。WAV容器格式有时会出现一些轻微的不规则性,导致播放失败。 - Till
将它们转换为CAF文件格式,但问题未得到解决。 - Quaso
2个回答

5

以下是解决方案:

我在头文件中设置了AVAudioPlayer。

@property (nonatomic, retain) AVAudioPlayer *theAudio;

我猜想,'retain'修饰符解决了我的问题。因为当我发送“play”时,它会发送“release”来平衡分配的内存。当AVAudioPlayer被释放时,它停止播放音频。


如果我通过选择MPMediaPickerController上传音频文件,然后在后台播放。音乐缩略图不会显示在主屏幕上。如何解决这个问题? - amisha.beladiya

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

}

如果您使用弱属性(或局部变量)并且正在使用ARC,则iOS将检测到没有强指针指向AVAudioPlayer对象,并在您希望删除该对象之前释放它。强指针会保留对象,防止其被删除,直到您明确地将属性设置为nil。 - Steve Liddle

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接