我正在尝试播放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");
}
现在的问题是如何播放以前的音乐?
答案 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");
}