使用AVAudioPlayer播放多首音乐

时间:2013-09-21 13:49:47

标签: iphone ios objective-c xcode ipad

我正在尝试播放2个音乐,他们应该使用循环选项,

互相播放
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    NSString * music = [[NSBundle mainBundle] pathForResource:@"music" ofType:@"wav"];
    myMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:music] error:NULL];
    myMusic.delegate = self;
   [myMusic play];

}

播放第二首音乐:

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {

    NSString * music = [[NSBundle mainBundle] pathForResource:@"music2" ofType:@"wav"];
    myMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:music] error:NULL];
    myMusic.delegate = self;
    [myMusic play];

    NSLog(@"MUSIC FINISH");
}

现在的问题是如何播放以前的音乐?

1 个答案:

答案 0 :(得分:2)

试试这个

<强> ViewController.h

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

@interface ViewController : UIViewController<AVAudioPlayerDelegate>
{
AVAudioPlayer *player;
int nIndex;
NSArray *arrPlayList;
}

@end

<强> ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
[super viewDidLoad];
arrPlayList =[[NSArray alloc]initWithObjects:@"music1.wav",@"music2.wav",@"music3.wav", nil];
nIndex =[arrPlayList count]-1;
[self playSound:nIndex];
}

-(void)playSound:(int )index
{

    NSString *path = [[NSBundle mainBundle] bundlePath];
    NSString *strFilePath = [path stringByAppendingPathComponent:[arrPlayList objectAtIndex:index]];
    NSURL *filePath = [NSURL fileURLWithPath:strFilePath];
    player= [[AVAudioPlayer alloc] initWithContentsOfURL:filePath error:nil];
    player.delegate=self;
    [player play];

}



#pragma mark - AVFoundation Delegate Methods

-(void)audioPlayerDidFinishPlaying: (AVAudioPlayer *)player successfully:(BOOL)flag
{
NSLog(@"MUSIC FINISH");
if (nIndex==0) {
    return;
}
nIndex--;
[self playSound:nIndex];
}
-(void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error
{
NSLog(@"Decode Error occurred");
}