2013-07-03 2 views
0

AVAudioPlayer에 init 메소드를 통해 재생할 파일의 URL 만 지정할 수 있습니다. 그리고 다른 파일을 재생하고 싶다면 이전 인스턴스를 재생하지 말고 AVAudioPlayer의 새 인스턴스를 재생할 새 오디오 파일의 URL로 초기화해야합니다.iOS : AVAudioPlayer는 하나의 파일 만 재생할 수 있습니까?

그러나 이것은 내비게이션 컨트롤러가 있기 때문에 어렵게 만들고, 사용자가 플레이어 화면을 떠날 때 사운드는 계속 재생되어야하며 그렇지 않습니다. 그러나 사용자가 tableview에서 재생할 새 오디오 파일을 선택하면 viewController 및 AVAudioPlayer의 새 인스턴스가 초기화되고 이전 재생을 중지 할 방법이 없습니다. 어떻게 작동합니까?

+0

당신은 어딘가에있는'AVAudioPlayer'를 추적 할 필요가 있습니다 (그리고 한 번에 하나의 파일 만 재생하기를 원하기 때문에, * one *'AVAudioPlayer' 만 추적하면됩니다). 대답을 제안하거나 테이블보기 자체에서 –

답변

0

당신은 당신의 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]; 
} 
+0

하지만 "NSString * soundFilePath = [[NSBundle mainBundle] pathForResource : @"시작 소리 "ofType : @"m4a "];" 이제는 URL을 변경할 수 없으므로 "StartSound"만 재생합니다. –