2017-08-04 10 views
-3

これは私がこの問題を解決するにはどうすればよい私のコード私はこのエラーがあります:「致命的なエラー:オプションの値をアンラップしながら、予想外にnilを見つけ、」Xcodeの8迅速で3

// 
// ViewController.swift 
// morpher app soundboard 
// 
// Created by Jared Evan Miller on 7/24/17. 
// Copyright © 2017 Jared Evan Miller. All rights reserved. 
// 

import UIKit 
import AVFoundation 

class ViewController: UIViewController { 


let soundFilenames = ["5","8","7","4","6","Sound3forbutton3","sound2forbutton1","sound2forbutton2"] 
var audioPlayers = [AVAudioPlayer]() 
var lastAudioPlayer = 0 

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

    // Set up audio players 
    for sound in soundFilenames { 

     do { 

      // Try to do something 

      let url = URL(fileURLWithPath: Bundle.main.path(forResource: sound, ofType: "wav")!) 
      let audioPlayer = try AVAudioPlayer (contentsOf:url) 

      audioPlayers.append(audioPlayer) 
     } 
     catch { 

      // Catch the error that is thrown 
     audioPlayers.append(AVAudioPlayer()) 
     } 
       } 
} 

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


@IBAction func buttonTapped(_ sender: UIButton) { 

    // Get the audioPlayer that corresponds to the button that they tapped 
    let lastPlayer = audioPlayers[lastAudioPlayer] 
    lastPlayer.stop(); 
    lastAudioPlayer = sender.tag; 
    lastPlayer.currentTime = 0; 
    let audioPlayer = audioPlayers[sender.tag] 
    audioPlayer.currentTime=0; 
    audioPlayer.play() 
} 

    @IBAction func tbuttonTapped(_ sender: UIButton) { 

    // Get the audioPlayer that corresponds to the button that they tapped 

    let lastPlayer = audioPlayers[lastAudioPlayer] 
    lastPlayer.stop(); 
    lastAudioPlayer = sender.tag; 
    lastPlayer.currentTime = 0; 
    let audioPlayer = audioPlayers[sender.tag] 
    audioPlayer.currentTime=0; 
    audioPlayer.play() 
} 

} 

のですか?

また、このエラーが発生します。これはコードの一部です。私が変わったものを見てください。それは私のiPhone上でそれを実行するときのエラーがあります。

![私のコード] [2]

[2]: https://i.stack.imgur.com/V5WC3.png 助けてください!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!

答えて

0

Budle.main.path ...の結果のアンラッピングを強制しています。これは、リソースが正しくロードされていないことを意味します。

サウンドファイルがアプリにバンドルされていることを確認してください。これを確認するには、プロジェクト設定に行き、「ビルド段階」の下にある「バンドルリソースのコピー」セクションにファイルを追加します。

for sound in soundFilenames { 

    guard let urlString = Bundle.main.path(forResource: sound, ofType: "wav") else { 

     print("Sound file not found: \(sound)") 

     continue 
    } 

    let url = URL(fileURLWithPath:urlString) 

    do { 

     // Try to do something 
     let audioPlayer = try AVAudioPlayer (contentsOf:url) 

     audioPlayers.append(audioPlayer) 
    } 
    catch { 

     // Catch the error that is thrown 
     audioPlayers.append(AVAudioPlayer()) 
    } 
} 
関連する問題