code

Swift를 사용하여 사운드를 재생하는 방법은 무엇입니까?

codestyles 2020. 8. 17. 08:59
반응형

Swift를 사용하여 사운드를 재생하는 방법은 무엇입니까?


Swift를 사용하여 소리를 재생하고 싶습니다.

내 코드는 Swift 1.0에서 작동했지만 이제 Swift 2 이상에서는 더 이상 작동하지 않습니다.

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

가장 바람직하게는 AVFoundation 을 사용할 수 있습니다 . 시청각 미디어 작업에 필요한 모든 것을 제공합니다.

업데이트 : 의견에서 일부가 제안한대로 Swift 2 , Swift 3Swift 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)
    }
}

Swift 4 (iOS 12 호환)

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경우 최상의 품질과 낮은 CPU 영향을 제공하기 때문에 압축되지 않은 오디오 형식 을 사용하는 것이 좋습니다. 짧은 사운드 파일의 경우 더 높은 디스크 공간 소비가 큰 문제는 아닙니다. 파일의 길이가 길수록 압축 된 형식을 사용하는 것이 .mp3좋습니다. pp. 호환되는 오디오 형식확인하세요 CoreAudio.


재미있는 사실 : 사운드를 더 쉽게 연주 할 수있는 깔끔한 작은 라이브러리가 있습니다. :)
예 : SwiftySound


대한 스위프트 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)")
    }
}

로컬 자산에 대한 모범 사례는이를 내부에 넣고 다음 assets.xcassets과 같이 파일을로드하는 것입니다.

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

iOS 12-Xcode 10 베타 6-Swift 4.2

1 개의 IBAction 만 사용하고 모든 버튼을 1 개의 액션으로 지정합니다.

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!")

        }

}

코드에서 오류가 발생하지 않지만 소리가 들리지 않는 경우 플레이어를 인스턴스로 만듭니다.

   static var player: AVAudioPlayer!

나를 위해이 변경을 수행했을 때 첫 번째 솔루션이 작동했습니다. :)


스위프트 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
}

먼저이 라이브러리를 가져옵니다.

import AVFoundation

import AudioToolbox    

이렇게 대리자를 설정하십시오.

   AVAudioPlayerDelegate

버튼 동작이나 뭔가 동작에이 예쁜 코드를 작성하십시오.

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 % 내 프로젝트에서 작업하고 테스트했습니다.


Swift 4 및 iOS 12로 테스트되었습니다.

import UIKit
import AVFoundation
class ViewController: UIViewController{
    var player: AVAudioPlayer!
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    func playTone(number: Int) {
        let path = Bundle.main.path(forResource: "note\(number)", ofType : "wav")!
        let url = URL(fileURLWithPath : path)
        do {
            player = try AVAudioPlayer(contentsOf: url)
            print ("note\(number)")
            player.play()
        }
        catch {
            print (error)
        }
    }

    @IBAction func notePressed(_ sender: UIButton) {
        playTone(number: sender.tag)
    }
}

신속하게 매우 간단한 코드

Xcode에 오디오 파일을 추가하고 주어진 코드를 제공하십시오

import AVFoundation

class ViewController: UIViewController{

   var audioPlayer = AVAudioPlayer() //declare as Globally

   override func viewDidLoad() {
        super.viewDidLoad()

        guard let sound = Bundle.main.path(forResource: "audiofilename", ofType: "mp3") else {
            print("error to get the mp3 file")
            return
        }
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: sound))
        } catch {
            print("audio file error")
        }
        audioPlayer.play()
    }



@IBAction func notePressed(_ sender: UIButton) { //Button action
    audioPlayer.stop()
}

Swift 4 (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)
}

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

신속한 4 최신 버전에서 작동합니다. ButtonTag는 인터페이스의 버튼에있는 태그입니다. 메모는 Main.storyboard와 평행 한 폴더의 폴더에 있습니다. 모든 노트의 이름은 note1, note2 등으로 지정됩니다. ButtonTag는 클릭 한 버튼에서 1, 2 등의 번호를 부여하며 매개 변수로 전달됩니다.


import UIKit
import AVFoundation

class ViewController: UIViewController{

    var player: AVAudioPlayer?

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

    @IBAction func notePressed(_ sender: UIButton) {

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

        do {
            try AVAudioSession.sharedInstance().setCategory((AVAudioSession.Category.playback), mode: .default, options: [])
            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.wav.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)
        }

    }

}

Swift 4, 4.2 및 5

URL 및 프로젝트 (로컬 파일)에서 오디오 재생

import UIKit
import AVFoundation

class ViewController: UIViewController{

var audioPlayer : AVPlayer!

override func viewDidLoad() {
        super.viewDidLoad()
// call what ever function you want.
    }

    private func playAudioFromURL() {
        guard let url = URL(string: "https://geekanddummy.com/wp-content/uploads/2014/01/coin-spin-light.mp3") else {
            print("error to get the mp3 file")
            return
        }
        do {
            audioPlayer = try AVPlayer(url: url as URL)
        } catch {
            print("audio file error")
        }
        audioPlayer?.play()
    }

    private func playAudioFromProject() {
        guard let url = Bundle.main.url(forResource: "azanMakkah2016", withExtension: "mp3") else {
            print("error to get the mp3 file")
            return
        }

        do {
            audioPlayer = try AVPlayer(url: url)
        } catch {
            print("audio file error")
        }
        audioPlayer?.play()
    }

}

게임 스타일 :

Sfx.swift 파일

import AVFoundation

public let sfx = Sfx.shared
public final class Sfx: NSObject {

    static let shared = Sfx()

    var apCheer: AVAudioPlayer? = nil

    private override init() {
        guard let s = Bundle.main.path(forResource: "cheer", ofType: "mp3") else {
            return  print("Sfx woe")
        }
        do {
            apComment = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: s))
        } catch {
            return  print("Sfx woe")
        }
    }

    func cheer() { apCheer?.play() }
    func plonk() { apPlonk?.play() }
    func crack() { apCrack?.play() } .. etc
}

Anywhere at all in code

sfx.explosion()
sfx.cheer()

import AVFoundation
var player:AVAudioPlayer!

 func Play(){
        guard let path = Bundle.main.path(forResource: "KurdishSong", ofType: "mp3")else{return}
        let soundURl = URL(fileURLWithPath: path)
        player = try? AVAudioPlayer(contentsOf: soundURl)
        player.prepareToPlay()
        player.play()
        //player.pause()
        //player.stop()
    }

참고URL : https://stackoverflow.com/questions/32036146/how-to-play-a-sound-using-swift

반응형