Play a short sound in iOS Play a short sound in iOS ios ios

Play a short sound in iOS


Every single one of the other answers leaks memory (unless ARC is enabled for one of the answers)... oddly, the answer originally marked as correct has a call to retainCount for no apparent reason.

If you alloc/init something, it needs to be released (unless you are using ARC).

If you call AudioServicesCreateSystemSoundID() you have to dispose of the resulting sound.

See the Audio UI Sounds example.

Basically:

@interface MyClass:UI*ViewController // fixed{     SystemSoundID mySound;}@implementation MyClass- (void) viewDidLoad {    [super viewDidLoad];    AudioServicesCreateSystemSoundID(.... URL ...., &mySound);}- (void) playMySoundLikeRightNowReally {    AudioServicesPlaySystemSound(mySound);}- (void) dealloc {   AudioServicesDisposeSystemSoundID(mySound);   [super dealloc]; // only in manual retain/release, delete for ARC}@end

For completeness:
add AudioToolbox.framework
#import <AudioToolbox/AudioToolbox.h>


For short sound clips (less than 30 secs), there's a SystemSounds library which is really nice.

Pros:You don't need to manage volume settings separately. The sound is played in a separate thread and loading and playing of audio clip is v fast. In short, you treat this clip as another system sound.

Cons: You can't provide a separate audio control setting. It's tied to the settings of the system sounds. You can't play more than 30 seconds. You probably can't apply any sound filters to enhance audio effect.

There are certainly more pros and cons, but these are some I could think of, off the top of my head.

use this import: <AudioToolbox/AudioToolbox.h>Add the AudioToolbox Frameworkthen call the below method like [self playSound], wherever you want to play the clip.

-(void) playSound {    NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"changeTrack" ofType:@"aif"];    SystemSoundID soundID;    AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath: soundPath], &soundID);    AudioServicesPlaySystemSound (soundID);    [soundPath release];}


Swift

The other answers here use Objective-C so I am providing a Swift version here. Swift uses Automatic Reference Counting (ARC), so I am not aware of any memory leak issues with this answer (as warned about in the accepted answer).

Using AudioToolbox

You can use the AudioToolbox framework to play short sounds when you do not need much control over how they are played.

Here is how you would set it up:

import UIKitimport AudioToolboxclass PlaySoundViewController: UIViewController {    var soundURL: NSURL?    var soundID: SystemSoundID = 0        @IBAction func playSoundButtonTapped(sender: AnyObject) {                let filePath = NSBundle.mainBundle().pathForResource("yourAudioFileName", ofType: "mp3")        soundURL = NSURL(fileURLWithPath: filePath!)        if let url = soundURL {            AudioServicesCreateSystemSoundID(url, &soundID)            AudioServicesPlaySystemSound(soundID)        }    }}

Notes:

  • This example is adapted from How to play a short sound clip with AudioToolbox in Swift.
  • Remember to add yourAudioFileName.mp3 (or .wav, etc) to your project.
  • Remember to import AudioToolbox
  • This answer puts the code in an IBAction button tap, but it could just as easily be put in another function, of course.

Using AVAudioPlayer

By importing the AVFoundation framework, you can use AVAudioPlayer. It works for both short audio clips and long songs. You also have more control over the playback than you did with the AudioToolbox method.

Here is how you would set it up:

import UIKitimport AVFoundationclass PlaySoundViewController: UIViewController {        var mySound: AVAudioPlayer?        // a button that plays a sound    @IBAction func playSoundButtonTapped(sender: AnyObject) {        mySound?.play() // ignored if nil    }        override func viewDidLoad() {        super.viewDidLoad()                // initialize the sound        if let sound = self.setupAudioPlayerWithFile("yourAudioFileName", type: "mp3") {            self.mySound = sound        }    }        func setupAudioPlayerWithFile(file: NSString, type: NSString) -> AVAudioPlayer? {                let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)        let url = NSURL.fileURLWithPath(path!)        var audioPlayer: AVAudioPlayer?        do {            try audioPlayer = AVAudioPlayer(contentsOfURL: url)        } catch {            print("Player not available")        }                return audioPlayer    }}

Notes: