SwiftUI Style for Swift, iPhone App Development: 13 Play and Record Music

Hello! In this post, we will take a closer look at how to play and record music in an iPhone app using Swift and SwiftUI. This tutorial will cover various techniques needed to implement music playback and recording features, starting from the basic elements of SwiftUI. I hope you will enhance your understanding of iOS app development and acquire the ability to perform practical tasks through this course.

1. What is SwiftUI?

SwiftUI is a UI framework announced by Apple in 2019 that uses a declarative programming style. This means you can define ‘what’ to display rather than ‘how’ to draw the UI you want to show on the screen. This allows developers to accomplish more tasks with less code.

  • Intuitive Syntax: SwiftUI is based on Swift syntax, making it easy to learn.
  • Real-time Preview: You can see the UI you are developing in real-time through Xcode’s preview feature.
  • Supported on All Apple Platforms: SwiftUI can be used on iOS, macOS, watchOS, and tvOS.

2. Setting Up SwiftUI

First, you need to set up the basic environment to use SwiftUI. Download the latest version of Xcode and create a new project. Here are the steps to create a new project:

  1. Launch Xcode.
  2. Select “Create a new Xcode project”.
  3. Choose “App” and click “Next”.
  4. Enter a product name and select “SwiftUI” under Interface, then click “Next”.
  5. Select your desired save location and click “Create”.

3. Implementing Music Playback Functionality

Now, let’s implement music playback functionality using SwiftUI. You can use the `AVFoundation` framework to play audio files. Let’s proceed to the next steps:

3.1 Importing the AVFoundation Framework

import AVFoundation

3.2 Creating the AudioPlayer Class

To play music files, we create the AudioPlayer class as follows:


    class AudioPlayer: ObservableObject {
        var player: AVAudioPlayer?
        
        func playSound(sound: String, type: String) {
            if let url = Bundle.main.url(forResource: sound, withExtension: type) {
                do {
                    player = try AVAudioPlayer(contentsOf: url)
                    player?.play()
                } catch {
                    print("Failed to initialize player: \(error)")
                }
            }
        }
        
        func stopSound() {
            player?.stop()
        }
    }
    

3.3 Using in SwiftUI View


    struct ContentView: View {
        @StateObject var audioPlayer = AudioPlayer()

        var body: some View {
            VStack {
                Button("Play Music") {
                    audioPlayer.playSound(sound: "music", type: "mp3")
                }
                
                Button("Stop Music") {
                    audioPlayer.stopSound()
                }
            }
        }
    }
    

4. Implementing Music Recording Functionality

This time, we will add music recording functionality. You will need to use `AVAudioRecorder` for music recording. Follow the steps below.

4.1 Creating the Recorder Class


    class Recorder: ObservableObject {
        var audioRecorder: AVAudioRecorder?
        let audioFilename = getDocumentsDirectory().appendingPathComponent("recording.m4a")

        static func getDocumentsDirectory() -> URL {
            let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
            return paths[0]
        }

        func startRecording() {
            let recordSettings: [String: Any] = [
                AVFormatIDKey: Int32(kAudioFormatAppleLossless),
                AVSampleRateKey: 44100.0,
                AVNumberOfChannelsKey: 2,
                AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
            ]
            do {
                audioRecorder = try AVAudioRecorder(url: audioFilename, settings: recordSettings)
                audioRecorder?.record()
            } catch {
                print("Failed to start recording: \(error)")
            }
        }

        func stopRecording() {
            audioRecorder?.stop()
            audioRecorder = nil
        }
    }
    

4.2 Using in SwiftUI View


    struct RecorderView: View {
        @StateObject var recorder = Recorder()

        var body: some View {
            VStack {
                Button("Start Recording") {
                    recorder.startRecording()
                }
                
                Button("Stop Recording") {
                    recorder.stopRecording()
                }
            }
        }
    }
    

5. Enhancing UI Design

To make the UI more attractive, you can utilize various views and styles in SwiftUI. Add colors and shapes to buttons, and include text to provide descriptions of the functionality.


    Button(action: {
        audioPlayer.playSound(sound: "music", type: "mp3")
    }) {
        Text("Play Music")
            .padding()
            .background(Color.green)
            .foregroundColor(.white)
            .cornerRadius(10)
    }
    

6. Summary and Future Developments

In this post, we explored how to implement music playback and recording features in an iOS app using SwiftUI. I hope this tutorial has not only enhanced your understanding of object-oriented programming but also helped you develop practical app development skills. In the future, we could learn about ways to further personalize user interfaces and apply various audio filters.

7. References

Thank you! If you have any questions or curiosities about app development, please leave a comment, and I will respond. I wish you good luck on your development journey!