这是我的所有代码播放mp4,mp4播放但没有声音
import UIKit
import AVFoundation
class ViewController: UIViewController {
@IBOutlet weak var containerView: UIView!
var playerLayer:AVPlayerLayer!
var player:AVPlayer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let path = NSBundle.mainBundle().pathForResource("huoguo", ofType: "mp4")
let url = NSURL(fileURLWithPath: path!)
let asset = AVAsset(URL: url)
let playerItem = AVPlayerItem(asset: asset)
self.player = AVPlayer(playerItem: playerItem)
self.playerLayer = AVPlayerLayer(player: player)
self.playerLayer.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.width * 9 / 16)
self.containerView.layer.addSublayer(playerLayer)
//self.playerLayer.player?.volume = 1
self.playerLayer.player?.play()
}
}
Run Code Online (Sandbox Code Playgroud)
我确定它有声音,因为我可以听到使用VLC播放mp4时,我是否想念一些东西?
vie*_* vu 71
检查手机是否处于静音模式.如果它是静音,请尝试将以下代码添加到viewDidLoad:
斯威夫特2.3
try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: [])
Run Code Online (Sandbox Code Playgroud)
斯威夫特3
try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: [])
Run Code Online (Sandbox Code Playgroud)
Kin*_*ell 10
检查 iPhone 是否启用了静音模式,它是左上角 2 个按钮上方的一个按钮。允许静音模式的拨动开关。
Gan*_*ang 10
对于Swift 4.2,将以下行放入 viewDidLoad
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [])
}
catch {
print("Setting category to AVAudioSessionCategoryPlayback failed.")
}
Run Code Online (Sandbox Code Playgroud)
我有多个视图控制器,即使设备设置为静音,也需要播放音频。因此,我没有更新每个单个viewDidLoad,而是将以下内容添加到AppDelegate.swiftdidFinishLaunchingWithOptions文件中的方法中。
try? AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
Run Code Online (Sandbox Code Playgroud)
笔记:
AVFoundationtry?.| 归档时间: |
|
| 查看次数: |
9218 次 |
| 最近记录: |