Play a Short Sound in 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

How to play a sound using Swift?

Most preferably you might want to use AVFoundation.
It provides all the essentials for working with audiovisual media.

Update: Compatible with Swift 2, Swift 3 and Swift 4 as suggested by some of you in the comments.


Swift 2.3

import AVFoundation

var player: AVAudioPlayer?

func playSound() {
let url = NSBundle.mainBundle().URLForResource("soundName", withExtension: "mp3")!

do {
player = try AVAudioPlayer(contentsOfURL: url)
guard let player = player else { return }

player.prepareToPlay()
player.play()

} catch let error as NSError {
print(error.description)
}
}

Swift 3

import AVFoundation

var player: AVAudioPlayer?

func playSound() {
guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return }

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

let player = try AVAudioPlayer(contentsOf: url)

player.play()

} catch let error {
print(error.localizedDescription)
}
}

Swift 4 (iOS 13 compatible)

import AVFoundation

var player: AVAudioPlayer?

func playSound() {
guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return }

do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)

/* The following line is required for the player to work on iOS 11. Change the file type accordingly*/
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)

/* iOS 10 and earlier require the following line:
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) */

guard let player = player else { return }

player.play()

} catch let error {
print(error.localizedDescription)
}
}

Make sure to change the name of your tune as well as the extension.
The file needs to be properly imported (Project Build Phases > Copy Bundle Resources). You might want to place it in assets.xcassets for
greater convenience.

For short sound files you might want to go for non-compressed audio formats such as .wav since they have the best quality and a low cpu impact. The higher disk-space consumption should not be a big deal for short sound files. The longer the files are, you might want to go for a compressed format such as .mp3 etc. pp. Check the compatible audio formats of CoreAudio.


Fun-fact: There are neat little libraries which make playing sounds even easier. :)

For example: SwiftySound

Play continuous short sound without lagging UI animation

I figured it out.

Use a timer to play sound at 0 volumn every 1 second forever to keep the audio session alive. It sounds stupid but it works like a charm!

iOS: Play short sounds in the background every 2 minutes

I have found the solution myself, thanks everybody tryed to help me ;) To play the sound in the background more then once you have to use AVAudioPlayer add audio as a supported backgroundmode and add this method to - (void)viewDidLoad

[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

Creating and playing a sound in swift

Here's a bit of code I've got added to FlappySwift that works:

import SpriteKit
import AVFoundation

class GameScene: SKScene {

// Grab the path, make sure to add it to your project!
var coinSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "coin", ofType: "wav")!)
var audioPlayer = AVAudioPlayer()

// Initial setup
override func didMoveToView(view: SKView) {
audioPlayer = AVAudioPlayer(contentsOfURL: coinSound, error: nil)
audioPlayer.prepareToPlay()
}

// Trigger the sound effect when the player grabs the coin
func didBeginContact(contact: SKPhysicsContact!) {
audioPlayer.play()
}

}

Playing sound effect in Xcode

You could just initialize the audioPlayer in Play method instead of viewDidLoad.

override func viewDidLoad() {
super.viewDidLoad()
}

@IBAction func Play(_ sender: Any) {
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "1", ofType: "mp3")!))
audioPlayer.prepareToPlay()
audioPlayer.play()
} catch {
print(error)
}
}

What's the SIMPLEST way to play a sound clip in an iPhone app?

Apple has an article on this subject, see: this link

AVAudioPlayer is the simplest way to play sounds of any length, looping or not, however it requires iPhone OS 2.2 or higher. A simple example:

NSString *soundFilePath =
[[NSBundle mainBundle] pathForResource: @"sound"
ofType: @"wav"];

NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];

AVAudioPlayer *newPlayer =
[[AVAudioPlayer alloc] initWithContentsOfURL: fileURL
error: nil];
[fileURL release];

[newPlayer play];

[newPlayer release];

It will play virtually any file format (aiff,wav,mp3,aac) Keep in mind that you can only play one mp3/aac file at a time.



Related Topics



Leave a reply



Submit