質問編集履歴

3 こード記入

torkia

torkia score 14

2018/07/17 19:55  投稿

Swift 再生中の音を取得してページ移動・ボタン押下で停止させたい。
お世話になります。
AVAudioPlayerを使用してボタン押下で再生/停止、ページ移動で停止させたいのですが、思い通りにいきません。
原因・解決方法など教えて頂けないでしょうか。
宜しくお願い致します。
---やりたいこと---
●再生中の音をページ移動する時に、停止させる。
●再生中の音と同じボタン押下で、停止させる。
●再生中の音とは別のボタン押下で、再生中の音を停止させ、押されたボタンに割り当てられた音を再生する。
(サンプルのコードでは1ページにつき16コのボタンを用意しています。)
###試したこと
ボタン押下されたら、ボタンメソッド内でplay()させ、変数currentPlayerに代入して、次に押されたボタンが同じボタンだった場合はcurrentPlayerと同じ音が割り当てられたかを(ここ1)のところで条件をだしているのですが、ここのスコープ内には全く入ってこず、再生中の音がある場合は、すべて(ここ2)の方へ流れていってしまってます。なので、同じボタンを押した場合は再生中の音は停止してまた同じ音を再生し始めてしまいます。本当は停止だけさせたいのですが。
同じボタンを押しても変数audioPlayerには同じ名前のAVAudioPlayerが入っておらず(ここ1)のif文内に入ってくれないのだと思うのですが、どうすればいいか分かりません。
###該当のソースコード
サンプルでは、配列soundNameArray内の1つの配列に16コのmp3データがあり、ページ数は20ページあります。
サンプルでは、2種類のmp3データを使い回して試しています。(ファイル名は1.mp3、2.mp3)
```
// 使用Version: Swift3
import UIKit
import AVFoundation
class PageContentViewController: UIViewController, AVAudioPlayerDelegate {
   let soundNameArray = [
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 1
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 2
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 3
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 4
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 5
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 6
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 7
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 8
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 9
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 10
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 11
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 12
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 13
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 14
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 15
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 16
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 17
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 18
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 19
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"]  // 20
       ]
 
   var pageIndex:Int = 0          // 各ページのindex
   let indexPageLabel = UILabel() // index確認用ラベル
   
   // sound関係
   var soundArray:[String] = []  // ファイル名のデータを格納する
   var audioPlayer:AVAudioPlayer! // urlから音声データにして格納する
   var soundButtons = [UIButton]() // 音声を鳴らすボタンを格納する
   var currentPlayer:AVAudioPlayer?
   
   override func viewDidLoad() {
       super.viewDidLoad()
       
       // indexPageラベル
       indexPageLabel.frame = CGRect(x: 20, y: 10, width: 240, height: 20)
       indexPageLabel.text = "pageIndex: \(pageIndex)  ページNo: \((pageIndex) + 1)"
       indexPageLabel.backgroundColor = .yellow
       self.view.addSubview(indexPageLabel)
       
       soundArray = soundNameArray[pageIndex]
       // サウンドボタンを量産  button
       for index in 0..<soundArray.count {
           let soundButton = UIButton()
           soundButton.frame = CGRect(x: 20, y: 40 + (index * 30), width: 40, height: 30)
           soundButton.backgroundColor = UIColor.lightGray
           soundButton.titleLabel?.font = UIFont.systemFont(ofSize: 10)
           soundButton.setTitle("▶", for: .normal)
           soundButton.setTitleColor(UIColor.darkGray, for: .normal)
           soundButton.tag = index // ボタン識別用ID
           soundButton.addTarget(self, action: #selector(buttonEventSound(sender:)), for: .touchUpInside)
           soundButtons.append(soundButton)
           self.view.addSubview(soundButton)
       }
       
   } //viewDidLoadを閉じる
override func viewWillDisappear(_ animated: Bool) {
       super.viewWillDisappear(animated)
       
       if currentPlayer != nil {
           if (currentPlayer?.isPlaying)! {
               currentPlayer?.stop()
               currentPlayer?.currentTime = 0
           }
       }
       currentPlayer = nil
   }
   
   // ボタンイベント音再生
   func buttonEventSound(sender: UIButton) {
       let index = sender.tag
       let audioPath = Bundle.main.path(forResource: "\(soundArray[index])", ofType:"mp3")!
       let audioUrl = URL(fileURLWithPath: audioPath)
           
           do {
               audioPlayer = try AVAudioPlayer(contentsOf: audioUrl)
               audioPlayer.delegate = self
               audioPlayer.prepareToPlay()
           } catch {
               print("エラー")
           }
       if currentPlayer != nil {
            if (currentPlayer?.isPlaying)! {
               if currentPlayer == audioPlayer {
                   currentPlayer?.stop()
                   currentPlayer?.currentTime = 0
                   currentPlayer = nil
                   print("ここ1")
              } else {
                   currentPlayer?.stop()
                   currentPlayer?.currentTime = 0
                   audioPlayer.play()
                   currentPlayer = audioPlayer
                   print("ここ2")
               }
           }
       } else {
           audioPlayer.play()
           currentPlayer = audioPlayer
           print("ここ3")
       }
   }
    // 音楽再生が成功した時に呼ばれるメソッド
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
       currentPlayer = nil 
       print("音終了")
    }
   
    // デコード中にエラーが起きた時に呼ばれるメソッド
    func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) {
       print("デコードエラー")
    }
   
   override func didReceiveMemoryWarning() {
       super.didReceiveMemoryWarning()
   } 
}
```
  • Swift

    8709 questions

    Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

2 コード記入

torkia

torkia score 14

2018/07/17 19:53  投稿

Swift 再生中の音を取得してページ移動・ボタン押下で停止させたい。
お世話になります。
AVAudioPlayerを使用してボタン押下で再生/停止、ページ移動で停止させたいのですが、思い通りにいきません。
原因・解決方法など教えて頂けないでしょうか。
宜しくお願い致します。
---やりたいこと---
●再生中の音をページ移動する時に、停止させる。
●再生中の音と同じボタン押下で、停止させる。
●再生中の音とは別のボタン押下で、再生中の音を停止させ、押されたボタンに割り当てられた音を再生する。
(サンプルのコードでは1ページにつき16コのボタンを用意しています。)
###試したこと
ボタン押下されたら、ボタンメソッド内でplay()させ、変数currentPlayerに代入して、次に押されたボタンが同じボタンだった場合はcurrentPlayerと同じ音が割り当てられたかを(ここ1)のところで条件をだしているのですが、ここのスコープ内には全く入ってこず、再生中の音がある場合は、すべて(ここ2)の方へ流れていってしまってます。なので、同じボタンを押した場合は再生中の音は停止してまた同じ音を再生し始めてしまいます。本当は停止だけさせたいのですが。
同じボタンを押しても変数audioPlayerには同じ名前のAVAudioPlayerが入っておらず(ここ1)のif文内に入ってくれないのだと思うのですが、どうすればいいか分かりません。
###該当のソースコード
サンプルでは、配列soundNameArray内の1つの配列に16コのmp3データがあり、ページ数は20ページあります。
サンプルでは、2種類のmp3データを使い回して試しています。(ファイル名は1.mp3、2.mp3)
サンプルでは、tableViewのセルから画面遷移して遷移先のページから音の再生やページスクロールができます。
```
// 使用Version: Swift3
import UIKit
import AVFoundation
class PageContentViewController: UIViewController, AVAudioPlayerDelegate {
   let soundNameArray = [
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 1
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 2
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 3
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 4
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 5
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 6
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 7
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 8
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 9
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 10
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 11
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 12
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 13
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 14
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 15
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 16
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 17
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 18
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 19
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"]  // 20
       ]
 
   var pageIndex:Int = 0          // 各ページのindex
   let indexPageLabel = UILabel() // index確認用ラベル
   
   // sound関係
   var soundArray:[String] = []  // ファイル名のデータを格納する
   var audioPlayer:AVAudioPlayer! // urlから音声データにして格納する
   var soundButtons = [UIButton]() // 音声を鳴らすボタンを格納する
   var currentPlayer:AVAudioPlayer?
   
   override func viewDidLoad() {
       super.viewDidLoad()
       
       // indexPageラベル
       indexPageLabel.frame = CGRect(x: 20, y: 10, width: 240, height: 20)
       indexPageLabel.text = "pageIndex: \(pageIndex)  ページNo: \((pageIndex) + 1)"
       indexPageLabel.backgroundColor = .yellow
       self.view.addSubview(indexPageLabel)
       
       soundArray = soundNameArray[pageIndex]
       // サウンドボタンを量産  button
       for index in 0..<soundArray.count {
           let soundButton = UIButton()
           soundButton.frame = CGRect(x: 20, y: 40 + (index * 30), width: 40, height: 30)
           soundButton.backgroundColor = UIColor.lightGray
           soundButton.titleLabel?.font = UIFont.systemFont(ofSize: 10)
           soundButton.setTitle("▶", for: .normal)
           soundButton.setTitleColor(UIColor.darkGray, for: .normal)
           soundButton.tag = index // ボタン識別用ID
           soundButton.addTarget(self, action: #selector(buttonEventSound(sender:)), for: .touchUpInside)
           soundButtons.append(soundButton)
           self.view.addSubview(soundButton)
       }
       
   } //viewDidLoadを閉じる
override func viewWillDisappear(_ animated: Bool) {
       super.viewWillDisappear(animated)
       
       if currentPlayer != nil {
           if (currentPlayer?.isPlaying)! {
               currentPlayer?.stop()
               currentPlayer?.currentTime = 0
           }
       }
       currentPlayer = nil
   }
   
   // ボタンイベント音再生
   func buttonEventSound(sender: UIButton) {
       let index = sender.tag
       let audioPath = Bundle.main.path(forResource: "\(soundArray[index])", ofType:"mp3")!
       let audioUrl = URL(fileURLWithPath: audioPath)
           
           do {
               audioPlayer = try AVAudioPlayer(contentsOf: audioUrl)
               audioPlayer.delegate = self
               audioPlayer.prepareToPlay()
           } catch {
               print("エラー")
           }
       if currentPlayer != nil {
            if (currentPlayer?.isPlaying)! {
               if currentPlayer == audioPlayer {
                   currentPlayer?.stop()
                   currentPlayer?.currentTime = 0
                   currentPlayer = nil
                   print("ここ1")
              } else {
                   currentPlayer?.stop()
                   currentPlayer?.currentTime = 0
                   audioPlayer.play()
                   currentPlayer = audioPlayer
                   print("ここ2")
               }
           }
       } else {
           audioPlayer.play()
           currentPlayer = audioPlayer
           print("ここ3")
       }
   }
    // 音楽再生が成功した時に呼ばれるメソッド
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
       currentPlayer = nil 
       print("音終了")
    }
   
    // デコード中にエラーが起きた時に呼ばれるメソッド
    func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) {
       print("デコードエラー")
    }
   
   override func didReceiveMemoryWarning() {
       super.didReceiveMemoryWarning()
   } 
}
```
###その他のソースコード(ページングするためのViewControllerとPageViewController)
```
import UIKit
class PageViewController: UIPageViewController, UIPageViewControllerDataSource {
   
   var selectedIndex: Int = 0   // タップされたセルのindex
   var pageIndex:Int = 0 // 各ページに割り当てたindex
   var contentVCs = [UIViewController]() 
   
   override func viewDidLoad() {
       super.viewDidLoad()
       
       // ナビゲーションバーの透過を無効にする。
       self.navigationController!.navigationBar.isTranslucent = false
       
       dataSource = self
       
       for index in 0..<20 {
           let contentVC = storyboard?.instantiateViewController(withIdentifier: "PageContentViewController") as! PageContentViewController
           contentVC.pageIndex = index
           contentVCs.append(contentVC)
       }
       
       self.setViewControllers([contentVCs[selectedIndex]], direction: .forward, animated: true, completion: nil)
       
   } // viewDidLoad()を閉じる
   
   
   // MARK: - UIPageViewControllerDataSource
   // スワイプでページを戻る(Before)
   func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
       guard let index = contentVCs.index(of: viewController as! PageContentViewController), index > 0 else {
           return nil
       }
       let previousVC = contentVCs[index - 1]
       return previousVC
   }
   
   // スワイプでページを進む(After)
   func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
       guard let index = contentVCs.index(of: viewController as! PageContentViewController), index < contentVCs.count - 1 else {
           return nil
       }
       let nextVC = contentVCs[index + 1]
       return nextVC
   }
   
}
```
```
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
   
   let sectionTitle = ["Title"]  //セクションに表示するデータ
   let section0 = Array(1...20)  //セルに表示するデータ
   @IBOutlet weak var tableView: UITableView!
   override func viewDidLoad() {
       super.viewDidLoad()
       
       tableView.delegate = self
       tableView.dataSource = self
   }
   
   override func didReceiveMemoryWarning() {
       super.didReceiveMemoryWarning()
   }
   
   func numberOfSections(in tableView: UITableView) -> Int {
       return sectionTitle.count
   }
   
   func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       return section0.count
   }
   
   func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
       return sectionTitle[section]
   }
   
   func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
       return 30
   }
   
   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
       cell.textLabel?.text = "\(section0[indexPath.row])"
       return cell
   }
   
   override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
       if segue.identifier == "ToPageViewController" {
           if let indexPath = self.tableView.indexPathForSelectedRow {
               tableView.deselectRow(at: indexPath, animated: false)
               if let pageViewController = segue.destination as? PageViewController {
                   pageViewController.selectedIndex = indexPath.row
               }
           }
       }
   }
   
}
```
  • Swift

    8709 questions

    Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

1 コード記入

torkia

torkia score 14

2018/07/14 16:48  投稿

Swift 再生中の音を取得してページ移動・ボタン押下で停止させたい。
お世話になります。
AVAudioPlayerを使用してボタン押下で再生/停止、ページ移動で停止させたいのですが、思い通りにいきません。
原因・解決方法など教えて頂けないでしょうか。
宜しくお願い致します。
---やりたいこと---
●再生中の音をページ移動する時に、停止させる。
●再生中の音と同じボタン押下で、停止させる。
●再生中の音とは別のボタン押下で、再生中の音を停止させ、押されたボタンに割り当てられた音を再生する。
(サンプルのコードでは1ページにつき16コのボタンを用意しています。)
###試したこと
ボタン押下されたら、ボタンメソッド内でplay()させ、変数currentPlayerに代入して、次に押されたボタンが同じボタンだった場合はcurrentPlayerと同じ音が割り当てられたかを(ここ1)のところで条件をだしているのですが、ここのスコープ内には全く入ってこず、再生中の音がある場合は、すべて(ここ2)の方へ流れていってしまってます。なので、同じボタンを押した場合は再生中の音は停止してまた同じ音を再生し始めてしまいます。本当は停止だけさせたいのですが。
同じボタンを押しても変数audioPlayerには同じ名前のAVAudioPlayerが入っておらず(ここ1)のif文内に入ってくれないのだと思うのですが、どうすればいいか分かりません。
###該当のソースコード
サンプルでは、配列soundNameArray内の1つの配列に16コのmp3データがあり、ページ数は20ページあります。
サンプルでは、2種類のmp3データを使い回して試しています。(ファイル名は1.mp3、2.mp3)
サンプルでは、tableViewのセルから画面遷移して遷移先のページから音の再生やページスクロールができます。
```
// 使用Version: Swift3
import UIKit
import AVFoundation
class PageContentViewController: UIViewController, UIScrollViewDelegate, AVAudioPlayerDelegate {
class PageContentViewController: UIViewController, AVAudioPlayerDelegate {
   let soundNameArray = [
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 1
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 2
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 3
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 4
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 5
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 6
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 7
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 8
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 9
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 10
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 11
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 12
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 13
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 14
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 15
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 16
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 17
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 18
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"], // 19
       ["1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"]  // 20
       ]
 
   var pageIndex:Int = 0          // 各ページのindex
   let indexPageLabel = UILabel() // index確認用ラベル
   
   // sound関係
   var soundArray:[String] = []  // ファイル名のデータを格納する
   var audioPlayer:AVAudioPlayer! // urlから音声データにして格納する
   var soundButtons = [UIButton]() // 音声を鳴らすボタンを格納する
   var currentPlayer:AVAudioPlayer?
   
   override func viewDidLoad() {
       super.viewDidLoad()
       
       // indexPageラベル
       indexPageLabel.frame = CGRect(x: 20, y: 10, width: 240, height: 20)
       indexPageLabel.text = "pageIndex: \(pageIndex)  ページNo: \((pageIndex) + 1)"
       indexPageLabel.backgroundColor = .yellow
       self.view.addSubview(indexPageLabel)
       
       soundArray = soundNameArray[pageIndex]
       // サウンドボタンを量産  button
       for index in 0..<soundArray.count {
           let soundButton = UIButton()
           soundButton.frame = CGRect(x: 20, y: 40 + (index * 30), width: 40, height: 30)
           soundButton.backgroundColor = UIColor.lightGray
           soundButton.titleLabel?.font = UIFont.systemFont(ofSize: 10)
           soundButton.setTitle("▶", for: .normal)
           soundButton.setTitleColor(UIColor.darkGray, for: .normal)
           soundButton.tag = index // ボタン識別用ID
           soundButton.addTarget(self, action: #selector(buttonEventSound(sender:)), for: .touchUpInside)
           soundButtons.append(soundButton)
           self.view.addSubview(soundButton)
       }
       
   } //viewDidLoadを閉じる
override func viewWillDisappear(_ animated: Bool) {
       super.viewWillDisappear(animated)
       
       if currentPlayer != nil {
           if (currentPlayer?.isPlaying)! {
               currentPlayer?.stop()
               currentPlayer?.currentTime = 0
           }
       }
       currentPlayer = nil
   }
   
   // ボタンイベント音再生
   func buttonEventSound(sender: UIButton) {
       let index = sender.tag
       let audioPath = Bundle.main.path(forResource: "\(soundArray[index])", ofType:"mp3")!
       let audioUrl = URL(fileURLWithPath: audioPath)
           
           do {
               audioPlayer = try AVAudioPlayer(contentsOf: audioUrl)
               audioPlayer.delegate = self
               audioPlayer.prepareToPlay()
           } catch {
               print("エラー")
           }
       if currentPlayer != nil {
            if (currentPlayer?.isPlaying)! {
               if currentPlayer == audioPlayer {
                   currentPlayer?.stop()
                   currentPlayer?.currentTime = 0
                   currentPlayer = nil
                   print("ここ1")
              } else {
                   currentPlayer?.stop()
                   currentPlayer?.currentTime = 0
                   audioPlayer.play()
                   currentPlayer = audioPlayer
                   print("ここ2")
               }
           }
       } else {
           audioPlayer.play()
           currentPlayer = audioPlayer
           print("ここ3")
       }
   }
    // 音楽再生が成功した時に呼ばれるメソッド
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
       currentPlayer = nil 
       print("音終了")
    }
   
    // デコード中にエラーが起きた時に呼ばれるメソッド
    func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) {
       print("デコードエラー")
    }
   
   override func didReceiveMemoryWarning() {
       super.didReceiveMemoryWarning()
   } 
}
```
###その他のソースコード(ページングするためのViewControllerとPageViewController)
```
import UIKit
class PageViewController: UIPageViewController, UIPageViewControllerDataSource {
   
   var selectedIndex: Int = 0   // タップされたセルのindex
   var pageIndex:Int = 0 // 各ページに割り当てたindex
   var contentVCs = [UIViewController]() 
   
   override func viewDidLoad() {
       super.viewDidLoad()
       
       // ナビゲーションバーの透過を無効にする。
       self.navigationController!.navigationBar.isTranslucent = false
       
       dataSource = self
       
       for index in 0..<20 {
           let contentVC = storyboard?.instantiateViewController(withIdentifier: "PageContentViewController") as! PageContentViewController
           contentVC.pageIndex = index
           contentVCs.append(contentVC)
       }
       
       self.setViewControllers([contentVCs[selectedIndex]], direction: .forward, animated: true, completion: nil)
       
   } // viewDidLoad()を閉じる
   
   
   // MARK: - UIPageViewControllerDataSource
   // スワイプでページを戻る(Before)
   func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
       guard let index = contentVCs.index(of: viewController as! PageContentViewController), index > 0 else {
           return nil
       }
       let previousVC = contentVCs[index - 1]
       return previousVC
   }
   
   // スワイプでページを進む(After)
   func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
       guard let index = contentVCs.index(of: viewController as! PageContentViewController), index < contentVCs.count - 1 else {
           return nil
       }
       let nextVC = contentVCs[index + 1]
       return nextVC
   }
   
}
```
```
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
   
   let sectionTitle = ["Title"]  //セクションに表示するデータ
   let section0 = Array(1...20)  //セルに表示するデータ
   @IBOutlet weak var tableView: UITableView!
   override func viewDidLoad() {
       super.viewDidLoad()
       
       tableView.delegate = self
       tableView.dataSource = self
   }
   
   override func didReceiveMemoryWarning() {
       super.didReceiveMemoryWarning()
   }
   
   func numberOfSections(in tableView: UITableView) -> Int {
       return sectionTitle.count
   }
   
   func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       return section0.count
   }
   
   func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
       return sectionTitle[section]
   }
   
   func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
       return 30
   }
   
   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
       cell.textLabel?.text = "\(section0[indexPath.row])"
       return cell
   }
   
   override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
       if segue.identifier == "ToPageViewController" {
           if let indexPath = self.tableView.indexPathForSelectedRow {
               tableView.deselectRow(at: indexPath, animated: false)
               if let pageViewController = segue.destination as? PageViewController {
                   pageViewController.selectedIndex = indexPath.row
               }
           }
       }
   }
   
}
```
  • Swift

    8709 questions

    Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

思考するエンジニアのためのQ&Aサイト「teratail」について詳しく知る