2016-08-04 2 views
2

내 응용 프로그램의 사용자에게 경고로 소리를 재생하려고 시도하고이 재생되지 나는 몇 가지 소스를 살펴 보았다AVAudioPlayer 오디오 스위프트

https://www.youtube.com/watch?v=Kq7eVJ6RSp8

다음 내가 원래 시작 아무 소용이 지금에 실행하고 문제)

Creating and playing a sound in swift()

그리고이 동영상을 해결

https://www.youtube.com/watch?v=RKfe7xzHEZk

모두 내게 원하는 결과를주지 못합니다 (사운드가 재생되지 않음).

여기 내 코드입니다 :

private func playFinishedSound(){ 
     if let pathResource = NSBundle.mainBundle().pathForResource("3000", ofType: "mp3"){ 
      let finishedStepSound = NSURL(fileURLWithPath: pathResource) 
      var audioPlayer = AVAudioPlayer() 
      do { 
       audioPlayer = try AVAudioPlayer(contentsOfURL: finishedStepSound) 
       if(audioPlayer.prepareToPlay()){ 
        print("preparation success") 
        audioPlayer.delegate = self 
        if(audioPlayer.play()){ 
         print("Sound play success") 
        }else{ 
         print("Sound file could not be played") 
        } 
       }else{ 
        print("preparation failure") 
       } 

      }catch{ 
       print("Sound file could not be found") 
      } 
     }else{ 
      print("path not found") 
     } 
    } 

은 현재 내가 "준비 성공"과 "소리 재생의 성공을"볼 수 있지만 소리가 재생되지 않습니다. 이 클래스를 구현하는 클래스는 AVAudioPlayerDelegate이고 파일은 프로젝트 디렉토리 내에있는 "3000.mp3"이라고합니다. 맥락에서 방법은 여기에 호출됩니다

private func finishCell(cell: TimerTableViewCell, currentTimer: TimerObject){ 
     currentTimer.isRunning = false 
     cell.label.text = "dismiss" 
     cell.backgroundColor = UIColor.lightMintColor() 
     if(!currentTimer.launchedNotification){ 
      playFinishedSound() 
     } 
     currentTimer.launchedNotification = true 
    } 

어떤 도움을 주시면 감사하겠습니다.

+0

또한 내가 '가져 주목해야한다을 'Build Phases'프로젝트 탭에있는 "Link With Binary With Libraries"옵션에'AVFoundation.framework' 옵션을 추가하십시오. –

답변

6

UPADTE/해결책 :

그래서 문제는 audioPlayer는 그것이 클래스의 호텔 중 하나 만들기 위해 내가 가진이 문제를 해결하려면, 사운드를 재생하는 대신 단지 내에서의 인스턴스를 생성하는 것입니다 전에 할당이 해제 될 것이라고했다 함수. 업데이트 된 코드는 다음과 같습니다

클래스의 속성 선언에서

옵션 참조 :

var audioPlayer : AVAudioPlayer? 

audioPlayer 사용 기능 :

private func playFinishedSound(){ 
     if let pathResource = NSBundle.mainBundle().pathForResource("3000", ofType: "mp3"){ 
      let finishedStepSound = NSURL(fileURLWithPath: pathResource) 
      audioPlayer = AVAudioPlayer() 
      do { 
       audioPlayer = try AVAudioPlayer(contentsOfURL: finishedStepSound) 
       if(audioPlayer!.prepareToPlay()){ 
        print("preparation success") 
        audioPlayer!.delegate = self 
        if(audioPlayer!.play()){ 
         print("Sound play success") 
        }else{ 
         print("Sound file could not be played") 
        } 
       }else{ 
        print("preparation failure") 
       } 

      }catch{ 
       print("Sound file could not be found") 
      } 
     }else{ 
      print("path not found") 
     } 
    } 
+0

왜 AVAudioPlayer를 두 번 인스턴스화합니까 (하나는 외부에 있고 다른 하나는 내부에 있습니다)? – AlvinfromDiaspar

+0

@AlvinfromDiaspar 왜 그런지는 기억이 안나지만 audioPlayer는 그렇지 않으면 오류를 던질 것입니다 ... 개인 레포에 더 이상 액세스 할 수 없어서 코드를 볼 수 없습니다. –