iOS:AVAudioPlayer只能播放一个文件吗?

时间:2013-07-03 00:44:14

标签: ios objective-c avaudioplayer avaudiosession

只能通过init方法为AVAudioPlayer提供要播放的文件的URL。 据我所知,如果想要播放另一个文件,则需要停止播放旧实例,并使用新的音频文件的URL初始化AVAudioPlayer的新实例。

但这让我很难,因为我有一个导航控制器,当用户离开播放器屏幕时,声音应该继续播放,而确实如此。但是当用户从tableview中选择要播放的新音频文件时,viewController和AVAudioPlayer的新实例被初始化,我无法阻止旧的播放。我如何使这个工作?

1 个答案:

答案 0 :(得分: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];
}