24

I'm trying to get an audio file playing in my iOS app. This is my current code

NSString *soundFilePath = [NSString stringWithFormat:@"%@/test.m4a", [[NSBundle mainBundle] resourcePath]];

NSLog(@"%@",soundFilePath);
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];

audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

[audioPlayer setVolume:1.0];

audioPlayer.delegate = self;

[audioPlayer stop];
[audioPlayer setCurrentTime:0];
[audioPlayer play];

I've being checking a bunch of other posts but they all generally do the same thing. I'm not getting an error, but I don't hear any audio playing on the simulator or device.

This is the path I get for the audio file on the simulator

/Users/username/Library/Application Support/iPhone Simulator/5.1/Applications/long-numbered-thing/BookAdventure.app/test.m4a

Any help is appreciated!

Lagoo87
  • 621
  • 1
  • 6
  • 20
  • Try another audio file, its possible that test.m4a might be corrupted, which is why it isn't playing. – WhoaItsAFactorial Jul 17 '12 at 15:36
  • Does `audioPlayer` point to a valid object? Is the mute switch on? Device volume turned up? – Caleb Jul 17 '12 at 15:38
  • I'm pretty sure it's a valid object. Is there a way to tell if the path is correct? I assumed it would throw an error if it was a null object or invalid path.. The mute switch is not on and device volume is turned up @Jeremy1026 the file plays normally in xCode and on my MBP so I think it's fine – Lagoo87 Jul 17 '12 at 16:37
  • Are you using ARC in this project? – Jonathan Grynspan Jul 17 '12 at 17:07
  • have you figured this out? @Lagoo87 – 4GetFullOf Jan 21 '14 at 22:00
  • Yes- The code shown works fine. There was an issue with the type of file. I found mp3 worked, but issues with m4a. Haven't tested/tried it since the issue! – Lagoo87 Jan 22 '14 at 21:30

7 Answers7

54

Maybe you should try using the NSBundle method pathForResource:ofType: method to create the path to the file.

The following code should successfully play an audio file. I have only used it with an mp3, but I imagine it should also work with m4a. If this code does not work, you could try changing the format of the audio file. For this code, the audio file is located in the main project directory.

/* Use this code to play an audio file */
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"test"  ofType:@"m4a"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];

AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
player.numberOfLoops = -1; //Infinite

[player play];

EDIT

Ok, so try this:

NSString *soundFilePath = [NSString stringWithFormat:@"%@/test.m4a",[[NSBundle mainBundle] resourcePath]];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];

AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
player.numberOfLoops = -1; //Infinite

[player play];

Also, make sure you do the proper imports:

#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
Community
  • 1
  • 1
bddicken
  • 1,412
  • 1
  • 15
  • 16
  • when I do that, my soundFilePath ends up being (null)...? My file is in the main project directory. In xCode its under the group "Audio", which I don't think matters. – Lagoo87 Jul 17 '12 at 18:52
  • You could try my code, but using your path creation method (eg NSString *soundFilePath = [NSString stringWithFormat:@"%@/test.m4a", [[NSBundle mainBundle] resourcePath]];) instead. Also, what does an NSLog of your soundFilePath print? – bddicken Jul 17 '12 at 19:58
  • 1
    sound file path is printing (null) every time When I use this other path creation method, my soundFilePath shows "file://localhost/Users/userName/Library/Application%20Support/iPhone%20Simulator/5.1/Applications/long-number-thing-here/BookAdventure.app/test.m4a" – Lagoo87 Jul 17 '12 at 20:04
  • I added another slightly modified code snippet to my response, try that. – bddicken Jul 17 '12 at 20:13
  • 1
    Had the proper imports already. Weird, .mp3 works but .m4a isn't working. Not sure why, but just happy I got some audio playing! – Lagoo87 Jul 17 '12 at 20:24
  • 8
    FYI AudioToolbox import is not required for these snippets :) – Luke Oct 19 '12 at 07:50
30

You need to store a strong reference to 'AVAudioPlayer'

@property (strong) AVAudioPlayer *audioPlayer;

And if you are sure that your audio file is in following Bundle Resources, it should play.

Project>Build Phases>Copy

Hima
  • 1,249
  • 1
  • 14
  • 18
  • 2
    I was having pretty much the same issue and making sure that I kept a reference to the player object solved the problem. Which variation of how the player gets created withUrl, etc. was NOT the problem but just the fact that the reference to the player was lost as the method/scope in which it was being instantiated finished. – Chris Amelinckx May 15 '14 at 10:55
21

To play file with extension .caf, .m4a, .mp4, .mp3,.wav, .aif


Download following two files from GitHub

SoundManager.h
SoundManager.m

Add these files to your project

Also add audio files to resource folder (sample files)

mysound.mp3, song.mp3

Import header file in desired file

#import "SoundManager.h"

And add following two lines in -(void)viewDidLoad

[SoundManager sharedManager].allowsBackgroundMusic = YES;
[[SoundManager sharedManager] prepareToPlay];

Use following line to play sound (mysound.mp3)

[[SoundManager sharedManager] playSound:@"mysound" looping:NO];

Use following line to stop the sound (mysound.mp3)

[[SoundManager sharedManager] stopSound:@"mysound"];

Also you can play music (song.mp3) as

[[SoundManager sharedManager] playMusic:@"song" looping:YES];

And can be stop music as

[[SoundManager sharedManager] stopMusic];

Complete Documentation is on GitHub

MD SHAHIDUL ISLAM
  • 14,325
  • 6
  • 82
  • 89
6

First import this framework to your file

#import <AVFoundation/AVFoundation.h>

Then declare an instance of AVAudioPlayer.

AVAudioPlayer *audioPlayer;

NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"Name of your audio file" 
                                                          ofType:@"type of your audio file example: mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
audioPlayer.numberOfLoops = -1;
[audioPlayer play];
Jagat Dave
  • 1,643
  • 3
  • 23
  • 30
Anooj VM
  • 2,593
  • 22
  • 19
  • 1
    Cool sample, bare minimum, for, say, have the functionality in place. A little clarification wrt _numbnerOfLoopsCounting_: (-1) -stands for infinity, 0 - for one and so on. I added a UIButton to run _[audioPlayer play];_ but it's up to user how to handle the code. I support your answer for brevity and user convenience standpoint! Thanks! – matrix3003 Dec 30 '15 at 03:17
0

To play your bundle audio file using below code if you generate the system sound ID

for(int i = 0 ;i< 5;i++)
{
    SystemSoundID   soundFileObject;
    NSString *audioFileName = [NSString stringWithFormat:@"Alarm%d",i+1];

    NSURL *tapSound   = [[NSBundle mainBundle] URLForResource: audioFileName
                                            withExtension: @"caf"];

    // Store the URL as a CFURLRef instance
    CFURLRef soundFileURLRef = (__bridge CFURLRef) tapSound;

    // Create a system sound object representing the sound file.
    AudioServicesCreateSystemSoundID (

                                  soundFileURLRef,
                                  &soundFileObject
                                  );
    [alarmToneIdList addObject:[NSNumber numberWithUnsignedLong:soundFileObject]];
}

You can play the sound by using below code

AudioServicesPlaySystemSound([[alarmToneIdList objectAtIndex:row]unsignedLongValue]);

To achieve this below framework need to add in your Xcode

AudioToolbox

Finally below header files are needs to be import in controller

#import AudioToolbox/AudioToolbox.h
#import AudioToolbox/AudioServices.h
P.J.Radadiya
  • 1,493
  • 1
  • 12
  • 21
Subathra D
  • 389
  • 3
  • 7
0

Updated for Swift 4 Playing from main bundle - iOS 11 only

import AVFoundation

var player: AVAudioPlayer?

The following code loads the sound file and plays it, returning an error if necessary.

guard let url = Bundle.main.url(forResource: "test", withExtension: "m4a") else { return }

    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true)

    guard let player = player else { return }

    player.play()

    } catch let error {
        // Prints a readable error
        print(error.localizedDescription)
    }
Niall Kiddle
  • 1,477
  • 1
  • 16
  • 35
0

Swift 4.2

var soundFilePath = "\(Bundle.main.resourcePath ?? "")/test.m4a"
var soundFileURL = URL(fileURLWithPath: soundFilePath)

var player = try? AVAudioPlayer(contentsOf: soundFileURL)
player?.numberOfLoops = -1 //Infinite

player?.play()
Til
  • 5,150
  • 13
  • 26
  • 34