iOS按钮不在按钮点击上播放音频文件

brn*_*792 0 iphone xcode objective-c uibutton ios

这是一个新手问题.

我有一个非常简单的应用程序,当点击主视图上的按钮时,它应该只播放音频文件.

我正在使用XCode版本4.6.

我在我的项目中添加了一个音频文件'audioclip.wav'.我添加了AVFoundation.framework.

我的项目只有ViewController.hViewController.m.

我双击并从故事板中的按钮拖动到.h文件,使用助理编辑器创建我的IBAction连接.

我的ViewController.h:

#import <UIKit/UIKit.h>
#import<AVFoundation/AVAudioPlayer.h>

@interface ViewController : UIViewController <AVAudioPlayerDelegate> {
}
- (IBAction)playAudio:(id)sender;

@end
Run Code Online (Sandbox Code Playgroud)

我的ViewController.m:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)playAudio:(id)sender {
    AVAudioPlayer *audioPlayer;
    NSString *audioPath = [[NSBundle mainBundle] pathForResource:@"audioclip" ofType:@"wav" ];
    NSURL *audioURL = [NSURL fileURLWithPath:audioPath];
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:nil];
    [audioPlayer play];
}

@end
Run Code Online (Sandbox Code Playgroud)

无论出于何种原因(可能是我遗漏的东西)当我点击按钮时,audioclip.wav文件无法播放.我已经在iPhone 6.1模拟器和我的设备上进行了测试.

rde*_*mar 6

我认为wav文件存在一些问题.有些人似乎让它工作,但我尝试了几个不同的文件,但没有一个播放.在下面的代码中注释掉的mp3和m4a文件运行正常.没有必要对委托做任何事情,它是可选的.

    #import "ViewController.h"
    #import <AVFoundation/AVFoundation.h>

    @interface ViewController ()
    @property (strong,nonatomic) AVAudioPlayer *audioPlayer;
    @end

    @implementation ViewController


    - (IBAction)playAudio:(id)sender {
        //NSString *audioPath = [[NSBundle mainBundle] pathForResource:@"11 Prayer" ofType:@"mp3" ];
       //NSString *audioPath = [[NSBundle mainBundle] pathForResource:@"Sunshine" ofType:@"m4a" ];
        NSString *audioPath = [[NSBundle mainBundle] pathForResource:@"space" ofType:@"wav" ];
        NSURL *audioURL = [NSURL fileURLWithPath:audioPath];
        NSError *error;
        self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&error];
        [self.audioPlayer play];
    }
Run Code Online (Sandbox Code Playgroud)

如果我记录错误,我得到的wav文件:

Error Domain=NSOSStatusErrorDomain Code=1685348671 "The operation couldn’t be completed. (OSStatus error 1685348671.)"
Run Code Online (Sandbox Code Playgroud)