Iphone 如何在我的应用程序启动后自动播放音乐?

Iphone 如何在我的应用程序启动后自动播放音乐?,iphone,ios,xcode,audio,Iphone,Ios,Xcode,Audio,我需要一些关于我最近启动的应用程序的帮助。我是一个非常大的初学者编码,所以请帮助我,这将意味着很多。当用户进入我的应用程序时,我需要一段音乐来播放,我已经学习了其他youtube教程,但它们只适用于较旧的Xcode版本,因此非常感谢您的帮助。您可以使用AVAudioPlayer。使用起来非常简单: NSURL *path = [[NSURL alloc] initFileURLWithPath:[DataPersister getQualifiedPathForFileInDirectory:D

我需要一些关于我最近启动的应用程序的帮助。我是一个非常大的初学者编码,所以请帮助我,这将意味着很多。当用户进入我的应用程序时,我需要一段音乐来播放,我已经学习了其他youtube教程,但它们只适用于较旧的Xcode版本,因此非常感谢您的帮助。

您可以使用
AVAudioPlayer
。使用起来非常简单:

NSURL *path = [[NSURL alloc] initFileURLWithPath:[DataPersister getQualifiedPathForFileInDirectory:DataPersisterPathBundle fileName:@"music.mp3"]];
NSError *outError;

AVAudioPlayer *musicSound = [[AVAudioPlayer alloc] initWithContentsOfURL:path error:&outError];
[musicSound play];
[path release];
记住输入

#import <AVFoundation/AVFoundation.h>
#导入

把它放在你的
应用程序已经启动了,但一定要在你的.h和.m中实例化它

像这样的事情可以解决你的问题:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
    resourcePath = [resourcePath stringByAppendingString:@"/YOURMUSICNAME.wav"];
    NSLog(@"Path to play: %@", resourcePath);
    NSError* err;

    //Initialize our player pointing to the path to our resource
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:
                 [NSURL fileURLWithPath:resourcePath] error:&err];

    if( err ){
        //bail!
        NSLog(@"Failed with reason: %@", [err localizedDescription]);
    }
    else{
        //set our delegate and begin playback
        player.delegate = self;
        [player play];
        player.numberOfLoops = -1;
        player.currentTime = 0;
        player.volume = 1.0;
    }
}
如果你想阻止它:

[player stop];
或者暂停:

[player pause];
并将其导入头文件:

#import <AVFoundation/AVFoundation.h>
//m

-(BOOL)应用程序:(UIApplication*)应用程序完成启动时使用此选项:(NSDictionary*)启动选项
方法肯定会播放音乐


快乐编码;)

把你的mp3放在AppDidFinishLaunch怎么样我应该在哪里申报播放器?因为现在它出现了一个错误,上面写着“使用未声明的标识符‘player’”,谢谢,如果我声明了它,我会将它连接到故事板中的任何东西吗?检查我编辑的答案,如果你仍然遇到问题,请告诉我谢谢你的帮助,我已经按照你说的做了,所有的错误都消失了,但是当我模拟它时,没有播放音乐,你想看看代码还是类似的东西??)谢谢
AVAudioPlayer *player;
}
@property (nonatomic, retain) AVAudioPlayer *player;
@synthesize player;
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/MUSIC.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = -1;
[audioPlayer play];
audioPlayer.volume = 1.0;
audioPlayer.currentTime = 2;