如何在应用启动时播放音频文件

时间:2013-06-26 12:23:17

标签: ios objective-c

我想在应用启动时播放声音,然后让用户有机会通过“停止”按钮暂停声音。我怎么能这样做?

我的实际代码是:

player1 = [[AVAudioPlayer alloc]
          initWithContentsOfURL:[NSURL fileURLWithPath:
          [[NSBundle mainBundle] pathForResource:@"Startsound" ofType:@"m4a"]]error:nil];
player1.numberOfLoops=-1;
[player1 prepareToPlay];

1 个答案:

答案 0 :(得分:2)

这个问题扭曲了,我确实得到了他想说的话。

这是你如何做到的。在v1AppDelegate.h文件中添加

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#include <AudioToolbox/AudioToolbox.h>

@interface v1AppDelegate : UIResponder <UIApplicationDelegate>
{
    AVAudioPlayer *myAudioPlayer;
}

@property (nonatomic, retain) AVAudioPlayer *myAudioPlayer;

@property (strong, nonatomic) UIWindow *window;

@end

现在在v1AppDelegate.m文件中添加此

#import "v1AppDelegate.h"
#import <AVFoundation/AVFoundation.h>
#include <AudioToolbox/AudioToolbox.h>

@implementation v1AppDelegate

@synthesize window = _window;

@synthesize myAudioPlayer;


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

    //start a background sound
    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"Startsound" ofType: @"m4a"];
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath ];    
    myAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
    myAudioPlayer.numberOfLoops = -1; //infinite loop
    [myAudioPlayer play];


    // Override point for customization after application launch.
    return YES;
}

如果您希望从代码中的任何其他位置停止或启动此音乐,只需添加此

即可
#import "v1AppDelegate.h"    
- (IBAction)stopMusic
    {
        v1AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
        [appDelegate.myAudioPlayer stop];
    }


    - (IBAction)startMusic
    {
        v1AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
        [appDelegate.myAudioPlayer play];
    }