Xcode에서 음악을 재생해 보았습니다.

7906 단어 XcodeSwift3.0
If you would like to try my code, you have to prepare music files. (does not matter what type of extension, but highly recommend mp3 or mp4)

Development Environment


  • OS X El Captain 10.11.2
  • Xcode Version 8.0

  • Language



    Swift 3.0

    Step



    1- Add your music file to Assets.xcassets



    2- import AVFoundation to activate the library to use
    import AVFoundation
    

    3- Declare a parameter of AVAudioPlayer
    var player: AVAudioPlayer?
    

    4- Create main function that will play a music file in Xcode
     func playSound() {
            guard let sound = NSDataAsset(name: "前前前世") else {
                print("The music file that you mentioned is not found in asset folder")
                return
            }
            do {
                try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
                try AVAudioSession.sharedInstance().setActive(true)
                player = try AVAudioPlayer(data: sound.data, fileTypeHint: AVFileTypeMPEGLayer3)
                player!.play()
            } catch let error as NSError {
                print("Error: \(error.localizedDescription)")
            }
        }
    

    5- Done

    Source Code



    ViewController.swift
    import UIKit
    import AVFoundation
    
    class ViewController: UIViewController {
    
        var player: AVAudioPlayer?
    
        override func viewDidLoad() {
            super.viewDidLoad()
            playSound()
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    }
    
    /* Function */
    extension ViewController{
        func playSound() {
            guard let sound = NSDataAsset(name: "前前前世") else {
                print("The music file that you mentioned is not found in asset folder")
                return
            }
            do {
                try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
                try AVAudioSession.sharedInstance().setActive(true)
                player = try AVAudioPlayer(data: sound.data, fileTypeHint: AVFileTypeMPEGLayer3)
                // You can print name of music that you are gonna play.
                print (sound.name)
                player!.play()
            } catch let error as NSError {
                print("Error: \(error.localizedDescription)")
            }
        }
    }
    

    Conclusion



    이제 음악 재생 앱을 만들 수 있습니다!

    좋은 웹페이지 즐겨찾기