AVPlayer not playing despite having correct URL
I have checked your code and discovered such a pattern:
- if I define and initialize
audioPlayer
beforeviewDidLoad
- thenaudioPlayer
works in 100% of cases (I worked with this audio) - if I define and initialize
audioPlayer
as you (atpausePlayAudio
) - sometimes it works, sometimes not.
Please, check this:
var audioPlayer = AVPlayer()
@IBAction func pausePlayAudio(_ sender: CustomButton) {
let audioSourceURL: String = "[Site]/module_lesson_uploads/audios/"
let audioString: String = audioSourceURL + (sender.paramaters["thisAudioURL"] as! String)
let audioURL = URL(string: audioString)
print(audioString)
let playerItem = AVPlayerItem(url: audioURL!)
self.audioPlayer = AVPlayer(playerItem: playerItem)
self.audioPlayer.play()
}
SwiftUI - How do I Press button - Autoplay video with no controls - Do rest of button actions
Regarding the VideoPlayer
and loading different content for it, you need to put the VideoPlayer
inside the view hierarchy. Right now, you have it inside the Button
's action, which means that even if you didn't have a compiler error, it would show up in your view.
Here's some code that loads different AVPlayer
s based on the state of number
and autoplays the video:
struct ContentView: View {
@State var number = 6
@State var player = AVPlayer(url: URL(string: "https://media.w3.org/2010/05/sintel/trailer.mp4")!)
var body: some View {
VStack {
VideoPlayer(player: player)
Button(action: {
number += 1
if number >= 9 {
player = AVPlayer(url: URL(string: "https://media.w3.org/2010/05/sintel/trailer.mp4")!)
} else {
player = AVPlayer(url: URL(string: "https://www.w3schools.com/html/movie.mp4")!)
}
player.play()
}) {
Text("Button")
}
}
}
}
Regarding hiding the controls, you can't actually do that with VideoPlayer
, but you can wrap AVPlayerViewController
: https://stackoverflow.com/a/65928091/560942
AVPlayer won't let me access URL
I found your question after you commented on a question I had answered previously, so lets continue here :)
I can get your code working by combining my original answer to that question with the answer provided by @callam above so...give him the credit for the correct answer :)
To summarize, you need to:
- Add a
AVPlayerView
to your Storyboard and connect it to yourViewController
- Setup your
ViewController
- Manage App Transport Security and the outgoing connection.
In greater detail
1. Add a AVPlayerView
to your Storyboard and connect it to your ViewController
Drag a AVKit Player View
to your view in the storyboard
In your ViewController
class, create an outlet
for the view:
@IBOutlet weak var playerView: AVPlayerView!
And connect it.
2. Setup your ViewController
Here is my code:
import Cocoa
import AVKit
class ViewController: NSViewController {
@IBOutlet weak var playerView: AVPlayerView!
override func viewDidLoad() {
super.viewDidLoad()
let fileURL = URL(string: "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4")
let avAsset = AVURLAsset(url: fileURL!, options: nil)
let playerItem = AVPlayerItem(asset: avAsset)
let videoPlayer = AVPlayer(playerItem: playerItem)
playerView.player = videoPlayer
videoPlayer.play()
}
}
Seems familiar no :)
Notice I create the videoPlayer
right here, no need to for me to use the let playerView = self.playerView
you mention in your comments.
If you just do these two steps, you end up with a player view that cannot play video and errors in your console. So you need to add the final piece to the puzzle, kindly provided by @callam above.
3. Manage App Transport Security and the outgoing connection.
First, if you cannot use a HTTPS
connection you must allow HTTP
connections in your info.plist
file.
Here is my .plist
file in its entirety
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIconFile</key>
<string></string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSMinimumSystemVersion</key>
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2017 :) </string>
<key>NSMainStoryboardFile</key>
<string>Main</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
</dict>
</plist>
The important part being the NSAppTransportSecurity
part
And then finally, you must enable Outgoing Connections (Client)
under Capabilities
of your project
If I do that, I end up with this:
But notice though, that I still see errors in the console.
Hope you are able to get to the same result following these steps :)
Related Topics
How to Change Orientation for Avcapturemoviefileoutput in Swift
How to Mutate an Array in a Dictionary
Check If Class Has a Value for a Key
Swift: Rsa Encrypt a String with a Specific Private Key
+' Is Deprecated: Mixed-Type Addition Is Deprecated in Swift 3.1
Swift Type Inference and Type Checking Issue
Arkit - Raycasting Using a World Ray Instead of a Screen Point
Localize iOS 14 Dynamic Widget Configuration
Testing a Timer in Xcode with Xctest
Uitextview Contentoffset Is Set
Instantiating a Nested Class Using Nsclassfromstring in Swift
Swift Unable to Locate and Read Property List (.Plist) File
Show and Hide Window Instead of Terminating App on Close Click in Cocoa App
Error: 'string' Is Not Convertible to 'string!'
Error Loading Media Sources in Mlmedialibrary
Uitableview Only Displays One Section