अधिमानतः आप उपयोग करना चाह सकते हैं AVFoundation । यह दृश्य-श्रव्य मीडिया के साथ काम करने के लिए सभी आवश्यक चीजें प्रदान करता है।
अद्यतन: स्विफ्ट 2 , स्विफ्ट 3 और के साथ संगत स्विफ्ट 4 के जैसा कि आप में से कुछ ने टिप्पणियों में सुझाया है।
स्विफ्ट 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)
}
}
स्विफ्ट 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)
}
}
स्विफ्ट 4 (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)
}
}
विस्तार के साथ-साथ अपनी धुन का नाम भी बदलना सुनिश्चित करें ।
फ़ाइल को ठीक से आयात करने की आवश्यकता है ( Project Build Phases>Copy Bundle Resources )। आप इसे assets.xcassetsअधिक से अधिक सुविधा के लिए रखना चाह सकते हैं ।
छोटी ध्वनि फ़ाइलों के लिए आप गैर-संपीड़ित ऑडियो प्रारूपों के लिए जाना चाहते हैं जैसे कि .wavउनके पास सबसे अच्छी गुणवत्ता और कम सीपीयू प्रभाव है। उच्च डिस्क-स्थान की खपत कम ध्वनि फ़ाइलों के लिए एक बड़ी बात नहीं होनी चाहिए। जितनी लंबी फाइलें हैं, आप एक संपीड़ित प्रारूप जैसे .mp3पीपीपी आदि के लिए जाना चाहते हैं । संगत ऑडियो प्रारूपों की जांच करें की CoreAudio।
मौज-मस्ती: साफ सुथरी छोटी लाइब्रेरियां हैं जो बजाने की आवाज़ को और भी आसान बनाती हैं। :)
उदाहरण के लिए: स्विफ्टसाउंड