2013-03-15 173 views
0

我一直在关注教程,看着其他帖子,但我似乎无法让音频在我的应用程序启动时自动开始播放。我的ios应用程序启动时如何播放音频?

我想让wav文件继续在后台播放和循环播放。我不想要启动和停止控制等...

下面是我在我的ViewController.m文件中的代码(这是正确的地方?),我已经添加了AVFoundation.frameowrk并将其导入到我的。 m文件。此外,我已将我的名为AlienRoom的wav文件添加到我的支持文件中。任何帮助都是极好的!我是新人,所以请一步一步来,或者如果可以的话,让它真正清楚。谢谢!!!

p.s.我没有添加代码来使它循环,所以任何帮助都会很棒!

//play background sound upon opening app 

-(void) awakeFromNib 

{ 

NSString *path = [[NSBundle mainBundle] pathForResource: @"AlienRoom" ofType: @"wav"]; 
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; 
[theAudio play]; 
} 
+0

ü要播放的声音,而应用程序从睡眠状态唤醒?或只是第一个应用程序加载? – 2013-03-15 01:08:03

+0

任何时候出现主视图时,我都希望背景音频连续播放。所以在第一次开放或返回到这个观点。 – Herbie999 2013-03-15 01:09:27

回答

0

实施AVAudioPlayerDelegateViewController.h

@interface ViewController : UIViewController <AVAudioPlayerDelegate> 

@property(nonatomic,strong)AVAudioPlayer *theAudio; 

ViewController.m文件

-(void)viewWillAppear:(BOOL)animated 
{ 
    NSString *path = [[NSBundle mainBundle] pathForResource: @"AlienRoom" ofType: @"wav"]; 
    if(!self.theAudio) 
     self.theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; 
    self.theAudio.delegate = self; 
    [self.theAudio play]; 
} 

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)data successfully:(BOOL)flag{ 

    [NSThread detachNewThreadSelector:@selector(playAudioAgain) toTarget:self withObject:nil]; 

} 

- (void)playAudioAgain{ 

    [self.theAudio play]; 
} 

-(void)viewWillDisappear:(BOOL)animated 
{ 
    if(self.theAudio.isPlaying) 
    { 
     self.theAudio.delegate = nil; 
     [self.theAudio stop]; 
    } 
} 
+0

感谢您的帮助!你是说要把我的ViewController.h文件中的代码?我在那里和在.m上试过,但它似乎不起作用。 – Herbie999 2013-03-15 01:21:55

+0

加载ViewController.h后,你做了什么?显示另一个视图?目前的模型视图还是其他? – 2013-03-15 01:23:58

+0

我编辑了答案.. plz检查它 – 2013-03-15 01:29:55

相关问题