如何使用swift 4在iOS 11上播放声音?我在哪里放置mp3文件?

Ang*_*lpe 4 audio ios

我看了很多教程,但是当我点击按钮(这就是func playsound)时声音没有播放.我看到stackoverflow推荐的代码但没有.我把mp3文件信息asset.xcasset.这是正确的?

Arp*_*ain 10

SWIFT 4/XCODE 9.1

import AVFoundation

var objPlayer: AVAudioPlayer?

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

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

        // For iOS 11 
        objPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)

        // For iOS versions < 11 
        objPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) 

        guard let aPlayer = objPlayer else { return }
        aPlayer.play()

    } catch let error {
        print(error.localizedDescription)
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 6

SWIFT 4.2 / XCODE 10.1

请注意,您必须在Swift 4.2中AVAudioSession.sharedInstance().setCategory()使用mode参数进行调用 。

import AVFoundation

var audioPlayer: AVAudioPlayer?

func playSound() {
    if let audioPlayer = audioPlayer, audioPlayer.isPlaying { audioPlayer.stop() }

    guard let soundURL = Bundle.main.url(forResource: "audio_file", withExtension: "wav") else { return }

    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, mode: AVAudioSession.Mode.default)
        try AVAudioSession.sharedInstance().setActive(true)
        audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
        audioPlayer?.play()
    } catch let error {
        Print.detailed(error.localizedDescription)
    }
}
Run Code Online (Sandbox Code Playgroud)