前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >IOS AVAudioPlayer 播放MP3

IOS AVAudioPlayer 播放MP3

作者头像
用户5760343
发布2019-07-08 12:22:38
1.2K0
发布2019-07-08 12:22:38
举报
文章被收录于专栏:sktj
代码语言:javascript
复制
 1 import UIKit
 2 import AVFoundation
 3
 4 class ViewController:UIViewController,
 AVAudioPlayerDelegate {
 5 var audioPlayer:AVAudioPlayer = AVAudioPlayer()
 6 override func viewDidLoad() {
 7 super.viewDidLoad()
 8 // Do any additional setup after loading the view,
 typically from a nib.
 9 let path = Bundle.main.path(forResource:“music”,
 ofType:“mp3”)
 10 let soundUrl = URL(fileURLWithPath:path!)
 11
 12 do{
 13 try audioPlayer = AVAudioPlayer(contentsOf:
 soundUrl)
 14 audioPlayer.volume = 1.0
 15 audioPlayer.numberOfLoops = -1
 16 audioPlayer.delegate = self
 17 audioPlayer.play()
 18 } catch{
 19 print(error)
 20 }
 21 let stopMusic = UIButton(frame:CGRect(x:20, y:
 80, width:280, height:44))
 22 stopMusic.backgroundColor = UIColor.purple
 23 stopMusic.setTitle(“暂停/恢复音乐”, for:
 UIControlState.init(rawValue:0))
 24 stopMusic.addTarget(self, action:
selector(ViewController.pauseOrResumeMusic),
for:.touchUpInside)
 25 self.view.addSubview(stopMusic)
 26 }
 27 func pauseOrResumeMusic(){
 28 if self.audioPlayer.isPlaying {
 29 self.audioPlayer.pause()
 30 }
 31 else{
 32 self.audioPlayer.play()
 33 }
 34 }
 35 func audioPlayerBeginInterruption(_ player:
 AVAudioPlayer) {
 36 print(“音乐播放被打断。”)
 37 }
 38 func audioPlayerDidFinishPlaying(_ player:
 AVAudioPlayer, successfully flag:Bool) {
 39 print(“音乐播放完毕。”);
 40 }
 41 }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019.06.10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档