当前位置: 移动技术网 > IT编程>移动开发>IOS > iOS音乐播放器实现代码完整版

iOS音乐播放器实现代码完整版

2019年07月24日  | 移动技术网IT编程  | 我要评论

信用社员工述职报告,浩莲生财宝,绯闻女孩第六季剧情

本文实例为大家分享了ios实现音乐播放器的具体代码,供大家参考,具体内容如下

audio_queue.cpp

/*
 * this file is part of the freestreamer project,
 * (c)copyright 2011-2013 matias muhonen.
 * see the file ''license'' for using the code.
 *
 * part of the code in this file has been rewritten from
 * the audiofilestreamexample / afsclient.cpp
 * example, copyright © 2007 apple inc.
 *
 * the threadless playback has been adapted from
 * alex crichton's audiostreamer.
 */

#include "audio_queue.h"

#include <cassert>

//#define aq_debug 1

#if !defined (aq_debug)
 #define aq_trace(...) do {} while (0)
#else
 #define aq_trace(...) printf(__va_args__)
#endif

namespace astreamer {
 
typedef struct queued_packet {
 audiostreampacketdescription desc;
 struct queued_packet *next;
 char data[];
} queued_packet_t;
 
/* public */ 
 
audio_queue::audio_queue()
 : m_delegate(0),
 m_state(idle),
 m_outaq(0),
 m_fillbufferindex(0),
 m_bytesfilled(0),
 m_packetsfilled(0),
 m_buffersused(0),
 m_processedpacketssizetotal(0),
 m_processedpacketscount(0),
 m_audioqueuestarted(false),
 m_waitingonbuffer(false),
 m_queuedhead(0),
 m_queuedtail(0),
 m_lasterror(noerr)
{
 for (size_t i=0; i < aq_buffers; i++) {
  m_bufferinuse[i] = false;
 }
}
 
audio_queue::~audio_queue()
{
 stop(true);
 
 cleanup();
}
 
bool audio_queue::initialized()
{
 return (m_outaq != 0);
}
 
void audio_queue::start()
{
 // start the queue if it has not been started already
 if (m_audioqueuestarted) {
  return;
 }
   
 osstatus err = audioqueuestart(m_outaq, null);
 if (!err) {
  m_audioqueuestarted = true;
  m_lasterror = noerr;
 } else {
  aq_trace("%s: audioqueuestart failed!\n", __pretty_function__);
  m_lasterror = err;
 }
}
 
void audio_queue::pause()
{
 if (m_state == running) {
  if (audioqueuepause(m_outaq) != 0) {
   aq_trace("%s: audioqueuepause failed!\n", __pretty_function__);
  }
  setstate(paused);
 } else if (m_state == paused) {
  audioqueuestart(m_outaq, null);
  setstate(running);
 }
}
 
void audio_queue::stop()
{
 stop(true);
}

void audio_queue::stop(bool stopimmediately)
{
 if (!m_audioqueuestarted) {
  aq_trace("%s: audio queue already stopped, return!\n", __pretty_function__);
  return;
 }
 m_audioqueuestarted = false;
 
 aq_trace("%s: enter\n", __pretty_function__);

 if (audioqueueflush(m_outaq) != 0) {
  aq_trace("%s: audioqueueflush failed!\n", __pretty_function__);
 }
 
 if (stopimmediately) {
  audioqueueremovepropertylistener(m_outaq,
           kaudioqueueproperty_isrunning,
           audioqueueisrunningcallback,
           this);
 }
 
 if (audioqueuestop(m_outaq, stopimmediately) != 0) {
  aq_trace("%s: audioqueuestop failed!\n", __pretty_function__);
 }
 
 if (stopimmediately) {
  setstate(idle);
 }
 
 aq_trace("%s: leave\n", __pretty_function__);
}
 
double audio_queue::packetduration()
{
 return m_streamdesc.mframesperpacket / m_streamdesc.msamplerate;
}
 
unsigned audio_queue::timeplayedinseconds()
{
 unsigned timeplayed = 0;
 
 audiotimestamp queuetime;
 boolean discontinuity;
 
 osstatus err = audioqueuegetcurrenttime(m_outaq, null, &queuetime, &discontinuity);
 if (err) {
  goto out;
 }
 
 timeplayed = queuetime.msampletime / m_streamdesc.msamplerate;
 
out:
 return timeplayed;
}
 
unsigned audio_queue::bitrate()
{
 unsigned bitrate = 0;
 
 double packetduration = this->packetduration();
 
 if (packetduration > 0 && m_processedpacketscount > 50) {
  double averagepacketbytesize = m_processedpacketssizetotal / m_processedpacketscount;
  bitrate = 8 * averagepacketbytesize / packetduration;
 }
 
 return bitrate;
}

void audio_queue::handlepropertychange(audiofilestreamid inaudiofilestream, audiofilestreampropertyid inpropertyid, uint32 *ioflags)
{
 osstatus err = noerr;
 
 aq_trace("found property '%lu%lu%lu%lu'\n", (inpropertyid>>24)&255, (inpropertyid>>16)&255, (inpropertyid>>8)&255, inpropertyid&255);
 
 switch (inpropertyid) {
  case kaudiofilestreamproperty_readytoproducepackets:
  {
   cleanup();
   
   // the file stream parser is now ready to produce audio packets.
   // get the stream format.
   memset(&m_streamdesc, 0, sizeof(m_streamdesc));
   uint32 asbdsize = sizeof(m_streamdesc);
   err = audiofilestreamgetproperty(inaudiofilestream, kaudiofilestreamproperty_dataformat, &asbdsize, &m_streamdesc);
   if (err) {
    aq_trace("%s: error in kaudiofilestreamproperty_dataformat\n", __pretty_function__);
    m_lasterror = err;
    break;
   }
   
   // create the audio queue
   err = audioqueuenewoutput(&m_streamdesc, audioqueueoutputcallback, this, cfrunloopgetcurrent(), null, 0, &m_outaq);
   if (err) {
    aq_trace("%s: error in audioqueuenewoutput\n", __pretty_function__);
    
    if (m_delegate) {
     m_delegate->audioqueueinitializationfailed();
    }
    
    m_lasterror = err;
    break;
   }
   
   // allocate audio queue buffers
   for (unsigned int i = 0; i < aq_buffers; ++i) {
    err = audioqueueallocatebuffer(m_outaq, aq_bufsiz, &m_audioqueuebuffer[i]);
    if (err) {
     /* if allocating the buffers failed, everything else will fail, too.
      * dispose the queue so that we can later on detect that this
      * queue in fact has not been initialized.
      */
     
     aq_trace("%s: error in audioqueueallocatebuffer\n", __pretty_function__);
     
     (void)audioqueuedispose(m_outaq, true);
     m_outaq = 0;
     
     if (m_delegate) {
      m_delegate->audioqueueinitializationfailed();
     }
     
     m_lasterror = err;
     break;
    }
   }
   
   setcookiesforstream(inaudiofilestream);
   
   // listen for kaudioqueueproperty_isrunning
   err = audioqueueaddpropertylistener(m_outaq, kaudioqueueproperty_isrunning, audioqueueisrunningcallback, this);
   if (err) {
    aq_trace("%s: error in audioqueueaddpropertylistener\n", __pretty_function__);
    m_lasterror = err;
    break;
   }
   
   break;
  }
 }
}

void audio_queue::handleaudiopackets(uint32 innumberbytes, uint32 innumberpackets, const void *ininputdata, audiostreampacketdescription *inpacketdescriptions)
{
 if (!initialized()) {
  aq_trace("%s: warning: attempt to handle audio packets with uninitialized audio queue. return.\n", __pretty_function__);
  
  return;
 }
 
 // this is called by audio file stream when it finds packets of audio
 aq_trace("got data. bytes: %lu packets: %lu\n", innumberbytes, innumberpackets);
 
 /* place each packet into a buffer and then send each buffer into the audio
  queue */
 uint32 i;
 
 if (!inpacketdescriptions) {
  aq_trace("%s: notice: supplying the packet descriptions for a supposed cbr data.\n", __pretty_function__);
  
  // if no packet descriptions are supplied, assume we are dealing with cbr data
  uint32 base = innumberbytes / innumberpackets;
  audiostreampacketdescription *descriptions = new audiostreampacketdescription[innumberpackets];
  
  for (i = 0; i < innumberpackets; i++) {
   descriptions[i].mstartoffset = (base * i);
   descriptions[i].mdatabytesize = base;
   descriptions[i].mvariableframesinpacket = 0;
  }
  inpacketdescriptions = descriptions;
  
  m_cbrpacketdescriptions.push_back(descriptions);
 }
 
 for (i = 0; i < innumberpackets && !m_waitingonbuffer && m_queuedhead == null; i++) {
  audiostreampacketdescription *desc = &inpacketdescriptions[i];
  int ret = handlepacket((const char*)ininputdata + desc->mstartoffset, desc);
  if (!ret) break;
 }
 if (i == innumberpackets) {
  return;
 }
 
 for (; i < innumberpackets; i++) {
  /* allocate the packet */
  uint32 size = inpacketdescriptions[i].mdatabytesize;
  queued_packet_t *packet = (queued_packet_t *)malloc(sizeof(queued_packet_t) + size);
  
  /* prepare the packet */
  packet->next = null;
  packet->desc = inpacketdescriptions[i];
  packet->desc.mstartoffset = 0;
  memcpy(packet->data, (const char *)ininputdata + inpacketdescriptions[i].mstartoffset,
    size);
  
  if (m_queuedhead == null) {
   m_queuedhead = m_queuedtail = packet;
  } else {
   m_queuedtail->next = packet;
   m_queuedtail = packet;
  }
 }
}
 
int audio_queue::handlepacket(const void *data, audiostreampacketdescription *desc)
{
 if (!initialized()) {
  aq_trace("%s: warning: attempt to handle audio packets with uninitialized audio queue. return.\n", __pretty_function__);
  
  return -1;
 }
 
 aq_trace("%s: enter\n", __pretty_function__);
 
 uint32 packetsize = desc->mdatabytesize;
 
 /* this shouldn't happen because most of the time we read the packet buffer
  size from the file stream, but if we restored to guessing it we could
  come up too small here */
 if (packetsize > aq_bufsiz) {
  aq_trace("%s: packetsize %lli > aq_bufsiz %li\n", __pretty_function__, packetsize, aq_bufsiz);
  return -1;
 }
 
 // if the space remaining in the buffer is not enough for this packet, then
 // enqueue the buffer and wait for another to become available.
 if (aq_bufsiz - m_bytesfilled < packetsize) {
  int hasfreebuffer = enqueuebuffer();
  if (hasfreebuffer <= 0) {
   return hasfreebuffer;
  }
 } else {
  aq_trace("%s: skipped enqueuebuffer aq_bufsiz - m_bytesfilled %lu, packetsize %lli\n", __pretty_function__, (aq_bufsiz - m_bytesfilled), packetsize);
 }
 
 m_processedpacketssizetotal += packetsize;
 m_processedpacketscount++;
 
 // copy data to the audio queue buffer
 audioqueuebufferref buf = m_audioqueuebuffer[m_fillbufferindex];
 memcpy((char*)buf->maudiodata + m_bytesfilled, data, packetsize);
 
 // fill out packet description to pass to enqueue() later on
 m_packetdescs[m_packetsfilled] = *desc;
 // make sure the offset is relative to the start of the audio buffer
 m_packetdescs[m_packetsfilled].mstartoffset = m_bytesfilled;
 // keep track of bytes filled and packets filled
 m_bytesfilled += packetsize;
 m_packetsfilled++;
 
 /* maximum number of packets which can be contained in one buffer */
#define kaqmaxpacketdescs 512
 
 /* if filled our buffer with packets, then commit it to the system */
 if (m_packetsfilled >= kaqmaxpacketdescs) {
  return enqueuebuffer();
 }
 return 1;
}

/* private */
 
void audio_queue::cleanup()
{
 if (!initialized()) {
  aq_trace("%s: warning: attempt to cleanup an uninitialized audio queue. return.\n", __pretty_function__);
  
  return;
 }
 
 if (audioqueuedispose(m_outaq, true) != 0) {
  aq_trace("%s: audioqueuedispose failed!\n", __pretty_function__);
 }
 m_outaq = 0;
 m_fillbufferindex = m_bytesfilled = m_packetsfilled = m_buffersused = m_processedpacketssizetotal = m_processedpacketscount = 0;
 
 for (size_t i=0; i < aq_buffers; i++) {
  m_bufferinuse[i] = false;
 }
 
 queued_packet_t *cur = m_queuedhead;
 while (cur) {
  queued_packet_t *tmp = cur->next;
  free(cur);
  cur = tmp;
 }
 m_queuedhead = m_queuedhead = 0;
 
 for (size_t i=0; i < m_cbrpacketdescriptions.size(); i++) {
  delete[] m_cbrpacketdescriptions[i];
 }
 m_cbrpacketdescriptions.clear();
 
 m_waitingonbuffer = false;
 m_lasterror = noerr;
}
 
void audio_queue::setcookiesforstream(audiofilestreamid inaudiofilestream)
{
 osstatus err;
 
 // get the cookie size
 uint32 cookiesize;
 boolean writable;
 
 err = audiofilestreamgetpropertyinfo(inaudiofilestream, kaudiofilestreamproperty_magiccookiedata, &cookiesize, &writable);
 if (err) {
  aq_trace("error in info kaudiofilestreamproperty_magiccookiedata\n");
  return;
 }
 aq_trace("cookiesize %lu\n", cookiesize);
 
 // get the cookie data
 void* cookiedata = calloc(1, cookiesize);
 err = audiofilestreamgetproperty(inaudiofilestream, kaudiofilestreamproperty_magiccookiedata, &cookiesize, cookiedata);
 if (err) {
  aq_trace("error in get kaudiofilestreamproperty_magiccookiedata");
  free(cookiedata);
  return;
 }
 
 // set the cookie on the queue.
 err = audioqueuesetproperty(m_outaq, kaudioqueueproperty_magiccookie, cookiedata, cookiesize);
 free(cookiedata);
 if (err) {
  aq_trace("error in set kaudioqueueproperty_magiccookie");
 }
}
 
void audio_queue::setstate(state state)
{
 if (m_state == state) {
  /* we are already in this state! */
  return;
 }
 
 m_state = state;
 
 if (m_delegate) {
  m_delegate->audioqueuestatechanged(m_state);
 }
}

int audio_queue::enqueuebuffer()
{
 assert(!m_bufferinuse[m_fillbufferindex]);
 
 aq_trace("%s: enter\n", __pretty_function__);
 
 m_bufferinuse[m_fillbufferindex] = true;
 m_buffersused++;
 
 // enqueue buffer
 audioqueuebufferref fillbuf = m_audioqueuebuffer[m_fillbufferindex];
 fillbuf->maudiodatabytesize = m_bytesfilled;
 
 assert(m_packetsfilled > 0);
 osstatus err = audioqueueenqueuebuffer(m_outaq, fillbuf, m_packetsfilled, m_packetdescs);
 if (!err) {
  m_lasterror = noerr;
  start();
 } else {
  /* if we get an error here, it very likely means that the audio queue is no longer
   running */
  aq_trace("%s: error in audioqueueenqueuebuffer\n", __pretty_function__);
  m_lasterror = err;
  return 1;
 }
 
 // go to next buffer
 if (++m_fillbufferindex >= aq_buffers) {
  m_fillbufferindex = 0; 
 }
 // reset bytes filled
 m_bytesfilled = 0;
 // reset packets filled
 m_packetsfilled = 0;
 
 // wait until next buffer is not in use
 if (m_bufferinuse[m_fillbufferindex]) {
  aq_trace("waiting for buffer %lu\n", m_fillbufferindex);
  
  if (m_delegate) {
   m_delegate->audioqueueoverflow();
  }
  m_waitingonbuffer = true;
  return 0;
 }
 
 return 1;
}
 
int audio_queue::findqueuebuffer(audioqueuebufferref inbuffer)
{
 for (unsigned int i = 0; i < aq_buffers; ++i) {
  if (inbuffer == m_audioqueuebuffer[i]) {
   aq_trace("findqueuebuffer %i\n", i);
   return i;
  }
 }
 return -1;
}
 
void audio_queue::enqueuecacheddata()
{
 assert(!m_waitingonbuffer);
 assert(!m_bufferinuse[m_fillbufferindex]);
 
 /* queue up as many packets as possible into the buffers */
 queued_packet_t *cur = m_queuedhead;
 while (cur) {
  int ret = handlepacket(cur->data, &cur->desc);
  if (ret == 0) {
   break; 
  }
  queued_packet_t *next = cur->next;
  free(cur);
  cur = next;
 }
 m_queuedhead = cur;
 
 /* if we finished queueing all our saved packets, we can re-schedule the
  * stream to run */
 if (cur == null) {
  m_queuedtail = null;
  if (m_delegate) {
   m_delegate->audioqueueunderflow();
  }
 }
}
 
// this is called by the audio queue when it has finished decoding our data. 
// the buffer is now free to be reused.
void audio_queue::audioqueueoutputcallback(void *inclientdata, audioqueueref inaq, audioqueuebufferref inbuffer)
{
 audio_queue *audioqueue = static_cast<audio_queue*>(inclientdata); 
 unsigned int bufindex = audioqueue->findqueuebuffer(inbuffer);
 
 assert(audioqueue->m_bufferinuse[bufindex]);
 
 audioqueue->m_bufferinuse[bufindex] = false;
 audioqueue->m_buffersused--;
 
 if (audioqueue->m_buffersused == 0 && !audioqueue->m_queuedhead && audioqueue->m_delegate) {
  audioqueue->m_delegate->audioqueuebuffersempty();
 } else if (audioqueue->m_waitingonbuffer) {
  audioqueue->m_waitingonbuffer = false;
  audioqueue->enqueuecacheddata();
 }
}

void audio_queue::audioqueueisrunningcallback(void *inclientdata, audioqueueref inaq, audioqueuepropertyid inid)
{
 audio_queue *audioqueue = static_cast<audio_queue*>(inclientdata);
 
 aq_trace("%s: enter\n", __pretty_function__);
 
 uint32 running;
 uint32 output = sizeof(running);
 osstatus err = audioqueuegetproperty(inaq, kaudioqueueproperty_isrunning, &running, &output);
 if (err) {
  aq_trace("%s: error in kaudioqueueproperty_isrunning\n", __pretty_function__);
  return;
 }
 if (running) {
  aq_trace("audio queue running!\n");
  audioqueue->setstate(running);
 } else {
  audioqueue->setstate(idle);
 }
} 
 
} // namespace astreamer

audio_stream.h

/*
 * this file is part of the freestreamer project,
 * (c)copyright 2011-2013 matias muhonen.
 * see the file ''license'' for using the code.
 */

#ifndef astreamer_audio_stream_h
#define astreamer_audio_stream_h

#import "http_stream.h"
#include "audio_queue.h"

#include <audiotoolbox/audiotoolbox.h>
#include <string>

namespace astreamer {
 
enum audio_stream_error {
 as_err_open = 1,   // cannot open the audio stream
 as_err_stream_parse = 2, // parse error
 as_err_network = 3  // network error
};
 
class audio_stream_delegate;
 
class audio_stream : public http_stream_delegate, public audio_queue_delegate { 
public:
 audio_stream_delegate *m_delegate;
 
 enum state {
  stopped,
  buffering,
  playing,
  seeking,
  failed,
  end_of_file
 };
 
 audio_stream();
 virtual ~audio_stream();
 
 void open();
 void close();
 void pause();
 
 unsigned timeplayedinseconds();
 unsigned durationinseconds();
 void seektotime(unsigned newseektime);
 
 void seturl(cfurlref url);
 void setstrictcontenttypechecking(bool strictchecking);
 void setdefaultcontenttype(std::string& defaultcontenttype);
 
 state state();
 
 /* audio_queue_delegate */
 void audioqueuestatechanged(audio_queue::state state);
 void audioqueuebuffersempty();
 void audioqueueoverflow();
 void audioqueueunderflow();
 void audioqueueinitializationfailed();
 
 /* http_stream_delegate */
 void streamisreadyread();
 void streamhasbytesavailable(uint8 *data, uint32 numbytes);
 void streamendencountered();
 void streamerroroccurred();
 void streammetadataavailable(std::map<cfstringref,cfstringref> metadata);

private:
 
 audio_stream(const audio_stream&);
 audio_stream& operator=(const audio_stream&);
 
 bool m_httpstreamrunning;
 bool m_audiostreamparserrunning;
 
 size_t m_contentlength;
 
 state m_state;
 http_stream *m_httpstream;
 audio_queue *m_audioqueue;
 
 audiofilestreamid m_audiofilestream; // the audio file stream parser
 
 sint64 m_dataoffset;
 unsigned m_seektime;
 
 bool m_strictcontenttypechecking;
 std::string m_defaultcontenttype;
 
 size_t contentlength();
 void closeandsignalerror(int error);
 void setstate(state state);
 
 static void propertyvaluecallback(void *inclientdata, audiofilestreamid inaudiofilestream, audiofilestreampropertyid inpropertyid, uint32 *ioflags);
 static void streamdatacallback(void *inclientdata, uint32 innumberbytes, uint32 innumberpackets, const void *ininputdata, audiostreampacketdescription *inpacketdescriptions);
 
 audiofiletypeid audiostreamtypefromcontenttype(std::string contenttype); 
};
 
class audio_stream_delegate {
public:
 virtual void audiostreamstatechanged(audio_stream::state state) = 0;
 virtual void audiostreamerroroccurred(int errorcode) = 0;
 virtual void audiostreammetadataavailable(std::map<cfstringref,cfstringref> metadata) = 0;
}; 

} // namespace astreamer

#endif // astreamer_audio_stream_h

更多源码请点击下载:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

  • ios uicollectionview实现横向滚动

    现在使用卡片效果的app很多,之前公司让实现一种卡片效果,就写了一篇关于实现卡片的文章。文章最后附有demo实现上我选择了使用uicollectionview ... [阅读全文]
  • iOS UICollectionView实现横向滑动

    本文实例为大家分享了ios uicollectionview实现横向滑动的具体代码,供大家参考,具体内容如下uicollectionview的横向滚动,目前我使... [阅读全文]
  • iOS13适配深色模式(Dark Mode)的实现

    iOS13适配深色模式(Dark Mode)的实现

    好像大概也许是一年前, mac os系统发布了深色模式外观, 看着挺刺激, 时至今日用着也还挺爽的终于, 随着iphone11等新手机的发售, ios 13系统... [阅读全文]
  • ios 使用xcode11 新建项目工程的步骤详解

    ios 使用xcode11 新建项目工程的步骤详解

    xcode11新建项目工程,新增了scenedelegate这个类,转而将原appdelegate负责的对ui生命周期的处理担子接了过来。故此可以理解为:ios... [阅读全文]
  • iOS实现转盘效果

    本文实例为大家分享了ios实现转盘效果的具体代码,供大家参考,具体内容如下demo下载地址: ios转盘效果功能:实现了常用的ios转盘效果,轮盘抽奖效果的实现... [阅读全文]
  • iOS开发实现转盘功能

    本文实例为大家分享了ios实现转盘功能的具体代码,供大家参考,具体内容如下今天给同学们讲解一下一个转盘选号的功能,直接上代码直接看viewcontroller#... [阅读全文]
  • iOS实现轮盘动态效果

    本文实例为大家分享了ios实现轮盘动态效果的具体代码,供大家参考,具体内容如下一个常用的绘图,主要用来打分之类的动画,效果如下。主要是ios的绘图和动画,本来想... [阅读全文]
  • iOS实现九宫格连线手势解锁

    本文实例为大家分享了ios实现九宫格连线手势解锁的具体代码,供大家参考,具体内容如下demo下载地址:效果图:核心代码://// clockview.m// 手... [阅读全文]
  • iOS实现卡片堆叠效果

    本文实例为大家分享了ios实现卡片堆叠效果的具体代码,供大家参考,具体内容如下如图,这就是最终效果。去年安卓5.0发布的时候,当我看到安卓全新的material... [阅读全文]
  • iOS利用余弦函数实现卡片浏览工具

    iOS利用余弦函数实现卡片浏览工具

    本文实例为大家分享了ios利用余弦函数实现卡片浏览工具的具体代码,供大家参考,具体内容如下一、实现效果通过拖拽屏幕实现卡片移动,左右两侧的卡片随着拖动变小,中间... [阅读全文]
验证码:
移动技术网