Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping Audio with AudioToolbox.framework

I have would like to play audio on the startup of my app, but, first of all, the audio doesn't play! No matter how i code it. And secondly I would love to loop it if i can.

@implementation ViewController

-(void)awakeFromNib
{
    SystemSoundID soundID;
    NSString *soundFile1 = [[NSBundle mainBundle] pathForResource:@"ScaryMusic" ofType:@"mp3"];
    AudioServicesCreateSystemSoundID((__bridge CFURLRef) [NSURL fileURLWithPath:soundFile1], &soundID);

    AudioServicesPlaySystemSound(soundID);
    NSLog(@"Sound Played");

}
like image 756
Brandon Boynton Avatar asked Aug 12 '26 19:08

Brandon Boynton


1 Answers

Try this instead:

#import <AVFoundation/AVFoundation.h>

AVAudioPlayer *player;
NSURL *soundFileURL = [[NSBundle mainBundle] URLForResource:@"ScaryMusic" withExtension:@"mp3"];
if (soundFileURL != nil)
{
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
    player.numberOfLoops = -1; //infinite
}

[player play];

This is better for mp3's and such. SystemSound is mostly reserved for short .wav type sounds.

like image 85
Aeramor Avatar answered Aug 15 '26 09:08

Aeramor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!