LoginSignup
4
5

More than 5 years have passed since last update.

Xcodeで音楽を再生してみた

Posted at

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

musicXcode.png

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

これで音楽再生アプリつくれちゃいますね!

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5