2017-01-08 5 views
1

iOSで曲を再生するためにこのコードを書きましたが、複数の曲を再生するコードを書き込む方法がわかりません。iOSで複数の曲を再生する

これは歌のためのコードの行です:あなたが実際にAVAudioPlayerのRESPのちょうど2つのインスタンスでそれを再生することができます

import UIKit 
import AVFoundation 

class ViewController: UIViewController { 
    var player:AVAudioPlayer = AVAudioPlayer() 

    @IBAction func play(_ sender: AnyObject) 
    { 
     player.play() 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 

     do 
     { 
      let audioPath = Bundle.main.path(forResource: "Ken", ofType: "mp3") 
      try player = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL) 
     } 
     catch 
     { 
      //ERROR 
     } 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 
} 

答えて

1

。同時に再生したい場合は、すべてのサウンドファイルに自分のAVAudioPlayerが必要です。

0

私はすでに回答を書いていますので、すでに正解があっても投稿します。パームは正しいと言った。複数のAVAudioPlayerインスタンスを使用して複数のサウンドを同時に再生することができます。

import UIKit 
import AVFoundation 

class ViewController: UIViewController { 

    let paths = ["a","b"] 
    var sounds = [AVAudioPlayer]() 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 

     for path in paths { 

      do 
      { 
       let audioPath = Bundle.main.path(forResource: path, ofType: "mp3") 

       let player = try AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL) 

       sounds.append(player) 

      } 
      catch 
      { 
       //ERROR 
      } 

     } 

     for sound in sounds { 
      sound.play() 
     } 
    } 
} 
関連する問題