wake-up-neo.net

Wie kann ich mit Swift 4 einen Sound auf iOS 11 abspielen? Und wo lege ich die MP3-Datei ab?

Ich habe eine Menge Tutorials gesehen, aber wenn ich auf die Schaltfläche klicke (die den Funksound aktiviert, wird der Sound nicht aktiviert) Ich habe gesehen, dass der Code von stackoverflow empfohlen wurde, aber nichts. Ich legte die MP3-Datei info asset.xcasset. Es ist richtig?

3
Angelo Volpe

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)
    }
}
8
Arpit Jain

Swift 4.2/XCODE 10.1

Beachten Sie, dass Sie AVAudioSession.sharedInstance().setCategory() mit dem Parameter mode in Swift 4.2 aufrufen müssen.

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)
    }
}
4
Robert Nelson

Eine sehr einfache Lösung.

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

}

Spielen Sie diese Audiodatei jetzt überall ab, indem Sie Folgendes aufrufen: playAudioFile()

2
amritpandey

Fügen Sie Ihre .mp3-Datei zu Bundle hinzu

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()
1
Suresh Vutukuru

Sie können auch einen Timer setzen, um den Fortschritt der Musik abzuspielen

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

}

0
pravasi steffi

Einfacher Weg mit Swift 4.2 :

import AVFoundation

und 

   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 :(
       } 
   }
0
Sunil Targe