2013-06-26 168 views
-4

我想在應用程序啓動時播放聲音,然後讓用戶有機會通過「停止」按鈕暫停聲音。我怎樣才能做到這一點?如何在應用程序啓動時播放音頻文件

我實際的代碼是:

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

這是非常糟糕的格式,沒有詳細的信息和沒有事先研究的跡象。 -1 –

+0

很差的問題,請清楚你想要的東西。 – sagarcool89

回答

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]; 
    } 
相關問題