我一直在关注教程并查看其他帖子但我似乎无法在我的应用启动时自动开始播放音频。
我希望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 :(得分:0)
在 ViewController.h
中实施 AVAudioPlayerDelegate@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];
}
}