AVAudioPlayer不会出错但不播放声音

时间:2014-01-28 12:43:49

标签: ios objective-c xcode avaudioplayer

你好我对苹果开发是全新的

我在我的iPhone上运行代码没有错误,但我听不到声音   这是代码

-(void) buttonPressed1:(UIButton *)sender{  
    NSString *fileName = @"Record_000";
    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 prepareToPlay];
    [self.theAudio play];
}

这是我的文件

#import <AVFoundation/AVFoundation.h>
#import <UIKit/UIKit.h>
@interface StartPage : UIViewController
@property (nonatomic, strong) AVAudioPlayer *theAudio;
@end

1 个答案:

答案 0 :(得分:1)

尝试设置音频会话:

#import <AVFoundation/AVAudioSession.h>

    -(void) viewDidLoad
    {
        [super viewDidLoad];
        [self setAudioSession];
    }

    -(void) setAudioSession
    {
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        NSError *sessionError = nil;
        BOOL success = [audioSession setCategory:AVAudioSessionCategoryPlayback error:&sessionError];
        if (!success)
        {
            NSLog(@"Setting Audio Session Category Error: %@", sessionError);
        }
        success = [audioSession setActive:YES error:&sessionError];
        if (!success)
        {
            NSLog(@"Setting Audio Session Active Error: %@", sessionError);
        }
    }