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

时间:2017-12-03 14:56:41

标签: ios audio

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

7 个答案:

答案 0 :(得分:9)

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

答案 1 :(得分:4)

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

答案 2 :(得分:2)

一个非常简单的解决方案。

import AVFoundation

var myAudioPlayer = AVAudioPlayer?

func playAudioFile() {

    let audioFileURL = Bundle.main.url(forResource: "<name-of-file>", withExtension: "mp3/wav/m4a etc.")

    do {
        try myAudioPlayer = AVAudioPlayer(contentsOf: audioFileURL!)
    } catch let error {
        print(error.localizedDescription)
    }

    myAudioPlayer?.play()

}

现在,通过调用:playAudioFile()

在任何地方播放此音频文件

答案 3 :(得分:1)

将.mp3文件添加到Bundle

import AVFoundation

let url = Bundle.main.url(forResource: "SampleAudio", withExtension: "mp3")

    let playerItem = AVPlayerItem(url: url!)
    let player=AVPlayer(playerItem: playerItem)
    let playerLayer=AVPlayerLayer(player: player)

    playerLayer.frame = CGRect(x: 0, y: 0, width: 0, height: 0)
    self.view.layer.addSublayer(playerLayer)
    player.play()

答案 4 :(得分:0)

您还可以设置一个计时器来显示播放音乐的进度

import AVFoundation

class ViewController: UIViewController {
var player : AVAudioPlayer?
var timer : Timer?
@IBOutlet var pauseBtn: UIButton!
@IBOutlet var replayBtn: UIButton!
@IBAction func rewind2(_ sender: Any) {

}
@IBAction func forward(_ sender: Any) {
    var time : TimeInterval = (player?.currentTime)!
    time += 5.0
    if (time > (player?.duration)!)
    {
        // stop, track skip or whatever you want
    }
    else
    {
        player?.currentTime = time
    }
}
@IBOutlet var progress: UIProgressView!
@IBAction func playClicked(_ sender: Any) {
    if player == nil {
        let resource = Bundle.main.url(forResource: "audioFX", withExtension: "mp3")
        do {
            player = try AVAudioPlayer(contentsOf: resource!)
            player?.isMeteringEnabled = true
            player?.prepareToPlay()
        } catch let error {
            print(error)

        }
    }
    if player != nil {
        player?.play()
        enableTimer()
        player!.delegate = self as? AVAudioPlayerDelegate
    }
}
@IBAction func pauseClicked(_ sender: Any) {
    if(player != nil){
        if(player?.isPlaying == true){
            endTimer()
            player!.pause()
            pauseBtn.setTitle("Resume", for: .normal)
        }else{
            player!.play()
            enableTimer()
            pauseBtn.setTitle("Stop", for: .normal)
        }

    }
}
@IBAction func replayClicked(_ sender: Any) {
    if player != nil{
        endTimer()
        player = nil
        pauseBtn.setTitle("Stop", for: .normal)
        playClicked(replayBtn)
    }
}

override func viewDidLoad() {
    super.viewDidLoad()


}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
func enableTimer(){
    if(player != nil){
        timer = Timer(timeInterval: 0.1, target: self, selector: (#selector(self.updateProgress)), userInfo: nil, repeats: true)
        RunLoop.main.add(timer!, forMode: RunLoopMode(rawValue: "NSDefaultRunLoopMode"))
    }
}
func endTimer(){
    if(timer != nil){
        timer!.invalidate()
    }
}

@objc func updateProgress(){
    if(player != nil){
        player!.updateMeters() //refresh state
        progress.progress = Float(player!.currentTime/player!.duration)
    }
}

}

答案 5 :(得分:0)

  

使用 Swift 4.2 的简单方法:

import AVFoundation

   let soundEffect = URL(fileURLWithPath: Bundle.main.path(forResource: "btn_click_sound", ofType: "mp3")!)
   var audioPlayer = AVAudioPlayer()

   @IBAction func buttonClick(sender: AnyObject) {
       do {
            audioPlayer = try AVAudioPlayer(contentsOf: soundEffect)
            audioPlayer.play()
       } catch {
          // couldn't load file :(
       } 
   }

答案 6 :(得分:-1)

Swift 4.1 Xcode 9.4.1

import UIKit
import AVFoundation

class ViewController: UIViewController, AVAudioPlayerDelegate {

    var audioPlayer: AVAudioPlayer!

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


// playing sound on tap of this button
    @IBAction func buttonPressed(_ sender: UIButton) {

    // setting up url for your soundtrack
        let soundURL = Bundle.main.url(forResource: “soundTrackName”, withExtension: “soundTrackExtension”)
        do {
    // setting up audio player to play your sound
            audioPlayer = try AVAudioPlayer(contentsOf: soundURL!)
        } catch  {
    // in case any errors occur
            print(error)
        }

    // playing your audio file
        audioPlayer.play()
    }
}