Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play audio file ios

I am trying to play an audio file but I can get it working. I imported the AVFoundation framework.

Here is the code:

NSString *fileName = [[NSBundle mainBundle] pathForResource:@"Alarm" ofType:@"caf"];
    NSURL *url = [[NSURL alloc] initFileURLWithPath:fileName];
    NSLog(@"Test: %@ ", url);

    AVAudioPlayer *audioFile = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
    audioFile.delegate = self;
    audioFile.volume = 1;

    [audioFile play];

I am receiving an error nil string parameter

I copied the file to the supporting files folder so the file is there.

Can you guys help me?

Thanks

like image 311
Camus Avatar asked Dec 13 '25 19:12

Camus


1 Answers

Just follow two simple steps

Step1:

UIViewController.h

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

@property(nonatomic, retain) AVAudioPlayer *player;

Step 2:

UIViewController.m

NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"sound" 
                                                      ofType:@"m4a"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];

 _player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
[_player setVolume:1.0];
[_player play];

Just make sure AVAudioPlayer property must be nonatomic and retain.

like image 77
Rizwan Shah Avatar answered Dec 15 '25 12:12

Rizwan Shah



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!