Looping Audio in Xcode

点点圈 提交于 2019-12-01 20:40:29

Something like this should do your problem:

    NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
    resourcePath = [resourcePath stringByAppendingString:@"/YOURMUSICNAME.mp3"];
    NSLog(@"Path to play: %@", resourcePath);
    NSError* err;

    //Initialize our player pointing to the path to our resource
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:
                 [NSURL fileURLWithPath:resourcePath] error:&err];

    if( err ){
        //bail!
        NSLog(@"Failed with reason: %@", [err localizedDescription]);
    }
    else{
        //set our delegate and begin playback
        player.delegate = self;
        [player play];
        player.numberOfLoops = -1;
        player.currentTime = 0;
        player.volume = 1.0;
    }

Then if you want to stop it:

[player stop];

or pause it :

[player pause];

and also import it in your header file:

#import <AVFoundation/AVFoundation.h>.   

You should to ofcourse declare it in your header, then synthesize it.

//.h and add the bold part:

@interface ViewController : UIViewController <AVAudioPlayerDelegate> {

AVAudioPlayer *player;
}
@property (nonatomic, retain) AVAudioPlayer *player;

//.m

@synthesize player;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!