2011-09-30 144 views
0

我需要播放短暫的聲音。這是我寫的無法播放聲音(wav)事件

在我的頭我的代碼有:

#import <AVFoundation/AVFoundation.h> 

@interface AddItemController : UIViewController < ... , AVAudioPlayerDelegate> { 
... 
AVAudioPlayer *audio; 
} 

... 
@property (nonatomic, retain) IBOutlet AVAudioPlayer *audio; 

@end 

在.m文件:

- (void)playSound { 
    NSURL *url; 
    if (error) { 
     url =[NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Resources/error.wav"]]; 
    } else { 
     url =[NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Resources/finished.wav"]]; 
    } 
    audio = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil]; 
    audio.delegate = self; 
    [audio play]; 
} 

-(IBAction)addItem:(id)sender { 
    if (...) { 
     error = true; 
     [self playSound]; 
     return; 
    } 

    ... 

    error = false; 
    [self playSound]; 
} 

沒有警告也沒有問題的代碼。所有其他功能正在工作。只是我聽不到任何聲音。

好的!我自己找到了解決方案。對不起,如果我困擾你。

希望我的解決方案對別人有用。

- (void)playSound 
{ 
    NSURL *url; 

    NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"error.aif"]; 

    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) { 
     url = [NSURL fileURLWithPath:path]; 
     audio = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil]; 
     [audio prepareToPlay]; 
    } 
    [audio play]; 
} 

回答

0

你可能想看看的AudioServicesCreateSystemSoundIDAudioServicesPlaySystemSound功能,從AudioToolbox框架。

+0

AVSudioPlayer無意以任何方式呈現播放器,您正在考慮使用AVPlayer。 –

+0

Ooops,我的壞...更正了答案,Thanx ...:) – Macmade

+0

Ehm,我的解決方案是對還是錯? – Oiproks