播放音频文件 Swift

引入AVFoundation库

import AVFoundation

创建AVAudioPlayer实例

var audioPlayer:AVAudioPlayer = AVAudioPlayer()

将文件放在工程项目里

实现方法

    func playAlarmVoiceAction() {
        let session = AVAudioSession.sharedInstance()
        do{
            try session.setActive(true)
            try session.setCategory(AVAudioSessionCategoryPlayback)
            UIApplication.shared.beginReceivingRemoteControlEvents()
            let path = Bundle.main.path(forResource: "track16_www.lhdown.com", ofType: "mp3")
            let soudUrl = URL(fileURLWithPath: path!)
            try audioPlayer = AVAudioPlayer(contentsOf: soudUrl, fileTypeHint: AVFileType.mp3.rawValue)
      
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现将网络音频URL存储到本地并播放,可以按照以下步骤进行操作: 1. 首先,使用AVPlayer或AVPlayerViewController来播放网络音频。例如: ```swift let url = URL(string: "http://example.com/audio.mp3") let player = AVPlayer(url: url!) let playerViewController = AVPlayerViewController() playerViewController.player = player present(playerViewController, animated: true) { player.play() } ``` 2. 接下来,使用URLSession来下载音频文件并将其保存到本地。例如: ```swift let url = URL(string: "http://example.com/audio.mp3") let task = URLSession.shared.downloadTask(with: url!) { (location, response, error) in guard let location = location else { return } let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! let destinationUrl = documentsUrl.appendingPathComponent("audio.mp3") do { try FileManager.default.moveItem(at: location, to: destinationUrl) // 播放本地音频 let player = AVPlayer(url: destinationUrl) let playerViewController = AVPlayerViewController() playerViewController.player = player present(playerViewController, animated: true) { player.play() } } catch { print(error) } } task.resume() ``` 3. 最后,为了节省空间,可以在不需要时删除本地音频文件。例如: ```swift let fileManager = FileManager.default let documentsUrl = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first! let destinationUrl = documentsUrl.appendingPathComponent("audio.mp3") do { try fileManager.removeItem(at: destinationUrl) } catch { print(error) } ``` 以上就是实现将网络音频URL存储到本地并播放的步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值