0

我正在尝试播放 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");
}

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

4

1 回答 1

2

试试这个

视图控制器.h

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

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

@end

视图控制器.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");
}
于 2013-09-21T14:27:02.197 回答