2017-08-04 72 views
-3

這是我的代碼我有這樣的錯誤:「致命錯誤:意外發現零而展開的可選值」在Xcode 8 SWIFT 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()) 
    } 
} 
相關問題