声音可以在我的模拟器上运行但不在我的设备上... SWIFT

时间:2015-11-15 01:49:31

标签: ios swift audio record

我的项目在这里有一个恼人的问题...... 当我在模拟器中录制并播放它时,一切正常。 但是当我在iPhone上播放时声音不起作用......我搜索了几个小时的解决方案......

这是我的代码

import UIKit
import Parse
import AVFoundation

class View1: UIViewController, AVAudioRecorderDelegate, AVAudioPlayerDelegate {

    @IBOutlet weak var recordButton: UIButton!
    @IBOutlet weak var playButton: UIButton!


    var soundRecorder: AVAudioRecorder!
    var soundPlayer:AVAudioPlayer!

    let fileName = "sound.caf"

    override func viewDidLoad() {
        super.viewDidLoad()
        setupRecorder()
    }

    @IBAction func recordSound(sender: AnyObject) {
        if (sender.titleLabel?!.text == "Record"){
            soundRecorder.record()
            sender.setTitle("Stop", forState: .Normal)
            playButton.enabled = false
        } else {
            soundRecorder.stop()
            sender.setTitle("Record", forState: .Normal)
        }
    }

    @IBAction func playSound(sender: AnyObject) {
        if (sender.titleLabel?!.text == "Play"){
            recordButton.enabled = false
            sender.setTitle("Stop", forState: .Normal)
            preparePlayer()
            soundPlayer.play()
        } else {
            soundPlayer.stop()
            sender.setTitle("Play", forState: .Normal)
        }
    }

    // MARK:- AVRecorder Setup

    func setupRecorder() {

        //set the settings for recorder

        let recordSettings = [AVSampleRateKey : NSNumber(float: Float(44100.0)),
            AVFormatIDKey : NSNumber(int: Int32(kAudioFormatAppleLossless)),
            AVNumberOfChannelsKey : NSNumber(int: 2),
            AVEncoderAudioQualityKey : NSNumber(int: Int32(AVAudioQuality.Max.rawValue))];

        var error: NSError?

        do {
            //  soundRecorder = try AVAudioRecorder(URL: getFileURL(), settings: recordSettings as [NSObject : AnyObject])
            soundRecorder =  try AVAudioRecorder(URL: getFileURL(), settings: recordSettings)
        } catch let error1 as NSError {
            error = error1
            soundRecorder = nil
        }

        if let err = error {
            print("AVAudioRecorder error: \(err.localizedDescription)")
        } else {
            soundRecorder.delegate = self
            soundRecorder.prepareToRecord()
        }
    }

    // MARK:- Prepare AVPlayer

    func preparePlayer() {
        var error: NSError?

        do {
            soundPlayer = try AVAudioPlayer(contentsOfURL: getFileURL())
        } catch let error1 as NSError {
            error = error1
            soundPlayer = nil
        }

        if let err = error {
            print("AVAudioPlayer error: \(err.localizedDescription)")
        } else {
            soundPlayer.delegate = self
            soundPlayer.prepareToPlay()
            soundPlayer.volume = 1.0
        }
    }

    // MARK:- File URL

    func getCacheDirectory() -> String {
        let paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory,.UserDomainMask, true)

        return paths[0]
    }

    func getFileURL() -> NSURL {

        let path = getCacheDirectory().stringByAppendingString(fileName)
        let filePath = NSURL(fileURLWithPath: path)
        return filePath
    }

    // MARK:- AVAudioPlayer delegate methods

    func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
        recordButton.enabled = true
        playButton.setTitle("Play", forState: .Normal)
    }

    func audioPlayerDecodeErrorDidOccur(player: AVAudioPlayer, error: NSError?) {
        print("Error while playing audio \(error!.localizedDescription)")
    }

    // MARK:- AVAudioRecorder delegate methods

    func audioRecorderDidFinishRecording(recorder: AVAudioRecorder, successfully flag: Bool) {
        playButton.enabled = true
        recordButton.setTitle("Record", forState: .Normal)
    }

    func audioRecorderEncodeErrorDidOccur(recorder: AVAudioRecorder, error:            NSError?) {
        print("Error while recording audio \(error!.localizedDescription)")
    }

    // MARK:- didReceiveMemoryWarning

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

谢谢。

1 个答案:

答案 0 :(得分:3)

在setupRecorder方法

中添加此代码
let session = AVAudioSession.sharedInstance()
  try!  session.setCategory(AVAudioSessionCategoryPlayAndRecord)