Jak odtworzyć dźwięk za pomocą Swift?

Chciałbym odtworzyć dźwięk za pomocą Swifta.

Mój kod działał w Swift 1.0, ale teraz nie działa już w Swift 2 lub nowszym.

override func viewDidLoad() {
    super.viewDidLoad()

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

    do { 
        player = try AVAudioPlayer(contentsOfURL: url, fileTypeHint: nil) 
    } catch _{
        return
    }

    bgMusic.numberOfLoops = 1
    bgMusic.prepareToPlay()


    if (Data.backgroundMenuPlayed == 0){
        player.play()
        Data.backgroundMenuPlayed = 1
    }
}
Author: Moritz, 2015-08-16

8 answers

Najlepiej użyć AVFoundation. Zapewnia wszystkie niezbędne elementy do pracy z mediami audiowizualnymi.

Aktualizacja: kompatybilny z Swift 2, Swift 3 i Swift 4 zgodnie z sugestią niektórych z Was w komentarzach.


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)
    }
}

W tym celu należy skontaktować się z Działem Obsługi Klienta.]}
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)



        /* 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)
    }
}

upewnij się, że zmienisz nazwa Twojego utworu oraz rozszerzenie . plik musi być poprawnie zaimportowany (Project Build Phases > Copy Bundle Resources). Możesz umieścić go w assets.xcassets dla większa wygoda.

W przypadku krótkich plików dźwiękowych warto wybrać nieskompresowane formaty audio, takie jak .wav, ponieważ mają one najlepszą jakość i niski wpływ na procesor. Większe zużycie miejsca na dysku nie powinno być wielką sprawą dla krótkich plików dźwiękowych. Im dłuższe są pliki, możesz chcieć iść dla formatu skompresowanego, takiego jak .mp3 itp. pp. Sprawdź kompatybilne Formaty audio z CoreAudio.


Ciekawostka: istnieją zgrabne małe biblioteki, które sprawiają, że odtwarzanie dźwięków jest jeszcze łatwiejsze. :)
Na przykład: SwiftySound

 155
Author: Devapploper,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-10 03:18:43

Dla Swift 3 :

import AVFoundation

/// **must** define instance variable outside, because .play() will deallocate AVAudioPlayer 
/// immediately and you won't hear a thing
var player: AVAudioPlayer?

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

    do {
        /// this codes for making this app ready to takeover the device audio
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true)

        /// change fileTypeHint according to the type of your audio file (you can omit this)

        player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3)

        // no need for prepareToPlay because prepareToPlay is happen automatically when calling play()
        player!.play()
    } catch let error as NSError {
        print("error: \(error.localizedDescription)")
    }
}

Najlepszą praktyką dla zasobów lokalnych jest umieszczenie go w assets.xcassets i załadowanie pliku w następujący sposób:

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

    do {
        /// this codes for making this app ready to takeover the device audio
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true)

        /// change fileTypeHint according to the type of your audio file (you can omit this)

        /// for iOS 11 onward, use :
        player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)

        /// else :
        /// player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3)

        // no need for prepareToPlay because prepareToPlay is happen automatically when calling play()
        player!.play()
    } catch let error as NSError {
        print("error: \(error.localizedDescription)")
    }
}
 37
Author: Adi Nugroho,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-07 06:17:14

IOS 12-Xcode 10 beta 6-Swift 4.2

Użyj tylko 1 IBAction i skieruj wszystkie przyciski do tej 1 Akcji.

import AVFoundation

    var player = AVAudioPlayer()

@IBAction func notePressed(_ sender: UIButton) {

        print(sender.tag) // testing button pressed tag

        let path = Bundle.main.path(forResource: "note\(sender.tag)", ofType : "wav")!
        let url = URL(fileURLWithPath : path)

        do {
            player = try AVAudioPlayer(contentsOf: url)
            player.play()

        } catch {

            print ("There is an issue with this code!")

        }

}
 6
Author: Tony Ward,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-27 05:07:47

Jeśli kod nie generuje żadnego błędu, ale nie słyszysz dźwięku - Utwórz odtwarzacz jako instancję:

   static var player: AVAudioPlayer!

Dla mnie pierwsze rozwiązanie zadziałało, gdy zrobiłem tę zmianę:)

 3
Author: EranKT,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-18 18:45:12

Swift 3

import AVFoundation


var myAudio: AVAudioPlayer!

    let path = Bundle.main.path(forResource: "example", ofType: "mp3")!
    let url = URL(fileURLWithPath: path)
do {
    let sound = try AVAudioPlayer(contentsOf: url)
    myAudio = sound
    sound.play()
} catch {
    // 
}

//If you want to stop the sound, you should use its stop()method.if you try to stop a sound that doesn't exist your app will crash, so it's best to check that it exists.

if myAudio != nil {
    myAudio.stop()
    myAudio = nil
}
 2
Author: Mr.Shin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-03 06:10:32

Swift 4 (kompatybilny z iOS 12)

    var player: AVAudioPlayer?

    let path = Bundle.main.path(forResource: "note\(sender.tag)", ofType: "wav")
    let url = URL(fileURLWithPath: path ?? "")

    do {
        player = try AVAudioPlayer(contentsOf: url)
        player?.play()
    } catch let error {
        print(error.localizedDescription)
    }
 1
Author: imdpk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-18 18:31:45
func playSound(_ buttonTag : Int){

    let path = Bundle.main.path(forResource: "note\(buttonTag)", ofType : "wav")!
    let url = URL(fileURLWithPath : path)

    do{
        soundEffect = try AVAudioPlayer(contentsOf: url)
        soundEffect?.play()
        // to stop the spound .stop()
    }catch{
        print ("file could not be loaded or other error!")
    }
}

Działa w najnowszej wersji swift 4. ButtonTag będzie znacznikiem na przycisku w interfejsie. Notatki znajdują się w folderze równoległym do głównego.storyboard. Każda nuta nosi nazwę note1, note2 itd. ButtonTag daje liczbę 1, 2 itd. z klikniętego przycisku, który jest przekazywany jako param

 0
Author: Egi Messito,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-14 14:23:19

Najpierw zaimportuj te biblioteki

import AVFoundation

import AudioToolbox    

Ustaw delegata w ten sposób

   AVAudioPlayerDelegate

Napisz ten ładny kod na akcji przycisku lub coś w tym stylu:

guard let url = Bundle.main.url(forResource: "ring", withExtension: "mp3") else { return }
    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true)
        player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
        guard let player = player else { return }

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

100% Praca w moim projekcie i przetestowane

 0
Author: Mr.Javed Multani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-08 07:07:55