Preferibilmente potresti voler usare AVFoundation . Fornisce tutti gli elementi essenziali per lavorare con i media audiovisivi.
Aggiornamento: compatibile con Swift 2 , Swift 3 e Swift 4 come suggerito da alcuni di voi nei commenti.
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 (compatibile con iOS 13)
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)
}
}
Assicurati di cambiare il nome della tua melodia così come l' estensione .
Il file deve essere importato correttamente ( Project Build Phases> Copy Bundle Resources). Si consiglia di posizionarlo assets.xcassetsper maggiore comodità.
Per file audio brevi potresti voler scegliere formati audio non compressi, ad esempio .wavpoiché hanno la migliore qualità e un basso impatto sulla CPU. Il maggiore consumo di spazio su disco non dovrebbe essere un grosso problema per i file audio brevi. Più i file sono lunghi, potresti voler scegliere un formato compresso come .mp3ecc. Pp. Controlla i formati audio compatibili di CoreAudio.
Curiosità: ci sono piccole librerie ordinate che rendono la riproduzione dei suoni ancora più semplice. :)
Ad esempio: SwiftySound